<template>
  <div>
    <Modal v-model="showEditModal" v-drag :mask-closable="false" width="700" class="zIndex-1100">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form
          id="edit-form-cert"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="90"
          inline
        >
          <Form-item label="名称" prop="name" class="width-48">
            <Input v-model="formObj.name" placeholder="请输入名称" />
          </Form-item>
          <Form-item label="证件号" prop="licenseNumber" class="width-48">
            <Input v-model="formObj.licenseNumber" placeholder="请输入证件号" />
          </Form-item>
          <Form-item label="发证机关" prop="issuingAuthority" class="width-48">
            <Input v-model="formObj.issuingAuthority" placeholder="请输入发证机关" />
          </Form-item>
          <Form-item label="级别" prop="level" class="width-48">
            <Input v-model="formObj.level" placeholder="请输入级别" />
          </Form-item>
          <Form-item label="开始时间" prop="startDate" class="width-48">
            <Date-picker
              v-model="formObj.startDate"
              type="date"
              placeholder="开始时间"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="有效期" prop="endDate" class="width-48">
            <Date-picker
              v-model="formObj.endDate"
              type="date"
              placeholder="有效期"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="预警期" prop="warningPeriod" class="width-48">
            <InputNumber
              v-model.number="warningPeriod"
              placeholder="请输入预警期"
              min="1"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <Input v-model="formObj.remark" placeholder="请输入备注" /></Input>
          </Form-item>
          <input type="hidden" name="staffId">
        </Form>
      </div>
      <div slot="footer">
        <Button type="ghost" style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button type="primary" @click="_ok">
          提交
        </Button>
      </div>
    </Modal>
    <Modal v-model="visible" title="查看图片" class="zIndex-1200">
      <img v-if="visible" :src="fileUrl" style="width: 100%">
    </Modal>
    <!--弹框-->
    <ModalConfirm
      ref="confirmModal"
      :content="modalContent"
      :btn-modal-list="btnModalList"
      @on-result-change="_modalResult"
    />
    <ModalConfirm
      ref="confirmModalDownload"
      :content="content"
      :btn-modal-list="btnModalList"
      @on-result-change="_downloadResult"
    />
  </div>
</template>
<script>
/**
 * 添加编辑人员证书表
 */
