<template>
  <el-tabs v-model="activeName" style="padding: 15px">
    <el-tab-pane label="完工材料" name="first">
      <el-container>
        <el-main>
          <el-form ref="elForm" :model="items" :rules="uploadRules" size="medium" label-width="100px">
            <el-form-item label="工程名称" prop="">
              <el-input v-model="items.proName" v-no-whitespace :style="{width: '30%'}" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="完工申请单" prop="completionApplyFiles">
              <uploadFile :limit="5" :multiple=true :accept="accept" :uploadList.sync="items.completionApplyFiles"
                          @picturePreview="picturePreview"
                          v-on:delFile="delFile"
                          v-on:up="handleFileChange('elForm','completionApplyFiles')"
                          :class="{disabled:paramsData.type === 'view'}"
                          :style="{width: '100%',height: '80%'}"
              ></uploadFile>
            </el-form-item>
            <el-form-item label="其他附件" prop="">
              <uploadFile :limit="5" :multiple=true :accept="accept" :uploadList.sync="items.otherFiles"
                          @picturePreview="picturePreview"
                          :style="{width: '100%',height: '80%'}"
                          v-on:delFile="delFile"
                          :class="{disabled:paramsData.type === 'view'}"
                          v-on:up="handleFileChange('elForm','otherFiles')"
              ></uploadFile>
            </el-form-item>
          </el-form>
        </el-main>
        <el-footer v-if="paramsData.type !== 'view'">
          <el-button type="primary" @click="submitForm('elForm')" v-preventReClick="5000">提交</el-button>
          <el-button @click="cancel()">取消</el-button>
        </el-footer>
      </el-container>


    </el-tab-pane>
    <el-tab-pane label="审批信息" name="second">
      <bns-timeline-tabs :is-examine="false" :btn-show="false" :show-type="1" :items="approvalInfo"/>
    </el-tab-pane>
  </el-tabs>
</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 { addFinishApply } from '@/api/pro/cons/consList'
import { getFileData, getParams } from '@/utils/bonus'
import { approvalHistory } from '@/api/terminalEquipment/deviceInformation'
import { submitApproval } from '@/api/pro/admissionRequest'
import { selectFile } from '@/api/tool/select'
import { decryptCBC } from '@/utils/aescbc'
export default {
  components: { BnsTimelineTabs, BnsEquipDetailsTabs, uploadFile },
  data() {
    return {
      activeName: 'first',
      items: {
        proName: this.$store.state.user.thisIds.proName,
        proId:  this.$store.state.user.thisIds.proId,
        consUuid:  this.$store.state.user.thisIds.consUuid,
        supUuid: this.$store.state.user.thisIds.supUuid,
        consId:  this.$store.state.user.thisIds.consId,
        uuid:  this.$store.state.user.thisIds.uuid,
        completionApplyFiles: [],
        otherFiles: [],
      },
      approvalInfo: [],
      uploadRules: {
        completionApplyFiles: [
          { required: true, message: '请上传完工申请单', trigger: 'blur' }
        ],
      },
      accept: '.png, .jpg, .jpeg, .gif, .bmp, .docx, .doc, .xlsx, .xls, .ppt, .pptx, .pdf',
      delFileIds: [],
      paramsData:{}
    }
  },
  created() {
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    console.log(this.paramsData)
    this.approvalHistory()
    // if (this.paramsData.type !== 'add') {
      this.getCompletionApplyFiles()
      this.getOtherFile()
    // }
  },
  methods: {
    getFileData,
    getParams,
    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)
    },
    approvalHistory(){
      console.log("this.paramsData.taskId:"+this.paramsData.taskId)
      approvalHistory({taskId:this.paramsData.taskId}).then(res => {
        this.approvalInfo = res.data;
      })
    },
    /** 获取四措两案文件 */
    getCompletionApplyFiles() {
      const params = {
        uuid: this.$store.state.user.thisIds.uuid,
        classification: '1',
        fromType: '1',
        informationType: '11'
      }
      selectFile(params).then(response => {
        this.items.completionApplyFiles = response.data
        this.handleFileChange('elForm','completionApplyFiles')
      })
    },
    /** 获取四措两案文件 */
    getOtherFile() {
      const params = {
        uuid: this.$store.state.user.thisIds.uuid,
        classification: '3',
        fromType: '1',
        informationType: '12'
      }
      selectFile(params).then(response => {
        this.items.otherFiles = response.data
        this.handleFileChange('elForm','otherFiles')
      })
    },
    //上传组件-图片查看
    picturePreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true

    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.items)
          this.items.delFileIds = this.delFileIds.join(',')
          const reqData = new FormData()
          reqData.append('params', JSON.stringify(this.items))

          // 使用 Promise.all 并行处理文件数据获取，提高效率
          Promise.all([
            this.getFileData(this.items.completionApplyFiles),
            this.getFileData(this.items.otherFiles),
          ]).then(([completionApplyFiles, otherFiles]) => {
            if (!completionApplyFiles || completionApplyFiles.length === 0) {
              reqData.append('completionApplyFiles', new Blob())
            } else {
              completionApplyFiles.forEach(item => reqData.append('completionApplyFiles', item))
            }
            if (!otherFiles || otherFiles.length === 0) {
              reqData.append('otherFiles', new Blob())
            } else {
              otherFiles.forEach(item => reqData.append('otherFiles', item))
            }
            addFinishApply(reqData).then(response => {
              this.submitApply()
            }).catch(error => {
              // 增加错误处理
              this.$modal.msgError('新增失败：' + error.message)
            })
          })
        }else{
          return false
        }
      })
    },
    submitApply(){
      console.log(this.getParams())
      const param = {
        ...this.getParams(),
        taskType: '9',
        taskId: this.paramsData.taskId,
        uuid:this.$store.state.user.thisIds.uuid
      }
      console.log("param="+JSON.stringify(param))
      submitApproval(param).then(response => {
        console.log("response="+JSON.stringify(response))
        if (response.code === 200) {
          if (response.msg === '此审核类型未配置相对应的审核流，请联系管理员配置后再次提交'){
            this.$modal.msgError(response.msg)
          }else{
            this.$modal.msgSuccess('提交成功')
          }
          this.$tab.closePage()
          this.$router.push({ path: '/index' , query: { result: 1}})
        } else {
          this.$modal.msgError('提交失败')
        }
      })
    },
    cancel() {
      this.$tab.closePage()
    }
  }

}
</script>
<style scoped lang="scss">
.el-header, .el-footer {
  color: #333;
  line-height: 60px;
  text-align: right;
  position: absolute;
  top: 90%;
  left: 85%;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  line-height: 750px;
  height: 750px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
</style>
