<template>
  <el-tabs v-model="activeName" :style="{padding:'20px',height:'90%'}">
    <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="applicationForCommencementFiles">
              <uploadFile :limit="5" :accept="accept" :uploadList.sync="items.applicationForCommencementFiles"
                          @picturePreview="picturePreview"
                          :style="{width: '100%',height: '80%'}"
                          v-on:delFile="delFile"
                          :disabled="paramsData.disabled"
                          :class="{disabled:this.paramsData.type === 'view'}"
                          v-on:up="handleFileChange('elForm','applicationForCommencementFiles')"
              ></uploadFile>
<!--              <el-empty v-if="items.applicationForCommencementFiles.length === 0 && this.paramsData.type === 'view'" description="暂无文件"></el-empty>-->
              <div v-if="items.applicationForCommencementFiles.length === 0 && this.paramsData.type === 'view'" class="no-files">
                <img src="@/assets/file/no_file.png" width="180" alt="文件图标" />
              </div>
            </el-form-item>
            <el-form-item label="其他附件" prop="otherFiles">
              <uploadFile :limit="5" :accept="accept" :uploadList.sync="items.otherFiles"
                          @picturePreview="picturePreview"
                          :style="{width: '100%',height: '80%'}"
                          v-on:delFile="delFile"
                          :disabled="paramsData.disabled"
                          :class="{disabled:this.paramsData.type === 'view'}"
                          v-on:up="handleFileChange('elForm','otherFiles')"
              ></uploadFile>
              <div v-if="items.otherFiles.length === 0 && this.paramsData.type === 'view'" class="no-files">
                <img src="@/assets/file/no_file.png" width="180" alt="文件图标" />
              </div>
<!--              <el-empty style="width: 10%" v-if="items.otherFiles.length === 0 && this.paramsData.type === 'view'" description="暂无文件"></el-empty>-->
            </el-form-item>
          </el-form>
        </el-main>
        <el-footer v-if="this.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 :items="approvalInfo" :show-type=1 :is-examine=false :btn-show="false"/>
    </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 { addConsStartWorkApply } from '@/api/pro/cons/consList'
import { getFileData, getParams, parseTime } from '@/utils/bonus'
import { submitApproval } from '@/api/pro/admissionRequest'
import { approvalHistory } from '@/api/terminalEquipment/deviceInformation'
import { selectFile } from '@/api/tool/select'
import { decryptCBC } from '@/utils/aescbc'

export default {
  components: { BnsTimelineTabs, BnsEquipDetailsTabs, uploadFile },
  data() {
    return {
      activeName: 'first',
      items: {
        proName: '',
        applicationForCommencementFiles: [],
        otherFiles: [],
      },
      approvalInfo: [],
      uploadRules: {
        applicationForCommencementFiles: [
          { required: true, message: '请上传完工申请单', trigger: 'blur' }
        ],
      },
      accept: '.png, .jpg, .jpeg, .pdf, .docx, .doc, .xlsx, .xls',
      delFileIds: [],
      paramsData:{}
    }
  },
  created() {
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    if (this.paramsData.type !== 'add') {
      this.getStartWorkFile()
      this.getOtherFile()
    }
    this.approvalHistory()
  },
  methods: {
    getParams,
    delFile(e) {
      console.log(e)
      if (!this.delFileIds.includes(e)) {
        this.delFileIds.push(e)
      }
      console.log(this.delFileIds)
    },
    getStartWorkFile(){
      const params = {
        uuid: this.paramsData.uuid,
        classification: '1',
        fromType: '1',
        informationType: '6',
      }
      selectFile(params).then(response => {
        this.items.applicationForCommencementFiles = response.data;
      });
    },
    getOtherFile(){
      const params = {
        uuid: this.paramsData.uuid,
        classification: '1',
        fromType: '1',
        informationType: '7',
      }
      selectFile(params).then(response => {
        this.items.otherFiles = response.data;
      });
    },
    handleFileChange(form,name) {
      // 手动校验
      this.$refs[form].validateField(name)
    },
    approvalHistory(){
      approvalHistory({taskId:this.paramsData.taskId}).then(res => {
        this.approvalInfo = res.data
        console.log(JSON.stringify(res))
      })
    },
    getFileData,
    //上传组件-图片查看
    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)
          const reqData = new FormData()
          this.items.proId = this.$store.state.user.thisIds.proId
          this.items.consUuid = this.$store.state.user.thisIds.consUuid
          this.items.supUuid = this.$store.state.user.thisIds.supUuid
          this.items.uuid = this.$store.state.user.thisIds.uuid
          this.items.delFileIds = this.delFileIds.join(',')
          reqData.append('params', JSON.stringify(this.items))

          // 使用 Promise.all 并行处理文件数据获取，提高效率
          Promise.all([
            this.getFileData(this.items.applicationForCommencementFiles),
            this.getFileData(this.items.otherFiles),
          ]).then(([applicationForCommencementFiles,otherFiles]) => {
            if (!applicationForCommencementFiles || applicationForCommencementFiles.length === 0) {
              reqData.append('applicationForCommencementFiles', new Blob())
            } else {
              applicationForCommencementFiles.forEach(item => reqData.append('applicationForCommencementFiles', item))
            }
            if (!otherFiles || otherFiles.length === 0) {
              reqData.append('otherFiles', new Blob())
            } else {
              otherFiles.forEach(item => reqData.append('otherFiles', item))
            }
            addConsStartWorkApply(reqData).then(response => {
              console.log(response)
              this.submitApply()
            }).catch(error => {
              console.log(error)
              // 增加错误处理
              this.$modal.msgError('提交失败')
            })
          })
        }else{
          return false
        }
      })
    },
    submitApply(){
      console.log(this.getParams())
      const param = {
        ...this.getParams(),
        taskType:'4',
        taskId: this.paramsData.type === 'edit' ? 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()
        } else {
          this.$message.error(response.msg)
          this.$tab.closePage()
        }
      })
    },
    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: 660px;
  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>