import global from '../../../../api/config'
import ModalConfirm from '../../../../components/base/ModalConfirm'
import { staffProfessional } from '../../../../api'
export default {
  components: { ModalConfirm },
  data() {
    return {
      id: '',
      modalTitle: '',
      formObj: {
        name: '',
        licenseNumber: '',
        issuingAuthority: '',
        level: '',
        startDate: '',
        endDate: '',
        remark: ''
      },
      warningPeriod: 1,
      ruleValidate: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        startDate: [
          {
            required: true,
            message: '开始时间不能为空',
            trigger: 'change',
            type: 'date'
          }
        ],
        endDate: [
          {
            required: true,
            message: '有效期不能为空',
            trigger: 'change',
            type: 'date'
          }
        ],
        licenseNumber: [
          { required: true, message: '证件号不能为空', trigger: 'blur' }
        ]
        // warningPeriod: [{required: true, validator:valWarning,trigger: 'blur', type: 'number'}],
      },
      showEditModal: false,
      fileAction: global.baseURL + '/res/v1/staff_professional/uploadFile',
      fileObj: {
        relId: 0,
        type: 2
      },
      fileList: [],
      visible: false,
      fileUrl: '',
      fileIds: [],
      modalContent: '',
      btnModalList: [
        { type: '', name: '取消' },
        { type: 'primary', name: '确定' }
      ],
      fileDel: '',
      fileDownload: '',
      content: '确认下载该文件?'
    }
  },
  methods: {
    _closeModal() {
      this.$refs.confirmModal._closeModal()
    },
    _modalResult(msg) {
      switch (msg) {
        case '取消':
          this._closeModal()
          break
        case '确定':
          this._deteleFile(this.fileDel)
          break
      }
    },
    _downloadResult(msg) {
      switch (msg) {
        case '取消':
          this._closeModal()
          break
        case '确定':
          this._downloadOk(this.fileDownload)
          break
      }
    },
    _resultChange(msg) {
      this.formObj = {}
      this.showEditModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form-cert')
          data.name = this.formObj.name
          data.licenseNumber = this.formObj.licenseNumber
          data.startDate = this.$dateformat(
            this.formObj.startDate,
            'yyyy-mm-dd'
          )
          data.endDate = this.$dateformat(this.formObj.endDate, 'yyyy-mm-dd')
          data.issuingAuthority = this.formObj.issuingAuthority
          data.level = this.formObj.level
          data.warningPeriod = this.warningPeriod
          data.remark = this.formObj.remark
          if (this.$string(this.id).isEmpty()) {
            if (this.fileList.length > 0) {
              this.fileList.forEach(item => {
                this.fileIds.push(item.id)
              })
              data.fileIds = this.fileIds.join(',')
            }
            // 添加
            // this.$store.dispatch('LmsStaffProfessional/add', data).then(() => {
            //   this._resultChange('添加成功!')
            // })
            this._save(data)
          } else {
            // 编辑
            // this.$store
            //   .dispatch('LmsStaffProfessional/edit', {
            //     id: this.formObj.id,
            //     obj: data
            //   })
            //   .then(() => {
            //     this._resultChange('编辑成功!')
            //   })
            this._edit({ id: this.formObj.id, obj: data })
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    // 添加保存
    _save: async function(data) {
      // 添加
      const result = await staffProfessional.add(data)
      this._resultChange(result, '添加成功')
    },
    // 编辑保存
    _edit: async function(data) {
      // 添加
      const result = await staffProfessional.edit(data)
      // this._resultChange(result, '编辑成功')
      if (result) {
        this.formObj = {}
        this.showEditModal = false
        this.$Message.success('编辑成功')
        this.$emit('on-result-change')
      }
    },
    _cancel() {
      this.showEditModal = false
    },
    _open(staffId, formObj) {
      $('input[name=staffId]').val(staffId)
      this.showEditModal = true
      this.$refs.formObj.resetFields()
      if (formObj === '' || undefined === formObj) {
        this.id = ''
        this.formObj = {}
        this.fileList = []
        this.modalTitle = '添加职称/证书'
        // this._getWarning();
      } else {
        this.id = formObj.id
        this.formObj = formObj
        this.fileList = formObj.fileList
        this.fileObj.relId = formObj.id
        if (formObj.warningPeriod !== undefined) {
          this.warningPeriod = formObj.warningPeriod
        } else {
          this.warningPeriod = 1
        }
        this.formObj.startDate = formObj.startDate
          ? this.$dateformat(formObj.startDate, 'yyyy-mm-dd')
          : ''
        this.formObj.endDate = formObj.endDate
          ? this.$dateformat(formObj.endDate, 'yyyy-mm-dd')
          : ''
        this.modalTitle = '编辑职称/证书'
      }
    },
    _getWarning() {
      this.$store.dispatch('LmsBaseDict/getItem', '证书预警期').then(() => {
        const result = this.$store.state.LmsBaseDict.item
        this.formObj.warningPeriod = result[0].name
      })
    },
    /* 附件 start */
    _handleView(data) {
      this.fileUrl = data.fileUrl
      if (
        this.fileUrl.indexOf('jpg') > -1 ||
        this.fileUrl.indexOf('png') > -1 ||
        this.fileUrl.indexOf('jpeg') > -1
      ) {
        this.visible = true
      } else {
        this.$Message.warning({
          content: '非图片文件无法查看，请下载查看',
          duration: 3
        })
        this.visible = false
      }
    },
    _downloadFile(file) {
      // 下载文件
      this.fileDownload = file
      this.$refs.confirmModalDownload._openModal()
    },
    _downloadOk(file) {
      const url =
        global.baseURL + '/res/v1/staff_professional/downLoadFile?id=' + file.id
      window.open(url)
      this.$refs.confirmModalDownload._closeModal()
    },
    _deteleFile(file) {
      const fileList = this.fileList
      const data = {
        id: file.id,
        type: 2
      }
      this.$store
        .dispatch('LmsStaffProfessional/deleteFileById', data)
        .then(() => {
          if (this.$store.state.LmsStaffProfessional.success) {
            this.fileList.splice(fileList.indexOf(file), 1)
            this._closeModal()
            this.$Message.success('删除成功！')
          }
        })
    },
    _handleRemove(file, content) {
      // 删除
      this.fileDel = file
      this.modalContent = content || '确定删除该文件？'
      this.$refs.confirmModal._openModal()
    },
    _handleBeforeUpload() {},
    _handleSuccess(response, file, fileList) {
      if (response.success) {
        this.$Message.success('上传成功！')
        this.fileList.push(response.data)
      } else {
        this.$Message.error('上传失败！')
      }
    }
    /* 附件 end */
  }
}
</script>
