<template>
  <dialog-edit :visible.sync="dialogVisible" :title="$t('certificateAudit.title')" width="1480px" :saveLabel="$t('common.submit')" :loading="loading"
               :form="form" :api="api" :editModel="editModel" :formRules="formRules" ref="dialog" :autoSave="false" @onSaved="onSaved">
    <div class="dialog-tab">
      <el-tabs v-model="activityName" type="card" @tab-click="tabClick">
        <div class="title">
          <span>{{$t('certificateAudit.' + tabsTitle)}}</span>
        </div>
        <el-divider class="divider"></el-divider>

        <!-- 项目公司信息 -->
        <el-tab-pane :label="$t('certificateAudit.proCompanyInfo')" name="proCompanyInfo">
          <projectCompanyInfo ref="proCompanyInfo"></projectCompanyInfo>
        </el-tab-pane>

        <!-- 线下历史审核意见 -->
        <el-tab-pane :label="$t('certificateAudit.offlineAuditOpinionHistory')" name="offlineAuditOpinionHistory">
          <offlineAuditOpinionHistory ref="offlineAuditOpinionHistory" class="bottomDiv"></offlineAuditOpinionHistory>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="coll-title coll-body">
      <el-form :model="fileForm" :rules="formRules" ref="fileForm">
        <el-collapse v-model="activityNames">
          <!-- 审核信息列表 -->
          <el-collapse-item :title="$t('certificateAudit.auditInfo')" name="auditInfo">
            <div class="table-form">
              <vxe-grid
                border
                show-overflow
                highlight-cell
                ref="fileGrid"
                class="vxeTable"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 1)"
                :columns="columns"
                cell-class-name="common-table-cell"
                header-cell-class-name="common-table-header"
                max-height="500"
                :data="fileForm.auditData"
                :optimization="{scrollY: {gt: 10}}">
                <!-- 表格上方操作按钮 -->
                <template v-slot:top>
                  <div class="btn-right bottomDiv">
                    <auth-button type="primary" size="medium" icon="iconfont iconzancun" :loading="tsLoading"
                                 :label="$t('common.staging')" @click="tempSave"></auth-button>
                    <btn-batch-download type="primary" size="medium" :classType="true" :fileID="allFileIds" :beforeBtchDownload="beforeBtchDownload"
                                        :icon="'iconfont iconxiazai1'" :downloadButtonMsg="$t('taskManage.todoTask.fileAllDownload')"></btn-batch-download>
                    <auth-button type="primary" size="medium" icon="iconfont iconfuzhi1"
                                 :label="$t('taskManage.todoTask.copyLastAuditOpinion')" @click="copy"></auth-button>
                  </div>
                </template>
                <!-- 列表操作按钮 -->
                <template v-slot:operation="{ row }">
                  <div class="btn-operate">
                    <btn-upload :uploadApi="uploadApi" :classType="true" :rowData="row" @uploadSuccess="importSuccess"
                                :icon="rowFileId(row).length > 0 ? 'iconfont iconzhongxinshangchuan' : 'iconfont iconshangchuan1'"
                                :title="rowFileId(row).length > 0 ? $t('common.reUpload') : $t('common.upload')"></btn-upload>
