<template>
  <div>
    <Modal v-model="showModalHandleApply" :mask-closable="false" width="500">
      <p slot="header">处理申请</p>
      <div>
        <Form ref="formObj" :id="formId" :model="formObj" :rules="ruleValidate" :label-width="90" inline>
          <Form-item label="申请日期:" prop="applyHandleTime" style="width:100%">
            <Date-picker v-model="formObj.applyHandleTime" :editable="false" name="applyHandleTime"
                         type="date" placeholder="请选择申请日期" style="width: 100%;"
            ></Date-picker>
          </Form-item>
          <Form-item label="申请人:" prop="applyHandler" style="width:100%">
            <Input v-model="formObj.applyHandler" @click.native="_selectPerson()" name="applyHandler" readonly></Input>
          </Form-item>
          <Form-item label="处理方式:" style="width:100%">
            <el-select v-model="formObj.handleWay" name="handleWay" placeholder="请选择"
                       size="small"
                       style="width:100%"
                       clearable>
              <el-option
                v-for="item in handleWayList"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </Form-item>
          <Form-item label="处理原因" prop="applyRemark" style="width:100%">
            <Input :rows="3" v-model="formObj.applyRemark" placeholder="请输入处理原因" type="textarea" name="applyRemark"/>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" @on-result-change="_footerResult" :footer="footerList"></modal-footer>
      </div>
    </Modal>
    <AssignPerson ref="personModal" @on-result-change="_assignBackData"></AssignPerson>
  </div>
