<template>
  <div>
    <Modal v-model="showModal" :mask-closable="false" width="1000">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="100"
          inline
        >
          <Form-item label="问题" prop="question" style="width: 97.6%;">
            <editor ref="editorQuestion" v-model="formObj.question" @on-result-change="_editorQuestion" />
          </Form-item>
          <Form-item label="纠正/预防措施" prop="method" style="width: 97.6%;">
            <editor ref="editorMethod" v-model="formObj.method" @on-result-change="_editorMethod" />
          </Form-item>
          <Form-item label="截止日期" prop="expiryDate" class="width-48">
            <Date-picker
              v-model="formObj.expiryDate"
              name="expiryDate"
              type="date"
              placeholder="请输入截止日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" />
          </Form-item>
          <Form-item label="附件上传" style="width: 98.6%;">
            <div v-for="item in formObj.lmsFrameFileList" :key="item.id" class="file-upload-list">
              <div>
                <div class="file-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="_handleView(item)" />
                  <Icon type="ios-cloud-download-outline" @click.native="_downloadFile(item)" />
                  <Icon type="ios-trash-outline" @click.native="_handleRemove(item)" />
                </div>
              </div>
              {{ item.orginName }}
            </div>
            <Upload
              :show-upload-list="false"
              :with-credentials="true"
              :on-success="_handleSuccess"
              :before-upload="_handleBeforeUpload"
              type="drag"
              :action="fileAction"
              :data="fileData"
              style="display: inline-block;width:100px;"
            >
              <div style="width: 100px;height:100px;line-height: 100px;">
                <Icon type="ios-cloud-upload" size="20" />
              </div>
            </Upload>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button type="success" @click="_ok(0)">
          草稿
        </Button>
        <Button type="primary" @click="_ok(1)">
          提交
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
/**
 * 添加编辑不符合项登记
 */
import { frameUnconformImprove } from '../../../../api'
import global from '../../../../api/config'
import editor from '../../../../components/base/editor'

export default {
  components: {
    editor
  },
  data() {
    return {
      id: '',
      modalTitle: '',
      formObj: {
        id: '',
        question: '',
        method: '',
        expiryDate: '',
        remark: '',
        lmsFrameFileList: []
      },
      fileAction: global.baseURL + '/res/v1/frame_unconform_improve/uploadFile',
      fileData: {
        id: ''
      },
      ruleValidate: {},
      showModal: false
    }
  },
  methods: {
    _editorQuestion(data) {
      this.formObj.question = data.content
    },
    _editorMethod(data) {
      this.formObj.method = data.content
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$Message.success(msg)
        this.$emit('on-result-change')
      }
    },
    _ok(status) {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          this.$extend(data, {
            status: status,
            question: this.formObj.question,
            method: this.formObj.method
          })
          this._save(data)
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await frameUnconformImprove.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await frameUnconformImprove.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功!')
      }
    },
    _cancel() {
      this.showModal = false
    },
    _open(formObj, msg) {
      this.showModal = true
      this.$refs.formObj.resetFields()
      if (this.$string(formObj).isEmpty()) {
        this.id = ''
        this.$refs.editorQuestion._initData()
        this.$refs.editorMethod._initData()
        this.modalTitle = '添加改进/纠正/预防措施'
        this._getFileList()
      } else if (msg === 'copy') {
        this.id = ''
        this.formObj = formObj
        this.formObj.expiryDate = formObj.expiryDate
          ? new Date(formObj.expiryDate)
          : ''
        this.fileData.id = formObj.id
        this.$refs.editorQuestion._initData(this.formObj.question)
        this.$refs.editorMethod._initData(this.formObj.method)
        this.modalTitle = '复制改进/纠正/预防措施'
      } else {
        this.id = formObj.id
        this.formObj = formObj
        this.formObj.expiryDate = formObj.expiryDate
          ? new Date(formObj.expiryDate)
          : ''
        this.fileData.id = formObj.id
        this.$refs.editorQuestion._initData(this.formObj.question)
        this.$refs.editorMethod._initData(this.formObj.method)
        this.modalTitle = '编辑改进/纠正/预防措施'
      }
    },
    _getFileList: async function() {
      this.formObj.lmsFrameFileList = []
      const result = await frameUnconformImprove.getTemp()
      this.fileData.id = result.id
      if (!this.$string(result.lmsFrameFileList).isEmpty()) {
        this.formObj.lmsFrameFileList = result.lmsFrameFileList
      }
    },
    _handleBeforeUpload(file) {},
    _handleSuccess(response, file, fileList) {
      if (response.success) {
        this.$Message.success('上传成功！')
        this.formObj.lmsFrameFileList.push(response.data)
      } else {
        this.$Message.error('上传失败！')
      }
    },
    _handleView(data) {
      this.filePath = data.filePath
      const index1 = this.filePath.lastIndexOf('.')
      const index2 = this.filePath.length
      const suffix = this.filePath.substring(index1 + 1, index2) // 后缀名
      if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpeg') {
        this.visible = true
      } else {
        this.visible = false
      }
    },
    _downloadFile(file) {
      // 下载文件
      this.$Modal.confirm({
        title: '提示',
        content: '确定要下载？',
        onOk: () => {
          const url = 'https://obs.myhwclouds.com/lims/' + file.filePath
          window.open(url)
        }
      })
    },
    _handleRemove(file) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除文件？',
        onOk: () => {
          this._removeFile(file)
        }
      })
    },
    _removeFile: async function(file) {
      const result = await frameUnconformImprove.deleteFileById(file.id)
      if (result) {
        const fileList = this.formObj.lmsFrameFileList
        this.formObj.lmsFrameFileList.splice(fileList.indexOf(file), 1)
        this.$Message.success('删除成功！')
      }
    }
  }
}
</script>
