<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm">
      <el-card style="margin-top: -30px">
        <el-button-group style="display: flex">
          <el-button type="primary" @click.native="submitUpload()" style="margin: 0 60px 10px auto; height: 35px"
                     :loading="subLoading"
          >提交
          </el-button>
        </el-button-group>
        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>组件路径：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="menuKey">
              <el-input v-model="formData.menuKey" auto-complete="off" :disabled="formData.auditStatus == 1"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>菜单名称：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="menuName">
              <el-input v-model="formData.menuName" auto-complete="off" :disabled="formData.auditStatus == 1"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>日期：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="vailDate">

              <el-date-picker
                v-model="formData.updateTime"
                type="datetime"
                placeholder="请选择日期"
                clearable
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 90%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>备注：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="remark">
              <el-input v-model="formData.remark" auto-complete="off" type="textarea" autosize></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>状态：</span>
            </div>
          </el-col>
          <el-col :span="8" type="flex">
            <el-form-item prop="userFlag">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>

              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>文件：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-upload
                :disabled="formData.auditStatus == 1"
                class="upload-demo"
                ref="upload"
                :action="this.uploadUrl"
                :on-preview="uploadHandlePreview"
                :on-remove="uploadHandleRemove"
                :limit="1"
                :headers="headers"
                :on-exceed="uploadHandleExceed"
                accept=".jpg,.png,.pdf,.doc"
                :on-change="uploadOnchange"
                :on-success="uploadHandleSuccess"
                :on-error="uploadHandleError"
                :file-list="fileList"
                :data="{type:'image2'}"
                :auto-upload="true"
              >
                <el-button slot="trigger" size="small" type="primary" :disabled="formData.auditStatus == 1">
                  {{ choiceFile }}
                </el-button>
                <div>只能上传 jpg,png,pdf,doc 文件，且不超过 3 MB</div>
              </el-upload>
              <el-button type="primary" size="mini" icon="search" @click="toViewCompanyCert"
                         style="text-align:right" v-show="formData.id!=null"
              >文件预览
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

  </div>
</template>

<script>
import draggable from 'vuedraggable'
import store from '@/store'
import { insertCompanyCert, updateCompanyCert } from '@/api/purchase/companyCert'
import { insertMenuHelp, updateMenuHelp } from '@/api/system/sysMenuHelp'
import { updateInv } from '@/api/auth/authAdmin'
import { isBlank } from '@/utils/strUtil'

export default {
  name: 'addhelpSettings',
  props: {
    closeDialog: {
      type: Function,
      required: true
    },
    from: {
      type: Object,
      required: true
    },
    formName: {
      type: Object,
      required: true
    }

  },
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      code: '',
      formData: {
        type: 0,
        updateTime: null,
        remark: null,
        menuKey: null,
        menuName: null,
        filePath: null,
        status: null
      },
      formRules: {
        menuKey: [
          { required: true, message: '请输入组件路径', trigger: 'blur' }
        ],
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ]
      },
      loading: false,
      subLoading: false,
      uploadUrl: '',
      fileList: [],
      headers: {},
      choiceFile: '选取文件'

    }
  },
  components: {
    draggable
  },
  methods: {
    submitUpload() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.$isBlank(this.formData.menuKey)) {
            this.$message.error('组件路径不能为空！')
            return
          }
          if (this.$isBlank(this.formData.menuName)) {
            this.$message.error('菜单名称不能为空！')
            return
          }
          this.subLoading = true
          if (this.formName == 2) {
            updateMenuHelp(this.formData).then((res) => {
              this.subLoading = false
              if (res.code === 20000) {
                this.$message.success('修改状态成功')
                this.closeDialog()
              }

            })
          }
          insertMenuHelp(this.formData).then((res) => {
            this.subLoading = false
            if (res.code === 20000) {
              this.$message.success('添加成功')
              this.closeDialog()
            }

          })
        }
      })

    },

    uploadHandleRemove(file, fileList) {
      console.log(file, fileList)
    },
    uploadHandlePreview(file) {
      console.log(file)
      console.log(this.fileList)
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    uploadOnchange(file, fileList) {
      let fileName = file.name
      let uid = file.uid
      let pos = fileName.lastIndexOf('.')
      let lastName = fileName.substring(pos, fileName.length)
      if (lastName.toLowerCase() !== '.jpg' && lastName.toLowerCase() !== '.png' && lastName.toLowerCase() !== '.doc' && lastName.toLowerCase() !== '.pdf') {
        this.$message.error('上传文件只能是 jpg,png,doc,pdf 格式')
        for (let i = 0; i < fileList.length; i++) {//从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 2 <= 1
      if (!isLt) {
        this.$message.error('上传文件大小不能超过 2MB')
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt
    },
    uploadHandleSuccess(response, file, fileList) {
      if (response.code === 20000) {
        this.formData.filePath = response.data.name

      } else {
        this.$message.error('文件上传失败：' + response.message)
      }
    },
    uploadHandleError() {

    },

    toViewCompanyCert() {
      this.certFileUrl = this.BASE_URL + '/udiwms/image/register/file/getImage?type=image2&name='
      window.open(this.certFileUrl + this.formData.filePath)
    }
  },
  filters: {},
  mounted() {
    document.body.ondrop = function(event) {
      event.preventDefault()
      event.stopPropagation()
    }
  },
  created() {
    this.uploadUrl = this.BASE_URL + '/udiwms/upload/register/file'
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token
    }

    if (isBlank(this.from.id)) {

      this.formData = {}
    } else {
      //编辑页面
      this.formData = this.from
    }
    if (this.formData.filePath != null) {
      this.choiceFile = '更换文件'
    } else {
      this.choiceFile = '选取文件'
    }
  }
}
</script>
<style scoped>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

</style>