<!--                    <btn-batch-download v-if="rowFileId(row).length > 0" :fileID="rowFileId(row)" :title="$t('common.downLoad')"></btn-batch-download>-->
                    <btn-download v-if="!UtilJs.isEmpty(bindFileId(row))" :fileID="bindFileId(row)" :title="$t('common.downLoad')"></btn-download>
                    <!-- 删除附件 -->
                    <auth-button v-if="rowFileId(row).length > 0" class="iconCircleDel"
                                 icon="iconfont iconshanchufujian" :title="$t('taskManage.todoTask.delFile')" @click="delFile(row)"></auth-button>
                    <auth-button class="iconCircleDel" icon="iconfont iconjian" :title="$t('common.del')" @click="delAuditInfo(row)"></auth-button>
                  </div>
                </template>
                <!-- 显示总数项 -->
                <template slot="bottom">
                  <span>{{$t('common.viewTip1')}}{{startNum1}}{{$t('common.viewTip2')}}{{endNum1}}{{$t('common.viewTip3')}}{{endNum1}}{{$t('common.viewTip4')}}</span>
                </template>
              </vxe-grid>
            </div>
          </el-collapse-item>
          <!-- 另需供应商或项目公司提供文件 -->
          <!--<el-collapse-item :title="$t('certificateAudit.neededOtherFile')" name="neededOtherFile">
            <div class="table-form">
              <data-table :showPage="false" :showSelection="true" :sourceData.sync="fileForm.fileData" :menuFlag="true"
                          :selectedRows.sync="selectedFileRows" :columns="fileCol" operateBtnLayout="">
                <template slot="headButton">
                  <div class="btn-right">
                    <auth-button type="primary" size="medium" icon="iconfont iconxinzeng" :label="$t('common.create')" @click="add"></auth-button>
                    <auth-button type="primary" size="medium" icon="iconfont iconshanchu" :label="$t('common.del')" @click="del"></auth-button>
                  </div>
                </template>
                &lt;!&ndash; 文件名称 &ndash;&gt;
                <template slot="fileName" slot-scope="scope">
                  <el-form-item v-if="scope.data.row.status" label-width="0" :prop="'fileData.'+scope.data.$index+'.fileCode'" :rules="formRules.fileCode">
                    <select-proj-file-name v-model="scope.data.row.fileCode" :rowIndex="scope.data.$index" @selectChanged="projFileChanged"
                                           :queryParas="projParas" :placeholder="$t('common.pleaseSelect')"
                                           :optionDisabled="optionDisabled" class="dymForm"></select-proj-file-name>
                  </el-form-item>
                  <span v-else>{{scope.data.row.fileName}}</span>
                </template>
                &lt;!&ndash; 有效份数 &ndash;&gt;
                <template slot="effectiveCopies" slot-scope="scope">
                  <el-form-item label-width="0" :prop="'fileData.'+scope.data.$index+'.effectiveCopies'"
                                :rules="{ required: true, validator: effectiveCopiesCheck, trigger: 'blur' }">
                    <el-input v-model.trim="scope.data.row.effectiveCopies" size="medium" :placeholder="$t('common.pleaseInput')"></el-input>
                  </el-form-item>
                </template>
                &lt;!&ndash; 是否扫描件 &ndash;&gt;
                <template slot="ifsScanFile" slot-scope="scope">
                  <el-form-item label-width="0">
                    <select-dictionary v-model="scope.data.row.ifsScanFile" dictTypeCode="ZDZD0024"></select-dictionary>
                  </el-form-item>
                </template>
                &lt;!&ndash; 审核意见 &ndash;&gt;
                <template slot="auditOpinions" slot-scope="scope">
                  <el-form-item label-width="0">
                    <el-input v-model="scope.data.row.auditOpinions" size="medium" maxlength="500" :placeholder="$t('taskManage.todoTask.fileAuditOpinionMsg')"></el-input>
                  </el-form-item>
                </template>
                &lt;!&ndash; 操作 &ndash;&gt;
                <el-table-column :label="$t('common.operate')" align="center">
                  <template slot-scope="scope">
                    <auth-button class="iconCircle table-btn" icon="iconfont iconshangchuan1" @click="onClick(scope.row)"
                                 :title="rowFileId(scope.row).length > 0 ? $t('common.reUpload') : $t('common.upload')"></auth-button>
                    <btn-upload v-show="false" ref="upload" :uploadApi="uploadApi" :classType="true" :rowData="scope.row" @uploadSuccess="uploadSuccess"></btn-upload>
                    <btn-batch-download v-if="rowFileId(scope.row).length > 0" :fileID="rowFileId(scope.row)" :title="$t('common.downLoad')"></btn-batch-download>
                  </template>
                </el-table-column>
                &lt;!&ndash; 显示总数项 &ndash;&gt;
                <template slot="paginationLeft">
                  <span>{{$t('common.viewTip1')}}{{startNum2}}{{$t('common.viewTip2')}}{{endNum2}}{{$t('common.viewTip3')}}{{endNum2}}{{$t('common.viewTip4')}}</span>
                </template>
              </data-table>
            </div>
          </el-collapse-item>-->
        </el-collapse>
      </el-form>
    </div>
  </dialog-edit>
</template>
<script>
import BaseEdit from '@/pages/baseEditPage.js'
import { DialogEdit, authButton, DataTable, btnUpload, btnDownload, btnBatchDownload, SelectDictionary } from 'newepoch-components'
import offlineAuditOpinionHistory from '@/pages/dataAudit/certificateAudit/offlineAuditOpinionHistory.vue'
import projectCompanyInfo from '@/pages/dataAudit/certificateAudit/projectCompanyInfo.vue'
import SelectProjFileName from '@/components/element/dataAduit/SelectProjFileName.vue'
import projCommonFileApi from '@/api/dataAudit/projCommonFileApi.js'
import * as format from '@/filters/index'
import { UPLOAD_API } from '@/constant.js'
import { regExp } from '@/validator/index.js'
import cn from '@/i18n/langs/cn.js'