</template>
<script>
import Global from '../../../api/config'
import AssignPerson from '../../../components/user-info-single/assignPerson'
import { soilSample } from '../../../api'
export default {
  components: { AssignPerson },
  data() {
    return {
      lengthLimitList: [{ key: 'handleQuantity', title: '样品处理数量' }],
      ids: [], // 委托ids
      showModalHandleApply: false,
      formObj: {
        id: '',
        applyHandleTime: new Date(),
        applyHandler: '',
        applyHandlerId: '',
        handleBatch: '',
        retentionTime: '',
        applyRemark: '',
        lmsEquipFiles: [],
        handleWay: '',
        handleQuantity: '',
        sampleUnit: ''
      },
      applyId: 0,
      ruleValidate: {},
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '提交', type: 'primary' }
      ],
      visible: false,
      fileAction: Global.baseURL + '/food/v1/sample_handle_apply/uploadFile',
      fileData: {
        id: 0,
        name: ''
      },
      formId: '',
      handleWayList: [
        {
          name: '到期处置'
        },
        {
          name: '立即处置'
        }
      ],
      imgSrc: ''
    }
  },
  mounted() {
    // this._dicSearch()
  },
  methods: {
    _selectPerson() {
      this.$refs.personModal._openGoup('申请人', 'itemTree')
    },
    _assignBackData(data) {
      this.formObj.applyHandler = data.realname
      this.formObj.applyHandlerId = data.id
    },
    // 从字典中查询类别
    _dicSearch() {
      this.$store.dispatch('LmsBaseDict/getItem', '样品处理方式').then(() => {
        const result = this.$store.state.LmsBaseDict.item
        this.handleWayList = result
      })
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '提交':
          this._ok()
          break
      }
    },
    _open(data) {
      this.ids = []
      this.applyId = 0
      this.fileData.id = 0
      this.formObj = this.$resetFields(this.formObj)
      // this._getRetention(data)
      // this._getSampleBatch(data)
      this.$refs.footerModal._hideLoading()
      this.ids = data
      this.formObj.lmsEquipFiles = []
      this.showModalHandleApply = true
      this.formObj.applyHandler = Global.getUserInfo().realname
      this.formObj.applyHandlerId = Global.getUserInfo().id
      this.formId = 'handleApplyEditForm' + this.$randomCode()
      this.formObj.applyHandleTime = new Date()
    },
    _getSampleBatch(data) {
      this.formObj.handleBatch = data.length
    },
    // 计算存储期限
    _getRetention(data) {
      const handleQuantityList = []
      const sampleUnitList = []
      let lastTime = ''
      const ids = []
      for (let i = 0; i < data.length; i++) {
        ids.push(data[i].id)

        // 样品处理数量和单位
        handleQuantityList.push(data[i].handleQuantity)
        sampleUnitList.push(data[i].sampleUnit)

        if (lastTime === '') {
          lastTime = data[i].endDate
        } else if (lastTime !== '' && lastTime < data[i].endDate) {
          lastTime = data[i].endDate
        }
      }
      this.ids = ids
      this.formObj.retentionTime = this.$dateformat(lastTime, 'yyyy-mm-dd')

      // 若勾选的样品处理数量、单位一样则显示
      // 通过for循环来判断数组的每一元素(若有不重复的，则返回false)
      this.formObj.handleQuantity =
        this.$duplicates(handleQuantityList) && handleQuantityList.length > 0
          ? handleQuantityList[0]
          : ''
      this.formObj.sampleUnit =
        this.$duplicates(sampleUnitList) && sampleUnitList.length > 0
          ? sampleUnitList[0]
          : ''
    },
    // 附件
    _handleView(data) {
      const filePath = data.filePath
      const index1 = filePath.lastIndexOf('.')
      const index2 = filePath.length
      const suffix = filePath.substring(index1 + 1, index2) // 后缀名
      if (
        suffix.toLowerCase() === 'png' ||
        suffix.toLowerCase() === 'jpg' ||
        suffix.toLowerCase() === 'jpeg'
      ) {
        this.visible = true
        this.imgSrc =
          Global.baseURL +
          '/food/v1/sample_handle_apply_attachment/view' +
          '?id=' +
          data.id +
          '&objectKey=' +
          data.filePath
      } else {
        this.$Message.warning({
          content: '非图片文件无法查看，请下载查看',
          duration: 3
        })
        this.visible = false
      }
    },
    // 下载文件
    _downloadFile(file) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定要下载？',
        onOk: () => {
          const url =
            Global.baseURL +
            '/food/v1/sample_handle_apply/downLoadFile?id=' +
            file.id
          window.open(url)
        }
      })
    },
    _handleSuccess(response, file, fileList) {
      if (response.success) {
        this.fileData.id = response.data.applyId
        this.applyId = response.data.applyId
        this.$Message.success('上传成功!')
        this.formObj.lmsEquipFiles.push(response.data)
      } else {
        this.$Message.error('上传失败!')
      }
    },
    _handleBeforeUpload(file) {},
    // 删除文件
    _handleRemove(file) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除文件？',
        onOk: () => {
          const fileList = this.formObj.lmsEquipFiles
          this.$store
            .dispatch('FoodSampleHandleApplyAttachment/deleteByIds', file.id)
            .then(() => {
              if (this.$store.state.FoodSampleHandleApplyAttachment.success) {
                this.formObj.lmsEquipFiles.splice(fileList.indexOf(file), 1)
                this.$Message.success('删除成功！')
              }
            })
        }
      })
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize(this.formId)
          data.applyHandlerId = this.formObj.applyHandlerId
          data.ids = this.ids.join(',')
          console.log(data)
          this._submitDispose(data)
          // data.handleBatch = this.formObj.handleBatch
          // data.id = this.applyId
          // data.handleWay = this.formObj.handleWay
          // data.applyHandler = this.formObj.applyHandler
          // data.handleQuantity = this.formObj.handleQuantity
          // // let returnData = {ids: this.ids, obj: data};
          // this.$extend(data, { backupIds: this.ids.join(',') })
          // if (this.$lengthLimitVal(this.lengthLimitList, data) === false) {
          //   this._hideLoading()
          //   return
          // }
          // this.$store
          //   .dispatch('FoodSampleHandleApply/handleApplySubmit', data)
          //   .then(() => {
          //     if (this.$store.state.FoodSampleHandleApply.success) {
          //       this._cancel()
          //       this.$Message.success('提交成功')
          //       this.$emit('on-result-change')
          //     } else {
          //       this.$refs.footerModal._hideLoading()
          //     }
          //   })
        } else {
          this.$Message.error('表单验证失败!')
          this.$refs.footerModal._hideLoading()
        }
      })
    },
    _submitDispose: async function(data) {
      const result = await soilSample.appleHandle(data)
      if (result) {
        this._resultChange('提交成功')
      }
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this.showModalHandleApply = false
      this.$emit('on-result-change')
    },
    _cancel() {
      this.showModalHandleApply = false
      this.$refs.footerModal._hideLoading()
    }
  }
}
</script>
<style scoped>
.file-upload-list {
  display: inline-block;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.file-upload-list i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.file-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.file-upload-list:hover .file-upload-list-cover {
  display: block;
}
</style>
