<template>
  <div class="container" style="padding: 15px">
    <el-tabs v-model="activeName">
      <el-tab-pane label="工器具信息" name="first">
        <el-form ref="form" :model="items" label-width="80px" :rules="rules">
          <el-form-item label="工器具名称" label-width="200px" prop="equipName">
            <el-input v-model="items.equipName" :style="{width:'30%'}" v-no-whitespace :disabled="paramsData.isDisabled" maxlength="100" show-word-limit/>
          </el-form-item>
          <el-form-item label="型号" label-width="200px" prop="model">
            <el-input v-model="items.model" :style="{width:'30%'}" v-no-whitespace :disabled="paramsData.isDisabled" maxlength="20" show-word-limit/>
          </el-form-item>
          <el-form-item label="单位" label-width="200px" prop="unit">
            <el-input v-model="items.unit" :style="{width:'30%'}" v-no-whitespace :disabled="paramsData.isDisabled" maxlength="10" show-word-limit/>
          </el-form-item>
          <el-form-item label="数量" label-width="200px" prop="num">
            <el-input v-model="items.num" :style="{width:'30%'}" v-no-whitespace :disabled="paramsData.isDisabled" maxlength="10" show-word-limit/>
          </el-form-item>
          <el-form-item label="设备类型" label-width="200px" prop="equipType">
            <el-select v-model="items.equipType" :style="{width:'30%'}" :disabled="paramsData.isDisabled">
              <el-option v-for="item in equipTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="检测时间" label-width="200px" prop="detectionTime">
            <el-date-picker
              v-model="items.detectionTime"
              type="date"
              :disabled="paramsData.isDisabled"
              :editable="false"
              :style="{width:'30%'}"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="是否强制检测检验" label-width="200px" prop="isForceDetection">
            <el-select v-model="items.isForceDetection" :style="{width:'30%'}" :disabled="paramsData.isDisabled">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下次检测时间" label-width="200px" prop="nextDetectionTime">
            <el-date-picker
              v-model="items.nextDetectionTime"
              type="date"
              :editable="false"
              :disabled="paramsData.isDisabled"
              :style="{width:'30%'}"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="工器具文件" prop="instrumentDocumentFiles" label-width="200px">
            <uploadFile :limit="5" :accept="accept" :uploadList.sync="items.instrumentDocumentFiles"
                        @picturePreview="picturePreview" style="margin-top: 10px;"
                        v-on:delFile="delFile"
                        :class="{disabled:paramsData.type === 'view'}"
                        v-on:up="handleFileChange('form','instrumentDocumentFiles')"
            ></uploadFile>
          </el-form-item>

        </el-form>
        <el-button @click="cancel()" style="float:right;margin-right: 20px;">取消</el-button>
        <el-button type="primary" style="float:right;margin-right: 10px;" @click="submitForm('form')" v-if="paramsData.type !== 'view'" v-preventReClick="5000">提交</el-button>
      </el-tab-pane>
      <el-tab-pane label="审批信息" name="second">
        <bns-timeline-tabs :items="approvalInfo" :show-type=1 :is-examine=false :btn-show="false"/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import BnsEquipDetailsTabs from '@/components/pro-tabs/bns-equip-details-tabs.vue'
import uploadFile from '@/views/pro/admissionRequest/uploadFile.vue'
import BnsTimelineTabs from '@/components/pro-tabs/bns-timeline-tabs.vue'
import { addEquip, selectDetails } from '@/api/pro/cons/equip'
import { getParams, parseTime } from '@/utils/bonus'
import { dictTableOption } from '@/api/tool/select'
import { approvalHistory } from '@/api/terminalEquipment/deviceInformation'
import { decryptCBC } from '@/utils/aescbc'

