<template>
    <div class="container">
      <el-tabs v-model="activeName">
        <el-tab-pane name="first">
          <span slot="label"><i style="color:red">*</i> 施工材料</span>
          <el-container>
            <el-main>
             <el-form ref="form" :rules="rules" :model="items">
               <el-form-item label="" prop="constructionMaterialFile">
                 <uploadFile :limit="limit" :accept="accept" :uploadList.sync="items.constructionMaterialFile"
                             @picturePreview="picturePreview"
                             v-on:delFile="delFile"
                             :multiple=true
                             v-on:up="handleFileChange('form','constructionMaterialFile')"
                             :disabled="disabled"
                             :class="{disabled:this.paramsData.type === 'view'}"
                             :style="{width: '100%',height: '80%'}"
                 ></uploadFile>
               </el-form-item>
             </el-form>
            </el-main>
            <el-footer v-if="paramsData.type !== 'view'">
              <el-button type="primary" @click="submitForm('form')" v-preventReClick="5000">提交</el-button>
              <el-button @click="cancel()">取消</el-button>
            </el-footer>
          </el-container>


        </el-tab-pane>
        <el-tab-pane label="审批信息" name="second" v-if="paramsData.type === 'view'">
          <bns-timeline-tabs :items="approvalInfo" :show-type= 1 :is-examine="false" :btn-show="false"/>
        </el-tab-pane>
      </el-tabs>
      <!-- 文件预览弹窗 -->
      <el-dialog title="文件预览" :visible.sync="dialogVisible" width="90%" append-to-body>
        <div style="width: 100%;height:720px">
          <bns-kkFile-preview :items="filePreview"></bns-kkFile-preview>
        </div>
      </el-dialog>
    </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 { addMaterialApply } from '@/api/pro/cons/materialList'
import { approvalHistory } from '@/api/terminalEquipment/deviceInformation'
import {submitMaterialApproval } from '@/api/pro/admissionRequest'
import { getParams } from '@/utils/bonus'
import { selectFile } from '@/api/tool/select'
import { decryptCBC } from '@/utils/aescbc'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'
export default {
  components: { bnsKkFilePreview, BnsTimelineTabs, BnsEquipDetailsTabs, uploadFile },
  data() {
    return{
      dialogVisible:false,
      activeName: "first",
      loading: false,
      limit:9,
      items: {
        proId: this.$store.state.user.thisIds.proId,
        consUuid: this.$store.state.user.thisIds.consUuid,
        supUuid: this.$store.state.user.thisIds.supUuid,
        constructionMaterialFile: [],
      },
      approvalInfo:[],
      accept: '.png, .jpg, .jpeg, .gif, .bmp, .docx, .doc, .xlsx, .xls, .ppt, .pptx, .pdf',
      delFileIds: [],
      paramsData: {},
      rules: {
        constructionMaterialFile: [
          { required: true, message: '请上传施工材料', trigger: 'blur' }
        ]
      },
      disabled: false,
      filePreview: {
        filePreviewUrl: '',
        fileName: '',
        showDownloadButton: false
      },
    }
  },
  created() {
    // this.paramsData = this.$route.query.params
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    this.disabled = this.paramsData.type === 'view'
    this.approvalHistory()
    if (this.paramsData.type !== 'add') {
      this.limit = 1
      this.getFile()
    }
  },
  methods: {
    getParams,
    //上传组件-图片查看
    picturePreview(file) {
      console.log(file)
      this.filePreview.filePreviewUrl = file.url
      this.filePreview.fileName = file.name
      this.dialogVisible = true
    },
    getFile(){
      const params = {
        uuid: this.paramsData.uuid,
        classification: '2',
        fromType : '5',
        informationType : '5',
      }
      selectFile(params).then(response => {
        this.items.constructionMaterialFile = []
        this.items.constructionMaterialFile = response.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)
    },
    approvalHistory(){
      console.log("this.paramsData.taskId:"+this.paramsData.taskId)
      approvalHistory({taskId:this.paramsData.taskId}).then(res => {
        this.approvalInfo = res.data;
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          this.items.delFileIds = this.delFileIds.join(',')
          this.items.uuid = this.paramsData.type === 'add' ? '' : this.paramsData.uuid
          this.items.type = this.paramsData.type
          console.log(this.items)
          const reqData = new FormData()
          reqData.append('params', JSON.stringify(this.items))

          // 使用 Promise.all 并行处理文件数据获取，提高效率
          Promise.all([
            this.getFileData(this.items.constructionMaterialFile),
          ]).then(([constructionMaterialFile]) => {
            if (!constructionMaterialFile || constructionMaterialFile.length === 0) {
              reqData.append('constructionMaterialFile', new Blob())
              this.submitApply()
            } else {
              constructionMaterialFile.forEach(item => reqData.append('constructionMaterialFile', item))
              addMaterialApply(reqData).then(response => {
                this.submitApply()
              }).catch(error => {
                // 增加错误处理
                this.loading = false
                this.$modal.msgError('新增失败：' + error.message)
              })
            }
          })
        }else{
          return false
        }
      })
    },
    submitApply(){
      console.log(this.getParams())
      const param = {
        ...this.getParams(),
        taskType: '7',
        taskId: this.paramsData.type === 'add' ? '' : this.paramsData.taskId,
        uuid:this.paramsData.type === 'add' ? '' : this.paramsData.uuid
      }
      console.log("param="+JSON.stringify(param))
      submitMaterialApproval(param).then(response => {
        console.log("response="+JSON.stringify(response))
        this.loading = false
        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();
    },
    // 提取公共方法，获取fileList中具有raw属性的文件
    getFileData(fileList) {
      return Promise.all(fileList.filter(item => item?.hasOwnProperty('raw')).map(item => item.raw))
    },
  }


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

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

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

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;
}
.container{
  padding: 10px;
}
</style>