const { common, taskManage: { todoTask } } = cn
export default {
  name: 'projectThreeCertificatesEdit',
  extends: new BaseEdit(),
  components: {
    DialogEdit,
    authButton,
    DataTable,
    btnUpload,
    btnDownload,
    btnBatchDownload,
    SelectDictionary,
    offlineAuditOpinionHistory,
    projectCompanyInfo,
    SelectProjFileName
  },
  data () {
    return {
      // assetInfoId: '1911221731528020102',
      loading: false,
      tsLoading: false,
      activityName: 'proCompanyInfo',
      activityNames: ['auditInfo', 'neededOtherFile'],
      tabsTitle: 'proCompanyInfo',
      uploadApi: UPLOAD_API,
      formRules: {
        // legalRepresentative: [{ required: true, message: common.input + certificateAudit.legalRepresentative, trigger: 'blur' }],
        // setDate: [{ required: true, message: common.point + certificateAudit.setDate, trigger: 'blur' }],
        // approvedDate: [{ required: true, message: common.point + certificateAudit.approvedDate, trigger: 'blur' }],
        // businessDate: [{ required: true, message: common.input + certificateAudit.businessDate, trigger: 'blur' }]
        fileCode: [{ required: true, message: todoTask.selectFileMsg, trigger: 'change' }]
      },
      projParas: {
        fileSource: '3',
        ifsCommon: '1'
      },
      tempSaveDto: {
        itemCompanyInfo: null,
        fileManagementId: '',
        commonFileInfoDtos: [],
        ifsOtherCommonFileInfoDtos: []
      },
      submitDto: {
        taskId: '',
        fileManagementId: '',
        enterpriseId: '',
        auditUserName: '',
        itemCompanyInfo: {},
        commonFileInfoDtos: [],
        ifsOtherCommonFileInfoDtos: []
      },
      allFileIds: [],
      selectData: [],
      fileForm: {
        auditData: [],
        fileData: []
      },
      selectedFileRows: [],
      startNum1: 0,
      endNum1: 0,
      startNum2: 0,
      endNum2: 0,
      search: '',
      columns: [
        // 审核文件名称
        {
          field: 'fileName',
          align: 'left',
          headerAlign: 'center',
          minWidth: '200px',
          showOverflow: 'title',
          title: todoTask.auditFile
        },
        // 需求份数
        {
          field: 'needCopies',
          align: 'right',
          headerAlign: 'center',
          minWidth: '150px',
          title: todoTask.neededNumber
        },
        // 已有份数
        {
          field: 'validCopies',
          align: 'right',
          headerAlign: 'center',
          minWidth: '150px',
          title: todoTask.existNumber
        },
        // 是否扫描件
        {
          field: 'ifsScanFile',
          align: 'center',
          headerAlign: 'center',
          minWidth: '150px',
          title: todoTask.scan,
          formatter: ({ cellValue }) => {
            return format.formatDict(cellValue, 'ZDZD0024')
          }
        },
        // 本次接收份数
        {
          field: 'receiveCopies',
          align: 'right',
          headerAlign: 'center',
          minWidth: '150px',
          title: todoTask.receivedNumber,
          formatter: ({ cellValue }) => { return cellValue === '' ? '-' : cellValue }
        },
        // 本次有效份数
        {
          field: 'effectiveCopies',
          align: 'right',
          headerAlign: 'center',
          minWidth: '150px',
          title: todoTask.effectiveNumber,
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item label-width="0"prop={'auditData.' + rowIndex + '.effectiveCopies'}
                  rules={ row.ifsScanFile === 0 ? { required: true, validator: this.effectiveCopiesCheck, trigger: 'blur' } : { required: false } }>
                  {row.ifsScanFile === 0
                    ? <el-input v-model_number_trim={row.effectiveCopies} size="medium" placeholder={common.pleaseInput}></el-input>
                    : <span>{'-'}</span>
                  }
                </el-form-item>
              ]
            }
          }
        },
        // 扫描件是否有效
        {
          field: 'ifsValidScanner',
          align: 'center',
          minWidth: '150px',
          title: todoTask.effectiveScan,
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item label-width="0">
                  {row.ifsScanFile === 1
                    ? <select-dictionary v-model={row.ifsValidScanner} dictTypeCode="ZDZD0024"></select-dictionary>
                    : <span>{'-'}</span>
                  }
                </el-form-item>
              ]
            }
          }
        },
        // 是否另需扫描件
        {
          field: 'ifsNeedAnotherScanner',
          align: 'center',
          minWidth: '150px',
          title: todoTask.otherScan,
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item label-width="0">
                  {row.ifsScanFile === 0
                    ? <select-dictionary v-model={row.ifsNeedAnotherScanner} dictTypeCode="ZDZD0024"></select-dictionary>
                    : <span>{'-'}</span>
                  }
                </el-form-item>
              ]
            },
            header: ({ column }) => {
              return [
                <div>
                  {todoTask.otherScan}
                  <select-dictionary size="mini" class="table_head_dict" v-model={this.search} name="selectAll" dictTypeCode="ZDZD0024"
                    v-on:selectChanged={this.selectChanged}>
                  </select-dictionary>
                </div>
              ]
            }
          }
        },
        // 审核意见
        {
          field: 'auditOpinions',
          align: 'left',
          minWidth: '250px',
          title: todoTask.auditOpinion,
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item label-width="0">
                  <el-input v-model_trim={row.auditOpinions} size="medium" maxlength="500" placeholder={todoTask.auditOpinionMsg}></el-input>
                </el-form-item>
                // <el-form-item label-width="0" prop={'auditData.' + rowIndex + '.auditOpinions'}
                //   rules={{ validator: this.auditOpinionsCheck, trigger: 'blur', row: row }}>
                //   <el-input v-model_trim={row.auditOpinions} size="medium" maxlength="500" placeholder={todoTask.auditOpinionMsg}></el-input>
                // </el-form-item>
              ]
            }
          }
        },
        {
          title: common.operate,
          minWidth: '200px',
          fixed: 'right',
          align: 'center',
          slots: { default: 'operation' }
        }
      ],
      fileCol: [
        // 文件名称
        {
          prop: 'fileName',
          align: 'left',
          width: '200px',
          label: todoTask.file,
          slot: true
        },
        // 需求份数
        {
          prop: 'needCopies',
          align: 'right',
          width: '150px',
          label: todoTask.neededNumber,
          format: (row) => { return row.needCopies === '' ? '-' : row.needCopies }
        },
        // 有效份数
        {
          prop: 'effectiveCopies',
          align: 'right',
          width: '150px',
          label: todoTask.effectiveNumbers,
          slot: true
        },
        // 是否扫描件
        {
          prop: 'ifsScanFile',
          align: 'center',
          width: '150px',
          label: todoTask.scan,
          slot: true
        },
        // 审核意见
        {
          prop: 'auditOpinions',
          align: 'left',
          width: '250px',
          label: todoTask.auditOpinion,
          slot: true
        }
      ]
    }
  },
  computed: {
    api () {
      return projCommonFileApi.projComFile
    }
  },
  methods: {
    // 切换标签
    tabClick (val) {
      let _this = this
      _this.tabsTitle = val.name
      _this.activityName = val.name
      _this.$nextTick(() => {
        if (val.name === 'offlineAuditOpinionHistory') {
          _this.$refs[val.name].loadData(_this.form.enterpriseId)
        }
      })
    },
    // 计算分页
    calPage (arr, start, end) {
      let res = [start, end]
      if (arr.length > 0) {
        res[0] = 1
        res[1] = arr.length
      } else {
        res[0] = 0
        res[1] = 0
      }
      return res
    },
    // 查询审核数据
    loadAuditData () {
      let _this = this
      _this.api.getList({ managementId: _this.form.managementId }).then(res => {
        if (res && res.data) {
          let pageRes = _this.calPage(res.data.commonFileInfoDtos, _this.startNum1, _this.endNum1)
          _this.startNum1 = pageRes[0]
          _this.endNum1 = pageRes[1]
          // 将字典ID转换为字符串
          res.data.commonFileInfoDtos.forEach(it => {
            if (it.auditOpinions === undefined) {
              _this.$set(it, 'auditOpinions', '')
            }
            it.ifsNeedAnotherScanner = it.ifsNeedAnotherScanner + ''
            it.ifsValidScanner = it.ifsValidScanner + ''
            _this.selectData.push(it.fileCode)
          })
          _this.fileForm.auditData = res.data.commonFileInfoDtos
        }
      })
    },
    // 查询另需数据
    loadOtherData () {
      let _this = this
      _this.api.getList({ managementId: _this.form.managementId }).then(res => {
        if (res && res.data) {
          const { ifsOtherCommonFileInfoDtos } = res.data
          let pageRes = _this.calPage(ifsOtherCommonFileInfoDtos, _this.startNum2, _this.endNum2)
          _this.startNum2 = pageRes[0]
          _this.endNum2 = pageRes[1]
          _this.fileForm.fileData = ifsOtherCommonFileInfoDtos
          // 将字典ID转换为字符串
          _this.fileForm.fileData.forEach(it => {
            it.ifsScanFile = it.ifsScanFile + ''
          })
          ifsOtherCommonFileInfoDtos.forEach(it => {
            _this.selectData.push(it.fileCode)
          })
        }
      })
    },
    projFileChanged (val, name, data, index) {
      let _this = this
      const { fileName, needCopies } = data
      if (this.UtilJs.isEmpty(val)) {
        _this.fileForm.fileData[index].fileName = ''
        _this.fileForm.fileData[index].needCopies = ''
        // _this.fileForm.fileData[index].infoRequirements = ''
        // _this.fileForm.fileData[index].necessaryType = ''
      } else {
        _this.fileForm.fileData[index].fileName = fileName
        _this.fileForm.fileData[index].needCopies = needCopies
        // _this.fileForm.fileData[index].infoRequirements = data.infoRequirements
        // _this.fileForm.fileData[index].necessaryType = data.necessaryType
      }
    },
    // 下拉框禁用选择项
    optionDisabled () {
      let _this = this
      return function (item) {
        let arr = [...new Set(_this.selectData)]
        if (arr.indexOf(item.fileCode) !== -1) {
          return true
        } else {
          return false
        }
      }
    },
    // 表头下拉框change
    selectChanged (val) {
      if (!this.UtilJs.isEmpty(val)) {
        this.fileForm.auditData.forEach(it => {
          if (it.ifsScanFile === 0) {
            it.ifsNeedAnotherScanner = val
          }
        })
      }
    },
    // 提交
    onSaved () {
      let _this = this
      if (_this.$refs.proCompanyInfo.validateForm()) {
        _this.$refs['fileForm'].validate((valid) => {
          if (valid) {
            let result = _this.isRepeat()
            if (result.length > 0) {
              let fileMsg = '文件名称为：'
              result.forEach(res => {
                fileMsg = fileMsg + res.fileName + '，'
              })
              fileMsg = fileMsg.substring(0, fileMsg.length - 1)
              _this.warning(fileMsg + '不能重复新增！')
              return
            }
            let tipMsg = '文件名称为：'
            let count = 0
            if (_this.fileForm.auditData.length > 0) {
              _this.fileForm.auditData.forEach(it => {
                if (it.ifsScanFile === 0) {
                  if (it.effectiveCopies !== it.receiveCopies) {
                    tipMsg = tipMsg + it.fileName + '，'
                    count++
                  }
                }
              })
            }
            if (count > 0) {
              tipMsg = tipMsg.substring(0, tipMsg.length - 1)
              tipMsg = tipMsg + ' 的本次接收份数与本次有效份数不一致，是否继续提交？'
              _this.$confirm(tipMsg, common.tip, {
                type: 'warning'
              }).then(() => {
                _this.submitMethod()
              }).catch(() => {})
            } else {
              _this.submitMethod()
            }
          } else {
            _this.error(todoTask.submitMsg)
          }
        })
      } else {
        _this.error('供应商信息填写有误，请检查！')
      }
    },
    submitMethod () {
      let _this = this
      const { fileForm: { auditData, fileData }, form: { taskId, enterpriseId, managementId } } = this
      let itemCompanyInfo = Object.assign({ enterpriseId: enterpriseId }, _this.$refs.proCompanyInfo.supplierForm)
      if (!_this.UtilJs.isEmpty(_this.$refs.proCompanyInfo.supplierForm.businessDate[0])) {
        _this.$set(itemCompanyInfo, 'fromTime', _this.$refs.proCompanyInfo.supplierForm.businessDate[0].valueOf())
      }
      if (!_this.UtilJs.isEmpty(_this.$refs.proCompanyInfo.supplierForm.businessDate[1])) {
        _this.$set(itemCompanyInfo, 'toTime', _this.$refs.proCompanyInfo.supplierForm.businessDate[1].valueOf())
      }
      _this.submitDto.itemCompanyInfo = itemCompanyInfo
      _this.submitDto.commonFileInfoDtos = auditData
      _this.submitDto.ifsOtherCommonFileInfoDtos = fileData
      _this.submitDto.fileManagementId = managementId
      _this.submitDto.taskId = taskId
      _this.submitDto.enterpriseId = enterpriseId
      _this.submitDto.auditUserName = _this.$store.getters.nikeName
      _this.submitDto.commonFileInfoDtos.forEach(audit => {
        _this.$set(audit, 'fileManagementId', _this.form.managementId)
      })
      _this.submitDto.ifsOtherCommonFileInfoDtos.forEach(file => {
        _this.$set(file, 'fileManagementId', _this.form.managementId)
      })
      _this.loading = true
      _this.api.submit(_this.submitDto).then(res => {
        if (res && res.data) {
          _this.success(common.saveSuccess)
          _this.dialogVisible = false
          _this.$emit('submit-success')
        } else {
          _this.error(common.saveError)
        }
        _this.loading = false
      }).catch(() => {
        _this.loading = false
      })
    },
    // 数组判重
    isRepeat () {
      let _this = this
      let arr = []
      _this.fileForm.auditData.forEach(audit => {
        arr.push({
          fileCode: audit.fileCode,
          fileName: audit.fileName
        })
      })
      _this.fileForm.fileData.forEach(file => {
        arr.push({
          fileCode: file.fileCode,
          fileName: file.fileName
        })
      })
      let hash = {}
      let res = []
      arr.forEach(it => {
        if (hash[it.fileCode]) {
          res.push(it)
        }
        // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
        hash[it.fileCode] = true
      })
      return res
    },
    // 暂存
    tempSave () {
      let _this = this
      const { fileForm: { auditData, fileData }, form: { enterpriseId, managementId } } = this
      if (_this.$refs.proCompanyInfo.validateForm()) {
        _this.$refs['fileForm'].validate((valid) => {
          if (valid) {
            let result = _this.isRepeat()
            if (result.length > 0) {
              let fileMsg = '文件名称为：'
              result.forEach(res => {
                fileMsg = fileMsg + res.fileName + '，'
              })
              fileMsg = fileMsg.substring(0, fileMsg.length - 1)
              _this.warning(fileMsg + '不能重复新增！')
              return
            }
            let itemCompanyInfo = Object.assign({ enterpriseId: enterpriseId }, _this.$refs.proCompanyInfo.supplierForm)
            if (_this.$refs.proCompanyInfo.supplierForm.businessDate.length > 0 && !_this.UtilJs.isEmpty(_this.$refs.proCompanyInfo.supplierForm.businessDate[0])) {
              _this.$set(itemCompanyInfo, 'fromTime', _this.$refs.proCompanyInfo.supplierForm.businessDate[0].valueOf())
            } else {
              _this.$set(itemCompanyInfo, 'fromTime', '')
            }
            if (_this.$refs.proCompanyInfo.supplierForm.businessDate.length > 1 && !_this.UtilJs.isEmpty(_this.$refs.proCompanyInfo.supplierForm.businessDate[1])) {
              _this.$set(itemCompanyInfo, 'toTime', _this.$refs.proCompanyInfo.supplierForm.businessDate[1].valueOf())
            } else {
              _this.$set(itemCompanyInfo, 'toTime', '')
            }
            _this.tempSaveDto.itemCompanyInfo = itemCompanyInfo
            _this.tempSaveDto.commonFileInfoDtos = auditData
            _this.tempSaveDto.ifsOtherCommonFileInfoDtos = fileData
            _this.tempSaveDto.fileManagementId = managementId
            _this.tempSaveDto.commonFileInfoDtos.forEach(audit => {
              _this.$set(audit, 'fileManagementId', managementId)
            })
            _this.tempSaveDto.ifsOtherCommonFileInfoDtos.forEach(file => {
              _this.$set(file, 'fileManagementId', managementId)
            })
            _this.tsLoading = true
            _this.api.tempSave(_this.tempSaveDto).then(res => {
              if (res && res.data) {
                _this.success(common.saveSuccess)
                _this.loadAuditData()
                _this.loadOtherData()
              } else {
                _this.error(common.saveError)
              }
              _this.tsLoading = false
            }).catch(() => {
              _this.tsLoading = false
            })
          } else {
            _this.error(todoTask.tempSaveMsg)
          }
        })
      } else {
        _this.error('供应商信息填写有误，请检查！')
      }
    },
    // 附件一键下载
    beforeBtchDownload () {
      let _this = this
      if (_this.fileForm.auditData.length === 0 && _this.fileForm.fileData.length === 0) {
        _this.allFileIds = _this.allFileIds.splice(0, _this.allFileIds.length)
      } else {
        let arr1 = _this.ergodicIds(_this.fileForm.auditData)
        let arr2 = _this.ergodicIds(_this.fileForm.fileData)
        _this.allFileIds.push(...arr1)
        _this.allFileIds.push(...arr2)
      }
      return _this.allFileIds
    },
    ergodicIds (targetArr) {
      let resArr = []
      targetArr.forEach(it => {
        if (it.auditItemCommonFileDetailDtos.length > 0) {
          it.auditItemCommonFileDetailDtos.forEach(item => {
            if (!this.UtilJs.isEmpty(item.newFileId) && item.newFileId !== '0') {
              resArr.push(item.newFileId)
            } else {
              if (!this.UtilJs.isEmpty(it.originalFileId) && it.originalFileId !== '0') {
                resArr.push(it.originalFileId)
              }
            }
          })
        }
      })
      return resArr
    },
    // 复制上轮审核意见
    copy () {
      let _this = this
      _this.api.getLastOpinion({ managementId: _this.form.managementId }).then(res => {
        if (res && res.data) {
          if (!_this.UtilJs.isEmpty(res.data)) {
            const { commonFileInfoDtos, ifsOtherCommonFileInfoDtos } = res.data
            if (commonFileInfoDtos.length === 0 && ifsOtherCommonFileInfoDtos.length === 0) {
              _this.warning(todoTask.auditEmptyMsg)
            } else {
              if (commonFileInfoDtos.length > 0) {
                commonFileInfoDtos.forEach(it => {
                  _this.fileForm.auditData.forEach(audit => {
                    if (audit.fileCode === it.fileCode) {
                      _this.$set(audit, 'auditOpinions', it.auditOpinions)
                    }
                  })
                })
              }
              if (ifsOtherCommonFileInfoDtos.length > 0) {
                ifsOtherCommonFileInfoDtos.forEach(item => {
                  _this.fileForm.fileData.forEach(file => {
                    if (file.fileCode === item.fileCode) {
                      _this.$set(file, 'auditOpinions', item.auditOpinions)
                    }
                  })
                })
              }
            }
          } else {
            _this.warning(todoTask.auditEmptyMsg)
          }
        }
      })
    },
    rowFileId (data) {
      let arr = []
      const { auditItemCommonFileDetailDtos } = data
      if (auditItemCommonFileDetailDtos.length > 0) {
        auditItemCommonFileDetailDtos.forEach(it => {
          if (!this.UtilJs.isEmpty(it.newFileId) && it.newFileId !== '0') {
            arr.push(it.newFileId)
          }
        })
      }
      return arr
    },
    bindFileId (data) {
      let id = ''
      const { auditItemCommonFileDetailDtos } = data
      if (auditItemCommonFileDetailDtos.length > 0) {
        auditItemCommonFileDetailDtos.forEach(it => {
          if (!this.UtilJs.isEmpty(it.newFileId) && it.newFileId !== '0') {
            id = it.newFileId
          } else if (!this.UtilJs.isEmpty(it.originalFileId) && it.originalFileId !== '0') {
            id = it.originalFileId
          }
        })
      }
      return id
    },
    // 删除附件
    delFile (row) {
      let _this = this
      _this.$confirm(todoTask.delFileTip, common.tip, {
        type: 'warning'
      }).then(() => {
        _this.api.delAuditFile({ fileManagementId: _this.form.managementId, fileCode: row.fileCode }).then(res => {
          if (res && res.data) {
            _this.success(common.delSuccess)
            // _this.loadAuditData()
            row.auditItemCommonFileDetailDtos[0].newFileId = ''
          } else {
            _this.error(common.delFailure)
          }
        })
      }).catch(() => {})
    },
    // 删除审核信息
    delAuditInfo (data) {
      let _this = this
      _this.$confirm(common.delTip, common.tip, {
        type: 'warning'
      }).then(() => {
        let fileInfoIds = []
        fileInfoIds.push(data.keyId)
        _this.api.delInfo(fileInfoIds).then(res => {
          if (res && res.data) {
            _this.success(common.delSuccess)
            _this.loadAuditData()
          } else {
            _this.error(common.delFailure)
          }
        })
      }).catch(() => {})
    },
    // 上传审核文件成功
    importSuccess (returnData, rowData) {
      let _this = this
      if (_this.UtilJs.isEmpty(rowData.fileCode)) {
        _this.warning(todoTask.uploadMsg)
        return
      }
      let uploadDto = {
        fileCode: rowData.fileCode,
        fileId: returnData.fileID,
        fileManagementId: _this.form.managementId
      }
      _this.api.upload(uploadDto).then(res => {
        if (res && res.data) {
          _this.$set(rowData.auditItemCommonFileDetailDtos[0], 'newFileId', returnData.fileID)
          _this.$set(rowData.auditItemCommonFileDetailDtos[0], 'fileCode', rowData.fileCode)
          _this.success(common.uploadSuccess)
          // _this.loadAuditData()
        } else {
          _this.error(common.uploadError)
        }
      })
    },
    // 上传另需文件
    onClick (data) {
      if (this.UtilJs.isEmpty(data.fileCode)) {
        this.warning(todoTask.uploadMsg)
      } else {
        this.$refs['upload'].upload()
      }
    },
    uploadSuccess (returnData, rowData) {
      let _this = this
      let uploadDto = {
        fileCode: rowData.fileCode,
        fileId: returnData.fileID,
        fileManagementId: _this.form.managementId
      }
      _this.api.upload(uploadDto).then(res => {
        if (res && res.data) {
          _this.success(common.uploadSuccess)
          if (rowData.auditItemCommonFileDetailDtos.length > 0) {
            rowData.auditItemCommonFileDetailDtos[0].fileCode = rowData.fileCode
            rowData.auditItemCommonFileDetailDtos[0].fileId = returnData.fileID
          } else {
            rowData.auditItemCommonFileDetailDtos.push({
              fileCode: rowData.fileCode,
              fileId: returnData.fileID
            })
          }
        } else {
          _this.error(common.uploadError)
        }
      })
    },
    effectiveCopiesCheck (rule, value, callback) {
      if (regExp.sequence.test(value)) {
        callback()
      } else {
        callback(new Error(todoTask.effectiveNumberMsg))
      }
    },
    // 新增另需文件
    add () {
      let _this = this
      _this.fileForm.fileData.push({
        auditItemCommonFileDetailDtos: [],
        fileCode: '',
        fileName: '',
        needCopies: '',
        effectiveNumber: '',
        auditOpinions: '',
        ifsScanFile: '',
        infoRequirements: 1,
        necessaryType: 3,
        date: new Date().valueOf(),
        status: true
      })
      _this.startNum2 = 1
      _this.endNum2 = _this.fileForm.fileData.length
    },
    // 删除另需文件
    del () {
      let _this = this
      if (_this.selectedFileRows.length === 0) {
        _this.warning(common.delSelectedTip)
        return
      }
      _this.$confirm(common.confirmTip, common.tip, {
        type: 'warning'
      }).then(() => {
        let obj = _this.filterData(_this.selectedFileRows)
        if (obj.keyArr.length > 0) {
          _this.api.delInfo(obj.keyArr).then(res => {
            if (res && res.data) {
              _this.success(common.delSuccess)
              _this.loadOtherData()
            }
          })
        } else {
          _this.fileForm.fileData = _this.fileForm.fileData.filter(item => {
            if (obj.dateArr.indexOf(item.date) === -1) {
              return true
            }
          })
          if (_this.fileForm.fileData.length === 0) {
            _this.startNum2 = 0
            _this.endNum2 = 0
          } else {
            _this.startNum2 = 1
            _this.endNum2 = _this.fileForm.fileData.length
          }
          _this.success(common.delSuccess)
        }
      }).catch(() => {})
    },
    filterData (rows) {
      let arr1 = []
      let arr2 = []
      rows.forEach(item => {
        if (item.keyId) {
          arr1.push(item.keyId)
        } else {
          arr2.push(item.date)
        }
      })
      return {
        keyArr: arr1,
        dateArr: arr2
      }
    }
    // 审核列表--审核意见校验
    /* auditOpinionsCheck (rule, value, callback) {
      // 盖章方式为鲜章 且 不是扫描件, 有效份数小于接收份数
      if (rule.row.ifsScanFile === 0 && rule.row.effectiveCopies < rule.row.receiveCopies) {
        if (this.UtilJs.isEmpty(value)) {
          callback(new Error(common.pleaseInput + todoTask.auditOpinion))
        } else {
          callback()
        }
      } else {
        callback()
      }
    } */
  },
  watch: {
    visible (val) {
      let _this = this
      const { form: { enterpriseId, enterpriseName, managementId } } = this
      if (val) {
        _this.$nextTick(() => {
          _this.activityName = 'proCompanyInfo'
          let params = {
            enterpriseId: enterpriseId,
            enterpriseName: enterpriseName,
            managementId: managementId
          }
          _this.$refs[_this.activityName].loadData(params)
        })
        _this.loadAuditData()
        _this.loadOtherData()
      } else {
        _this.search = ''
        _this.selectData = []
        _this.tempSaveDto = {
          itemCompanyInfo: null,
          fileManagementId: '',
          commonFileInfoDtos: [],
          ifsOtherCommonFileInfoDtos: []
        }
        _this.submitDto = {
          taskId: '',
          fileManagementId: '',
          enterpriseId: '',
          auditUserName: '',
          itemCompanyInfo: {},
          commonFileInfoDtos: [],
          ifsOtherCommonFileInfoDtos: []
        }
        _this.startNum1 = 0
        _this.endNum1 = 0
        _this.startNum2 = 0
        _this.endNum2 = 0
      }
    }
  }
}
</script>
<style scoped lang="scss" src="@/styles/dataAudit/certificateAudit/projectThreeCertificatesEdit.scss">
</style>