export default {
  components: { BnsTimelineTabs, BnsEquipDetailsTabs, uploadFile },
  data() {
    return {
      activeName: 'first',
      isDisabled: false,
      equipTypeOptions:[],
      items: {
        id: '0',
        equipName: '',
        equipType: '',
        model: '',
        num: '',
        unit: '',
        detectionTime: '',
        isForceDetection: '0',
        nextDetectionTime: '',
        instrumentDocumentFiles: [],
      },
      approvalInfo: [],
      rules : {
        equipName: [
          { required: true, message: '请输入工器具单位名称', trigger: 'blur' },
        ],
        model: [
          { required: true, message: '请输入型号', trigger: 'blur' },
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' },
        ],
        num: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          {
            pattern: /^[0-9]*$/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        equipType: [
          { required: true, message: '请输入设备类型', trigger: 'blur' },
        ],
        detectionTime: [
          { required: true, message: '请输入检测时间', trigger: 'blur' },
        ],
        isForceDetection: [
          { required: true, message: '请输入是否强制检测检验', trigger: 'blur' },
        ],
        nextDetectionTime: [
          { required: true, message: '请输入下次检测时间', trigger: 'blur' },
        ],
        instrumentDocumentFiles: [
          { required: true, message: '请上传工器具文件', trigger: 'blur' },
        ]
      },
      accept: '.png, .jpg, .jpeg, .gif, .xls, .xlsx, .docx, .doc, .pdf',
      paramsData: {},
      delFileIds: [],
    }
  },
  created() {
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    console.log(this.paramsData)
    this.getEquipType()
    this.approvalHistory()
    if (this.paramsData.type !== 'add') {
      const param = {
        uuid: this.paramsData.uuid
      }
      selectDetails(param).then(response => {
        console.log(response)
        this.items = response.data;
        this.items.instrumentDocumentFiles = response.fileList;
        this.loading = false
      });
    }
  },
  watch: {
    'items.equipType': function(newVal) {
      this.updateRules(newVal);
    }
  },
  mounted() {
    this.updateRules(this.items.equipType);
  },
  methods: {
    updateRules(equipType) {
      if (equipType == 2) {
        this.$set(this.rules, 'instrumentDocumentFiles', [
          { required: true, message: '请上传工器具文件', trigger: 'change' }
        ]);
      } else {
        this.$set(this.rules, 'instrumentDocumentFiles', []);
      }
    },
    getParams,
    approvalHistory(){
      console.log("this.paramsData.taskId:"+this.paramsData.taskId)
      approvalHistory({taskId:this.paramsData.taskId}).then(res => {
        this.approvalInfo = res.data
      })
    },
    delFile(e) {
      console.log(e)
      if (!this.delFileIds.includes(e)) {
        this.delFileIds.push(e)
      }
      console.log(this.delFileIds)
    },
    handleFileChange(form,name) {
      // 手动校验
      this.$refs[form].validateField(name)
    },
    // 获取设备类型
    getEquipType(){
      const params = {
        dictType: 'sys_tools_type',
        dictValue: ''
      }
      dictTableOption(params).then(response => {
        this.equipTypeOptions = response.data
      })
    },
    //上传组件-图片查看
    picturePreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.items.detectionTime >= this.items.nextDetectionTime) {
            this.$message({
              message: '检测不能早于或等于下次检测时间',
              type: 'error'
            })
            return false
          }

          this.items.proId = this.$store.state.user.thisIds.proId
          this.items.consId = this.$store.state.user.thisIds.consId
          this.items.consUuid = this.$store.state.user.thisIds.consUuid
          this.items.uuid = this.paramsData.uuid
          this.items.detectionTime = parseTime(this.items.detectionTime,'{y}-{m}-{d}')
          this.items.nextDetectionTime =  parseTime(this.items.nextDetectionTime,'{y}-{m}-{d}')
          this.items.delFileIds = this.delFileIds.join(',')
          this.items.type = this.paramsData.type
          const reqData = new FormData()
          reqData.append('params', JSON.stringify(this.items))
          Promise.all([
            this.getFileData(this.items.instrumentDocumentFiles),
          ]).then(([instrumentDocumentFiles]) => {
            if (!instrumentDocumentFiles || instrumentDocumentFiles.length === 0) {
              reqData.append('instrumentDocumentFiles', new Blob())
            } else {
              instrumentDocumentFiles.forEach(item => reqData.append('instrumentDocumentFiles', item))
            }
            addEquip(reqData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$tab.closePage();
            }).catch(error => {
              // 增加错误处理
              this.$modal.msgError('新增失败：' + error.message)
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.$tab.closePage()
    },
    // 提取公共方法，获取fileList中具有raw属性的文件
    getFileData(fileList) {
      return Promise.all(fileList.filter(item => item?.hasOwnProperty('raw')).map(item => item.raw))
    },
  }

}
</script>
<style scoped lang="scss">

</style>
