<!--监理入场申请页面-->
<template>
  <el-container>
    <el-form ref="elForm" :model="formData" :rules="rule" label-width="100px" style="height: 82vh;overflow: auto;width: 100%;">
      <el-main>
        <el-tabs v-model="activeName">
          <el-tab-pane label="监理单位信息" name="first">
            <bns-supervisor-info-tabs :items="formData.supervisionInfo" />
          </el-tab-pane>
          <el-tab-pane label="监理人员基本信息" name="second">
            <div class="app-container">
              <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="监理姓名" prop="supervisorName">
                  <el-input
                    v-model="queryParams.name"
                    v-no-whitespace
                    placeholder="请输入监理姓名"
                    maxlength="20"
                    show-word-limit
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    v-if="this.paramsData.type !== 'view'"
                    @click="handleAdd"
                  >新增
                  </el-button>
                  <el-button type="primary" plain icon="el-icon-upload" size="mini" @click="handlePersonImport">
                    基础数据上传
                  </el-button>
                  <el-button type="primary" plain icon="el-icon-upload" size="mini" @click="handleFileImport">文件上传
                  </el-button>
                </el-form-item>
              </el-form>
              <el-table v-loading="loading" :data="supervisorList">
                <el-table-column label="序号" type="index" width="55" align="center"
                                 :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
                />
                <el-table-column label="姓名" align="center" prop="name" />
                <el-table-column label="岗位" align="center" prop="postName" />
                <el-table-column label="体检文件" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleShow(scope.row,1)">查看</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="保险文件" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleShow(scope.row,2)">查看</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="其他文件" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleShow(scope.row,4)">查看</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="性别" align="center" prop="sex" />
                <el-table-column label="年龄" align="center" prop="age" />
                <el-table-column label="联系方式" width="120" align="center">
                  <template slot-scope="scope">
                    <!-- 检查是否存在身份证号 -->
                    <span v-if="scope.row.phone">{{ hideSensitiveInfo(scope.row.phone) }}</span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="人脸照片" align="center" prop="faceUrl">
                  <template slot-scope="scope">
                    <el-popover placement="right" title="" trigger="hover">
                      <img :src="`${scope.row.faceUrl ? lookFaceFile+scope.row.faceUrl : ''}`" :min-width="300" :height="300" alt="照片" />
                      <img slot="reference" :src="`${scope.row.faceUrl ? lookFaceFile+scope.row.faceUrl : ''}`"
                           style="max-height: 50px; max-width: 50px"
                           :alt="`${scope.row.faceUrl ? lookFaceFile+scope.row.faceUrl : ''}`"
                      />
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                                 v-if="this.paramsData.type !== 'view'"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"

                      @click="handleEdit(scope.row)"
                    >编辑
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getSupervisorPersonList"
              />

              <el-dialog title="文件查看" :visible.sync="document" width="80%" top="5vh" append-to-body>
                <div style="width: 100%;height:720px">
                  <bns-file-list-tabs :items="fileList" />
                </div>
              </el-dialog>
              <el-dialog title="文件查看" :visible.sync="documentPreview" width="80%" top="5vh" append-to-body>
                <div style="width: 100%;height:720px">
                  <bns-kkFile-preview :items="kkFilePreview"></bns-kkFile-preview>
                </div>
              </el-dialog>


              <el-dialog :title="upload.title" :visible.sync="upload.open" width="25%">
                <el-form label-width="80px" label-position="left" :model="formFile" ref="form" :rules="ruleFile" >
                  <el-form-item label="文件上传" prop="fileList">
                    <el-upload ref="upload" :limit="1" accept=".zip"
                               :show-file-list="true"
                               class="upload-demo"
                               action="#"
                               :file-list="formFile.fileList"
                               :on-change="fileChange"
                               :on-remove="handleRemove"
                               :before-upload="beforeUpload"
                               :auto-upload="false" drag
                    >
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text">
                        将文件拖到此处，或
                        <em>点击上传</em>
                      </div>
                      <div
                        class="el-upload__tip"
                        slot="tip"
                      >
                      </div>
                      <div
                        class="el-upload__tip"
                        style="color:red"
                        slot="tip"
                      >提示：仅允许导入“zip”格式文件！
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-form>
                <div
                  slot="footer"
                  class="dialog-footer"
                >
                  <el-button
                    type="primary"
                    @click="submitFileForm"
                    v-preventReClick="5000"
                  >确 定
                  </el-button>
                  <el-button @click="upload.open = false">取 消</el-button>
                </div>
              </el-dialog>

              <el-dialog :title="`人员基础数据导入`" :visible.sync="personBasicOpen" width="60%" style="height: 1000px">
                <div style="padding: 15px;width: 100%;height: 750px">
                  <el-steps :active="active" :finish-status="status" align-center>
                    <el-step title="选择文件"></el-step>
                    <el-step title="数据预览"></el-step>
                    <el-step title="异常数据"></el-step>
                    <el-step title="导入完成"></el-step>
                  </el-steps>
                  <div class="step1" style="margin-bottom: 30px;">
                    <div
                      style="display: flex;flex-direction: column;padding: 20px;margin-left: 7%;height:80%;margin-top: 20px;border: 1px solid #ababab;border-radius: 5px;margin-right: 7%;"
                      v-if="active === 1"
                    >
                      <span style="font-size: 18px;font-weight: bold">模板下载</span>
                      <span style="font-size: 16px;margin-top: 10px;"
                      >请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</span>
                      <!--                      00afff-->
                      <el-button type="text" style="float:left;margin-top: 10px;width: 60px;" @click="downloadTemplate">
                        下载模板
                      </el-button>
                    </div>
                    <div
                      style="display: flex;flex-direction: column;padding: 20px;margin-left: 7%;margin-top: 20px;border: 1px solid #ababab;border-radius: 5px;margin-right: 7%;"
                      v-if="active === 1"
                    >
                      <span style="font-size: 18px;font-weight: bold">上传文件</span>
                      <span style="font-size: 16px;margin-top: 10px;"
                      >文件后缀名必须为xls或xlsx(即Excel格式),文件大小不得大于10Mb,最多支持1000行数据</span>
                      <input type="file" id="excel-file" style="display: none;">
                      <el-form ref="form" :model="formPerson" style="margin-top: 10px;" :rules="rulesPerson">
                        <el-form-item prop="fileList">
                          <el-upload
                            multiple
                            drag
                            accept=" .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf "
                            :show-file-list="true"
                            class="upload-demo"
                            action="#"
                            :limit="1"
                            :file-list="formPerson.fileList"
                            :on-change="filePersonChange"
                            :on-remove="handlePersonRemove"
                            :before-upload="beforePersonUpload"
                            :auto-upload="false"
                            ref="upload"
                          >
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__text">只能上传 xls/xlsx 文件，且不超过10MB</div>
                          </el-upload>
                        </el-form-item>
                      </el-form>
                      <div style="display: flex;flex-direction: column;">
                        <div style="margin-top: 10px;font-weight: 600;font-size: 16px;">特别提示</div>
                        <div style="margin-top: 10px;font-weight: 400;font-size: 12px;">1. 人员手机号唯一，不可重复</div>
                        <div style="margin-top: 10px;font-weight: 400;font-size: 12px;">2.
                          导入过程中如发现相同手机号数据，则停止导入
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="step2" style="margin-bottom: 30px;">
                    <div v-if="active === 2"
                         style="height: 680px;overflow-x: auto;overflow-y: auto;display: flex;flex-direction: column;padding: 20px;margin-left: 7%;margin-top: 20px;margin-right: 7%;"
                    >
                      <div v-if="errorLine.length > 0 || errorPhone.length > 0"
                           style="background: #ebebeb;padding: 10px;"
                      >
                        <div style="font-size: 16px;font-weight: 600;margin-bottom: 10px;color: red;">异常数据</div>
                        <div v-if="errorLine.length > 0" style="width: 100%;">行数：{{ errorLine.join(',') }}
                          有空数据或者错误数据
                        </div>
                        <div v-if="errorPhone.length > 0" style="width: 100%">
                          表格中手机号存在重复，请先删除重复的数据项！
                        </div>
                        <div v-if="errorPhone.length > 0"
                             style="margin-top: 10px;font-weight: 400;font-size: 16px;width: 100%;"
                        >重复的手机号:{{ errorPhone }}
                        </div>
                      </div>
                      <!-- 这里展示excel数据的表格 -->
                      <el-table :data="excelData" style="width: 100%;height: 700px;overflow-x: auto;overflow-y: auto">
                        <!-- 表格列定义 -->
                        <el-table-column prop="arg0" width="55" align="center" />
                        <el-table-column prop="arg1" width="120" align="center" />
                        <el-table-column prop="arg2" width="120" align="center" />
                        <el-table-column prop="arg3" width="120" align="center" />
                        <el-table-column prop="arg4" width="220" align="center" />
                        <el-table-column prop="arg5" width="160" align="center" />
                        <el-table-column prop="arg6" width="120" align="center" />
                      </el-table>
                    </div>
                  </div>

                  <div class="step3" style="margin-bottom: 30px;">
                    <div v-if="active === 3">
                      <div
                        style="display: flex;flex-direction: column;padding: 20px;margin-left: 7%;margin-top: 20px;margin-right: 7%;margin-bottom: 30px;"
                      >
          <span style="font-size: 16px;margin-top: 10px;"
          >以下是已经在库的手机号（人员已经录入），请先根据手机号删除相应行内容，然后再进行导入</span>
                        <span style="margin-top: 10px;width: 100%"
                        >{{ errorCode.substring(1, errorCode.length - 1) }}</span>
                      </div>
                    </div>
                  </div>

                  <div class="step4" style="margin-bottom: 30px;">
                    <div v-if="active === 4">
                      <div
                        style="display: flex;flex-direction: column;padding: 20px;margin-left: 7%;margin-top: 100px;margin-right: 7%;align-items: center;justify-content: center"
                      >
                        <img src="@/assets/file/import_success_blue.png" alt="导入成功">
                        <span style="margin-top: 20px;font-size: 18px"
                        >数据导入成功，请在列表中查看，提交审核之前请先上传相关人员的文件！</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="type === '导入'">
                    已导入：{{ importedCount }} / 1000
                    <el-progress :percentage="importProgress"></el-progress>
                  </div>
                  <div class="el-footer" style="position: absolute;top: 90%;left: 76%;margin-top: 10px;">
                    <el-button type="primary" style="margin-top: 12px;" @click="before"
                               v-if="active === 2 || active === 3"
                    >上一步
                    </el-button>
                    <el-button type="primary" style="margin-top: 12px;" @click="next"
                               v-if="active === 0 || active === 1"
                    >下一步
                    </el-button>
                    <el-button type="primary" style="margin-top: 12px;" @click="importExcel"
                               v-if="active === 2 && errorLine.length === 0 && errorPhone.length === 0 "
                    >导入
                    </el-button>
                    <el-button type="primary" plain style="margin-top: 12px;margin-bottom: 10px;" @click="personClose">
                      关闭
                    </el-button>
                  </div>

                </div>

              </el-dialog>

            </div>
          </el-tab-pane>
          <el-tab-pane name="three">
            <span slot="label"><i style="color:red">*</i> 企业资质</span>
            <el-form-item label-width="20px" label="" prop="enterpriseQualificationFiles">
              <upload-file
                :limit="9"
                :accept="accept"
                v-on:delFile="delFile"
                :uploadList.sync="formData.enterpriseQualificationFiles"
                @picturePreview="picturePreview"
                :class="{ disabled:this.paramsData.type === 'view'}"
                v-on:up="handleFileChange('elForm','enterpriseQualificationFiles')"
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="four">
            <span slot="label"><i style="color:red">*</i> 安全协议书</span>
            <el-form-item label-width="20px" label="" prop="securityAgreementFiles">
              <upload-file
                :limit="9"
                :accept="accept"
                v-on:delFile="delFile"
                :uploadList.sync="formData.securityAgreementFiles"
                @picturePreview="picturePreview"
                :class="{ disabled:this.paramsData.type === 'view'}"
                v-on:up="handleFileChange('elForm','securityAgreementFiles')"
                :style="{width: '100%'}"
              />
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane name="five">
            <span slot="label"><i style="color:red">*</i> 监理规划</span>
            <el-form-item label-width="20px" label="" prop="supervisionPlanningFiles">
              <upload-file
                :limit="9"
                :accept="accept"
                :uploadList.sync="formData.supervisionPlanningFiles"
                v-on:delFile="delFile"
                @picturePreview="picturePreview"
                :class="{ disabled:this.paramsData.type === 'view'}"
                v-on:up="handleFileChange('elForm','supervisionPlanningFiles')"
                :style="{width: '100%'}"
              />
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane name="six">
            <span slot="label"><i style="color:red">*</i> 实施细则</span>
            <el-form-item label-width="20px" label="" prop="implementationRulesFiles">
              <upload-file
                :limit="9"
                :accept="accept"
                v-on:delFile="delFile"
                :uploadList.sync="formData.implementationRulesFiles"
                @picturePreview="picturePreview"
                :class="{ disabled:this.paramsData.type === 'view'}"
                v-on:up="handleFileChange('elForm','implementationRulesFiles')"
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="审批信息" name="seven">
            <bns-timeline-tabs :is-examine="false" :btn-show="false"
                               final-check="0"
                               :show-type="1"
                               :items="approvalItems"
            />
          </el-tab-pane>
        </el-tabs>
        <el-dialog title="文件预览" :visible.sync="fileOpen" width="80%" append-to-body>
          <div style="width: 100%;height:720px">
            <bns-kkFile-preview
              :items="fileItems"
            ></bns-kkFile-preview>
          </div>
        </el-dialog>
      </el-main>
    </el-form>
    <el-footer style="border-top: 1px solid gray;padding: 10px;display: flex;justify-content: flex-end"  v-if="this.paramsData.type !== 'view'">
      <el-button type="primary" plain style="float:right" @click="cancel"
      >取消
      </el-button>
      <el-button type="primary" style="float:right;margin-right: 10px;" @click="submitForm('elForm','提交')" v-preventReClick="5000"
      >提交审核
      </el-button>
      <el-button type="primary" style="float:right;margin-right: 10px;" @click="submitForm('elForm','保存')" v-preventReClick="5000"
      >保存
      </el-button>
    </el-footer>
    <!--监理人员基本信息查看-->
    <el-dialog :title="'查看详情'" :visible.sync="supervisorOpen" width="60%">
      <el-form ref="form" :model="form" size="medium" label-width="100px" :rules="rules"  v-if="supervisorOpen">
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="11">
            <el-form-item label-width="120px" label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" clearable maxlength="20" show-word-limit
                        :style="{width: '100%'}" v-no-whitespace
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="120px" label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别" clearable
                         :style="{width: '100%'}"
              >
                <el-option label="男" :value="0"></el-option>
                <el-option label="女" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="11">
            <el-form-item label-width="120px" label="年龄" prop="age">
              <el-input v-model="form.age" placeholder="请输入年龄" clearable maxlength="2" show-word-limit
                        :style="{width: '100%'}" v-no-whitespace
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="120px" label="身份证号码" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号码" clearable maxlength="18"
                        show-word-limit v-no-whitespace
                        :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="11">
            <el-form-item label-width="120px" label="联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系方式" clearable maxlength="11"
                        show-word-limit v-no-whitespace
                        :style="{width: '100%'}" :disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="120px" label="岗位" prop="postName">
              <el-select v-model="form.postName" placeholder="请选择岗位" :style="{width: '100%'}" clearable>
                <el-option v-for="(item,index) in postList" :key="item.value" :label="item.label"
                           :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="24">
            <el-form-item label-width="120px" label="人脸照片" :style="{width:'100%'}" prop="facePhoto">
              <upload-file
                :limit="1"
                accept=".png, .jpg, .jpeg"
                :uploadList.sync="form.facePhoto"
                @picturePreview="picturePreview"
                v-on:up="handleFileChange('form','facePhoto')"
                :style="{width: '100%'}"
              />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="24">
            <el-form-item label-width="120px" label="体检文件" prop="physicalExaminationFile">
              <upload-file
                :limit="5"
                :accept="accept"
                v-on:delFile="delFile"
                :uploadList.sync="form.physicalExaminationFile"
                @picturePreview="picturePreview"
                v-on:up="handleFileChange('form','physicalExaminationFile')"
                :style="{width: '100%'}"
              />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="24">
            <el-form-item label-width="120px" label="保险文件" prop="insuranceFile">
              <upload-file
                :limit="5"
                :accept="accept"
                v-on:delFile="delFile"
                :uploadList.sync="form.insuranceFile"
                @picturePreview="picturePreview"
                v-on:up="handleFileChange('form','insuranceFile')"
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" :gutter="gutterValue">
          <el-col :span="24">
            <el-form-item label-width="120px" label="其他文件">
              <upload-file
                :limit="5"
                :accept="accept"
                v-on:delFile="delFile"
                :uploadList.sync="form.otherFileList"
                @picturePreview="picturePreview"
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="submitPersonForm" type="primary" v-preventReClick="5000">保存</el-button>
        <el-button @click="cancelPerson">关闭</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
import { getFileData, getParams, hideSensitiveInfo, indexContinuous, lookFaceFile } from '@/utils/bonus'
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 BnsSupervisorInfoTabs from '@/components/pro-tabs/bns-supervisor-info-tabs.vue'
import bnsGenerateWorkCardTabs from '@/components/pro-tabs/bns-generate-work-card-tabs.vue'
import bnsFileListTabs from '@/components/pro-tabs/bns-file-list-tabs.vue'

import { addSupervisoryApply, addSupervisoryPersonApply } from '@/api/pro/supervisory'
import { dictTableOption, getTemplateLink, selectFile, downloadFile } from '@/api/tool/select'
import { listSupervisorPersonById, listSupervisor, listSupervisorPerson } from '@/api/pro/outsourcingPro'

import numberUtils from '@/utils/validate'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'
import { judgeIsFileComplete, submitApproval } from '@/api/pro/admissionRequest'
import { decryptCBC } from '@/utils/aescbc'
import { importPersonZip, importPersonData } from '@/api/importData/importData'
import XLSX from '@/utils/xlsx.full.min'
import { StrUtil } from '@/utils/StrUtil'
import { approvalHistory } from '@/api/terminalEquipment/deviceInformation'

export default {
  components: {
    bnsKkFilePreview,
    bnsFileListTabs,
    bnsGenerateWorkCardTabs, BnsSupervisorInfoTabs, BnsTimelineTabs, BnsEquipDetailsTabs, uploadFile
  },
  data() {
    return {
      paramsData: {},
      disabled: false,
      delFileIds: [],
      loading: false,
      fileUuid: '',
      personId: '',
      activeName: 'first',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      total: 0,
      supervisorOpen: false,
      supervisorList: [],
      fileOpen: false,
      document: false,
      documentPreview: false,
      fileList: [],
      kkFilePreview: {
        filePreviewUrl: '',
        fileName: '',
        showDownloadButton: false
      },
      fileItems: {},
      postList: [],
      form: {
        physicalExaminationFile: [],
        insuranceFile: [],
        facePhoto: [],
        otherFileList: []
      },
      formData: {
        supervisionInfo: {},
        enterpriseQualificationFiles: [],
        securityAgreementFiles: [],
        supervisionPlanningFiles: [],
        implementationRulesFiles: []
      },

      active: 1,
      importedCount: 0,
      importProgress: 0,
      status: 'success',
      excelData: [],
      errorLine: [],
      errorPhone: [],
      errorCode: '',
      type: '',
      formPerson: {
        fileList: [],
        proId: undefined,
        uploadType: undefined
      },
      rulesPerson: {
        fileList: [
          { required: true, message: '请先选择需要导入的excel文件', trigger: 'blur' }
        ]
      },

      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '上传压缩文件'
      },
      formFile: {
        fileList: []
      },
      ruleFile: {
        fileList: [
          { required: true, message: '请上传文件', trigger: 'blur' }
        ]
      },

      personBasicOpen: false,
      gutterValue: parseInt('21', 10),
      accept: '.png, .jpg, .jpeg, .docx, .doc, .xlsx, .xls, .ppt, .pptx, .pdf',
      rule: {
        enterpriseQualificationFiles: [
          { required: true, message: '请上传企业资质文件', trigger: 'blur' }
        ],
        securityAgreementFiles: [
          { required: true, message: '请上传安全协议书', trigger: 'blur' }
        ],
        supervisionPlanningFiles: [
          { required: true, message: '请上传监理规划', trigger: 'blur' }
        ],
        implementationRulesFiles: [
          { required: true, message: '请上传实施细则', trigger: 'blur' }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入监理姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请输入性别', trigger: 'change' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          {
            pattern: /^[0-9]+$/,
            message: '请输入数字',
            trigger: 'blur'
          }
        ],
        idCard: [
          { required: true, validator: numberUtils.checkIdCardNumber, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: numberUtils.checkPhone, trigger: 'blur' }
        ],
        postName: [
          { required: true, message: '请输入岗位', trigger: 'change' }
        ],
        // facePhoto: [
        //   { required: true, message: '请上传人脸照片', trigger: 'change' }
        // ],
        physicalExaminationFile: [
          { required: true, message: '请上传体检文件', trigger: 'change' }
        ],
        insuranceFile: [
          { required: true, message: '请上传保险文件', trigger: 'change' }
        ]
      },
      lookFaceFile: '',
      templateLink:'',
      approvalItems: []
    }
  },
  created() {
    this.lookFaceFile = lookFaceFile()
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    //查询企业资质、安全协议书、监理规划、实施细则数据回显
    this.getEnterpriseQualificationFile()
    this.getSecurityAgreementFile()
    this.getSupervisionPlanningFile()
    this.getImplementationRulesFile()
    this.getStatus()
    this.getSupervisorList()
    this.approvalHistory()
  },
  methods: {
    indexContinuous,
    hideSensitiveInfo,
    getParams,
    getFileData,
    approvalHistory() {
      console.log('this.paramsData.taskId:' + this.paramsData.taskId)
      approvalHistory({ taskId: this.paramsData.taskId }).then(res => {
        this.approvalItems = res.data
      })
    },
    getTemplateLink(){
      const params = {
        dictType: 'sys_template_link',
        dictValue: '1'
      }
      getTemplateLink(params).then(response => {
        this.templateLink = response.msg
      })
    },
    /** 文件查看按钮操作 */
    handleShow(row, informationType) {
      // console.log("row="+JSON.stringify(row))
      // console.log("informationType="+informationType)
      this.loading = true
      const arr = {
        1: '体检文件',
        2: '保险文件',
        3: '特殊工种文件',
        4: '其他文件'
      }
      selectFile({
        classification: 9,
        uuid: row.uuid,
        informationType: informationType,
        fromType: 3
      }).then(response => {
        console.log(response)
        if (response.data.length === 0) {
          this.fileList = []
          this.$message.warning(arr[informationType] + '暂无')
        } else if (response.data.length === 1) {
          this.kkFilePreview = {
            filePreviewUrl: response.data[0].filePath,
            fileName: response.data[0].fileName,
            showDownloadButton: false
          }
          this.documentPreview = true
        } else {
          this.fileList = response.data
          this.document = true
        }
        this.loading = false
      })
    },
    handleFileChange(form, name) {
      // 手动校验
      this.$refs[form].validateField(name)
    },
    //上传组件-图片查看
    picturePreview(file) {
      console.log(file)
      this.fileItems = {
        filePreviewUrl: file.filePreviewUrl,
        fileName: file.name
      }
      this.fileOpen = true
    },
    delFile(e) {
      if (!this.delFileIds.includes(e)) {
        this.delFileIds.push(e)
      }
    },
    /**获取企业资质文件*/
    getEnterpriseQualificationFile() {
      const params = {
        id: this.$store.state.user.thisIds.proId,
        classification: '1',
        fromType: '1',
        informationType: '1',
        uuid : this.$store.state.user.thisIds.uuid
      }
      selectFile(params).then(response => {
        this.formData.enterpriseQualificationFiles = response.data
      })
    },
    /**获取安全协议书文件*/
    getSecurityAgreementFile() {
      const params = {
        id: this.$store.state.user.thisIds.proId,
        classification: '1',
        fromType: '1',
        informationType: '2',
        uuid : this.$store.state.user.thisIds.uuid
      }
      selectFile(params).then(response => {
        this.formData.securityAgreementFiles = response.data
      })
    },
    /**获取监理规划文件*/
    getSupervisionPlanningFile() {
      const params = {
        id: this.$store.state.user.thisIds.proId,
        classification: '1',
        fromType: '1',
        informationType: '9',
      }
      selectFile(params).then(response => {
        this.formData.supervisionPlanningFiles = response.data
      })
    },
    /**获取实施细则文件*/
    getImplementationRulesFile() {
      const params = {
        id: this.$store.state.user.thisIds.proId,
        classification: '1',
        fromType: '1',
        informationType: '10'
      }
      selectFile(params).then(response => {
        this.formData.implementationRulesFiles = response.data
      })
    },
    /**获取监理单位基本信息*/
    getSupervisorList() {
      this.loading = true
      const params = {
        proId: this.$store.state.user.thisIds.proId,
        supUuid: this.$store.state.user.thisIds.supUuid
      }
      listSupervisor(params).then(response => {
        this.formData.supervisionInfo = response.data
        this.formData.supervisionInfo.corporatePhone = hideSensitiveInfo(response.data.corporatePhone)
        this.init()
        this.loading = false
      })
    },
    init() {
      this.getSupervisorPersonList()
    },
    /**监理人员基本信息查询*/
    getSupervisorPersonList() {
      this.loading = true
      const params = {
        proId: this.$store.state.user.thisIds.proId,
        supUuid: this.$store.state.user.thisIds.supUuid,
        ...this.queryParams
      }
      listSupervisorPerson(params).then(response => {
        console.log(response)
        this.supervisorList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getStatus() {
      const params = {
        dictType: 'sys_sup_post',
        dictValue: ''
      }
      dictTableOption(params).then(response => {
        this.postList = response.data
      })
    },
    submitForm(formName, submitType) {
      this.loading = true
      let isReturn = false
      if (submitType === '提交') {
        const param = {
          ...this.getParams(),
          taskType: '1',
          taskId: this.paramsData.type === 'edit' ? this.paramsData.taskId : '',
          uuid: this.$store.state.user.thisIds.uuid,
          parentUuid: this.$store.state.user.thisIds.parentUuid
        }
        if (this.formData.enterpriseQualificationFiles.length === 0 || this.formData.securityAgreementFiles.length === 0
          || this.formData.supervisionPlanningFiles.length === 0 || this.formData.implementationRulesFiles.length === 0) {
          this.$message({
            message: '请先上传企业资质、安全协议书、监理规划、实施细则文件！',
            type: 'error'
          })
          this.loading = false
          return false
        }
        //查询判断当前下所以人员文件是否上传


        try {
          const response = judgeIsFileComplete(param)
          console.log('response=====', response)
          if (response.msg === '部分人员文件不存在，请先仔细核对，上传相关文件！') {
            this.$message({
              message: '部分人员文件不存在，请先仔细核对，上传相关文件！',
              type: 'error'
            })
            // return false
            isReturn = true
          }
        } catch (error) {
          this.$message({
            message: '文件检查失败，请稍后重试！',
            type: 'error'
          })
          // return false
        }
      }

      if(isReturn)  return
      this.$refs[formName].validate((valid) => {
          if (submitType === '提交' && !valid) {
            return this.$modal.msgError('请完善全部上传信息')
          }
          console.log(this.formData)
          const reqData = new FormData()
          this.formData.proId = this.$store.state.user.thisIds.proId
          this.formData.supId = this.$store.state.user.thisIds.supId
          this.formData.supUuid = this.$store.state.user.thisIds.supUuid
          this.formData.uuid = this.$store.state.user.thisIds.uuid
          this.formData.delFileIds = this.delFileIds.join(',')
          this.formData.submitType = submitType
          reqData.append('params', JSON.stringify(this.formData))

          // 使用 Promise.all 并行处理文件数据获取，提高效率
          Promise.all([
            this.getFileData(this.formData.enterpriseQualificationFiles),
            this.getFileData(this.formData.securityAgreementFiles),
            this.getFileData(this.formData.supervisionPlanningFiles),
            this.getFileData(this.formData.implementationRulesFiles)
          ]).then(([enterpriseQualificationFiles, securityAgreementFiles, supervisionPlanningFiles, implementationRulesFiles]) => {
            if (!enterpriseQualificationFiles || enterpriseQualificationFiles.length === 0) {
              reqData.append('enterpriseQualificationFiles', new Blob())
            } else {
              enterpriseQualificationFiles.forEach(item => reqData.append('enterpriseQualificationFiles', item))
            }
            if (!securityAgreementFiles || securityAgreementFiles.length === 0) {
              reqData.append('securityAgreementFiles', new Blob())
            } else {
              securityAgreementFiles.forEach(item => reqData.append('securityAgreementFiles', item))
            }
            if (!supervisionPlanningFiles || supervisionPlanningFiles.length === 0) {
              reqData.append('supervisionPlanningFiles', new Blob())
            } else {
              supervisionPlanningFiles.forEach(item => reqData.append('supervisionPlanningFiles', item))
            }
            if (!implementationRulesFiles || implementationRulesFiles.length === 0) {
              reqData.append('implementationRulesFiles', new Blob())
            } else {
              implementationRulesFiles.forEach(item => reqData.append('implementationRulesFiles', item))
            }
            addSupervisoryApply(reqData).then(response => {
              if (submitType === '提交') {
                this.submitApply()
              } else {
                this.loading = false
                this.$modal.msgSuccess('保存成功')
                this.$tab.closePage()
              }

            }).catch(error => {
              // 增加错误处理
              this.loading = false
              this.$modal.msgError('提交失败')
            })
          })
      })
    },
    /**
     * 提交审批
     */
    submitApply() {
      console.log(this.getParams())
      const param = {
        ...this.getParams(),
        taskType: '1',
        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))
        this.loading = false
        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(response.msg)
          this.$tab.closePage()
          this.$router.push({ path: '/index', query: { result: 1 } })
        }
      })
    },

    submitPersonForm() {
      this.loading = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.form)
          const reqData = new FormData()
          this.form.proId = this.$store.state.user.thisIds.proId
          this.form.supId = this.$store.state.user.thisIds.supId
          this.form.supUuid = this.$store.state.user.thisIds.supUuid
          if (this.personId === '') {
            this.form.id = ''
          }
          this.form.delFileIds = this.delFileIds.join(',')
          console.log( JSON.stringify(this.form))
          reqData.append('params', JSON.stringify(this.form))

          // 使用 Promise.all 并行处理文件数据获取，提高效率
          Promise.all([
            this.getFileData(this.form.facePhoto),
            this.getFileData(this.form.physicalExaminationFile),
            this.getFileData(this.form.insuranceFile),
            this.getFileData(this.form.otherFileList)
          ]).then(([facePhoto, physicalExaminationFile, insuranceFile, otherFileList]) => {
            if (!facePhoto || facePhoto.length === 0) {
              reqData.append('facePhoto', new Blob())
            } else {
              facePhoto.forEach(item => reqData.append('facePhoto', item))
            }
            if (!physicalExaminationFile || physicalExaminationFile.length === 0) {
              reqData.append('physicalExaminationFile', new Blob())
            } else {
              physicalExaminationFile.forEach(item => reqData.append('physicalExaminationFile', item))
            }
            if (!insuranceFile || insuranceFile.length === 0) {
              reqData.append('insuranceFile', new Blob())
            } else {
              insuranceFile.forEach(item => reqData.append('insuranceFile', item))
            }
            if (!otherFileList || otherFileList.length === 0) {
              reqData.append('otherFileList', new Blob())
            } else {
              otherFileList.forEach(item => reqData.append('otherFileList', item))
            }
            addSupervisoryPersonApply(reqData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.supervisorOpen = false
              this.delFileIds = []
              this.getSupervisorPersonList()
              this.loading = false
            }).catch(error => {
              this.loading = false
              // 增加错误处理
              this.$modal.msgError('新增失败：' + error.message)
            })
          })
        } else {
          return false
        }
      })
    },
    cancel() {
      this.$tab.closePage()
    },
    cancelPerson() {
      this.supervisorOpen = false
      this.resetForm()
    },
    resetForm() {
      this.resetForm('elForm')
    },
    //新增监理人员
    handleAdd() {
      this.form = {
        name: '',
        age: '',
        sex: '',
        idCard: '',
        phone: '',
        postName: '',
        physicalExaminationFile: [],
        insuranceFile: [],
        facePhoto: [],
        otherFileList: []
      }
      this.fileUuid = ''
      this.personId = ''
      this.disabled = false
      this.supervisorOpen = true

    },
    //查询
    handleQuery() {
      this.getSupervisorPersonList()
    },
    //重置
    resetQuery() {
      this.queryParams.name = ''
      this.handleQuery()
    },
    //编辑
    handleEdit(row, type) {
      console.log("---------------------------------------------------------");
      this.form.physicalExaminationFile = this.$set( this.form,'physicalExaminationFile', [])
      this.form.insuranceFile = this.$set(this.form,'insuranceFile',  [])
      this.form.facePhoto = this.$set(this.form,'facePhoto',  [])
      this.form.otherFileList = this.$set(this.form, 'otherFileList', [])

      this.getDetails(row)
      this.disabled = true
      if (type === 1) {
        this.disabled = false
      }
      this.supervisorOpen = true
    },
    //获取详情
    getDetails(row) {
      this.loading = true
      const params = {
        id: row.id,
        proId: row.proId,
        uuid: row.uuid,
        supUuid: row.supUuid
      }

      listSupervisorPersonById(params).then(response => {
        console.log(response)
        this.form = {...response.data}
        this.fileUuid = response.data.id
        this.personId = response.data.uuid
        this.loading = false
      })
    },
    /**
     * 人员基础数据上传
     */
    handlePersonImport() {
      this.getTemplateLink();
      this.personBasicOpen = true
      this.formPerson.fileList = []
    },
    next() {
      if (this.formPerson.fileList.length === 0) {
        this.$message.warning('请先选择需要导入的excel文件')
        return
      }
      this.active++
      this.status = 'success'
    },
    personClose() {
      this.personBasicOpen = false
      this.formPerson.fileList = []
    },
    before() {
      this.active--
      this.status = 'success'
      if (this.active === 1) {
        this.excelData = []
        this.errorCode = ''
        this.errorPhone = []
        this.errorLine = []
        this.fileList = []
        this.formPerson.fileList = []
      }
    },
    downloadTemplate() {
      downloadFile(this.templateLink, '监理人员模板.zip')
    },
    importExcel() {
      this.loading = true
      let data = []
      for (let i = 1; i < this.excelData.length; i++) {
        data.push(this.excelData[i])
      }
      const param = {
        proId: this.$store.state.user.thisIds.proId,
        consUuid: this.$store.state.user.thisIds.consUuid,
        subUuid: this.$store.state.user.thisIds.subUuid,
        supUuid: this.$store.state.user.thisIds.supUuid,
        uuid: this.$store.state.user.thisIds.uuid,
        userType: this.$store.state.user.userType,
        importArgList: data
      }
      importPersonData(param).then(response => {
        if (response.code === 200) {
          if (response.msg === '导入成功') {
            this.$modal.msgSuccess('导入成功')
            this.active = 4
            this.formPerson.fileList = []
            this.excelData = []
            this.getSupervisorPersonList()
            this.loading = false
          } else {
            this.errorCode = response.msg
            this.active = 3
            this.status = 'error'
          }
        }
      })
    },
    beforePersonUpload(file) {
      const isExcel = /\.(xlsx|xls)$/.test(file.name)
      if (!isExcel) {
        this.$message.error('只能上传.xlsx、.xls 文件!')
        this.formPerson.fileList = []
        return false
      }
      return true
    },
    /** 获取文件数据 */
    filePersonChange(file, fileList) {
      console.log(fileList)
      const isExcel = /\.(xlsx|xls)$/.test(file.name)
      if (!isExcel) {
        this.$message.error('只能上传.xlsx、.xls 文件!')
        this.formPerson.fileList = []
        return false
      }
      // 检查文件大小
      if (file.size > 1024 * 1024 * 10) { // 10MB 限制
        this.$message.warning('文件大小不能超过10MB')
        fileList = fileList.filter(item => item.uid !== file.uid)
      } else {
        const reader = new FileReader()

        reader.onload = (e) => {
          if (e.target && e.target.result) {
            try {
              const data = new Uint8Array(e.target.result)
              console.log('读取成功:', data)
              const workbook = XLSX.read(data, { type: 'array' })
              const firstSheetName = workbook.SheetNames[0]
              const worksheet = workbook.Sheets[firstSheetName]
              let jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
              const maxColumns = jsonData.reduce((max, row) => Math.max(max, row.length), 0)

              if (maxColumns !== 7) {
                this.active = 1
                this.formPerson.fileList = []
                this.$message.warning('请选择正确的excel进行数据导入！')
              }
              // 计算最大行数
              const maxRows = jsonData.length
              if (maxRows === 1) {
                this.active = 1
                this.formPerson.fileList = []
                this.$message.warning('表格数据为空，请先填写相关数据，再进行导入')
              }
              this.errorLine = []
              let uuid = StrUtil.generateSimpleUUID()
              for (let i = 0; i < jsonData.length; i++) {
                if (StrUtil.isBlank(jsonData[i][1]) || StrUtil.isBlank(jsonData[i][2]) || StrUtil.isBlank(jsonData[i][3]) || StrUtil.isBlank(jsonData[i][4])
                  || StrUtil.isBlank(jsonData[i][5]) || StrUtil.isBlank(jsonData[i][6])) {
                  this.errorLine.push(jsonData[i][0])
                }
                const rowData = {
                  arg0: jsonData[i][0],
                  arg1: jsonData[i][1],
                  arg2: jsonData[i][2],
                  arg3: jsonData[i][3],
                  arg4: jsonData[i][4],
                  arg5: jsonData[i][5],
                  arg6: jsonData[i][6],
                  uuid: uuid,
                  personType: jsonData[i][6] === '监理负责人' ? '1' : '2',
                  sex: jsonData[i][2] === '男' ? '0' : '1'
                }
                const isDuplicate = this.excelData.some(item => item.arg5 === rowData.arg5)
                if (isDuplicate) {
                  this.errorPhone.push(rowData.arg5)
                }
                this.excelData.push(rowData)
              }
              if (this.excelData.length > 999) {
                this.$message.warning('数据量大于1000行')
              }
            } catch (error) {
              console.error('处理 Excel 文件时出错:', error)
            }
          } else {
            console.error('文件读取结果无效:', e.target)
          }
        }
        reader.onerror = (error) => {
          console.error('文件读取错误:', error)
        }

        // 确保 file.raw 存在并有效
        if (file.raw) {
          reader.readAsArrayBuffer(file.raw)
        } else {
          console.error('文件对象无效')
        }
      }

      // 更新 fileList 状态
      this.formPerson.fileList = fileList
    }
    ,
    //移除文件
    handlePersonRemove(file) {
      this.formPerson.fileList.splice(this.formPerson.fileList.indexOf(file), 1)
      this.$emit('input', this.listToString(this.formPerson.fileList))
    },

    /**
     * 人员文件上传
     */
    handleFileImport() {
      this.upload.title = '上传压缩文件'
      this.upload.open = true
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = ''
      separator = separator || ','
      for (let i in list) {
        strs += list[i].url + separator
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : ''
    },
    beforeUpload(file) {
      console.log('beforeUpload')
      const isZip = /\.(zip|ZIP|Zip)$/.test(file.name)

      if (!isZip) {
        this.$message.error('只能上传.zip 文件!')
        return false
      }
      return true
    },
    /** 获取文件数据 */
    fileChange(file, fileList) {
      // 检查文件大小
      if (file.size > 1024 * 1024 * 500) { // 10MB 限制
        this.$message.warning('文件大小不能超过500MB')
        fileList = fileList.filter(item => item.uid !== file.uid)
      }
      // 更新 fileList 状态
      this.formFile.fileList = fileList
    },
    //移除文件
    handleRemove(file) {
      this.formFile.fileList.splice(this.formFile.fileList.indexOf(file), 1)
      this.$emit('input', this.listToString(this.formFile.fileList))
    },
    submitFileForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.formFile.fileList[0].name.toLowerCase().endsWith('.zip')) {
            this.$message.error('请上传zip文件')
            this.formFile.fileList = []
            return
          }
          const reqData = new FormData()
          reqData.append('proId', this.$store.state.user.thisIds.proId)
          reqData.append('consUuid', this.$store.state.user.thisIds.consUuid)
          reqData.append('subUuid', this.$store.state.user.thisIds.subUuid)
          reqData.append('supUuid', this.$store.state.user.thisIds.supUuid)
          reqData.append('uuid', this.$store.state.user.thisIds.uuid)
          reqData.append('userType', this.$store.state.user.userType)

          Promise.all([
            this.getFileData(this.formFile.fileList)
          ]).then(([fileList]) => {
            fileList.forEach(item => reqData.append('fileList', item))
            importPersonZip(reqData).then(response => {
              if (response.code === 200) {
                console.log(response)
                if (response.result === '无数据问题') {
                  this.$modal.msgSuccess('导入成功')
                  this.upload.open = false
                  this.formFile.fileList = []
                } else {
                  let content
                  if (response.result.split('&&').length === 1) {
                    content = '<span>' + response.result.split('&&')[0] + '</span>'
                  } else {
                    content = '<span>' + response.result.split('&&')[0] + '<br/>' + response.result.split('&&')[1] + '</span>'
                  }
                  this.$confirm(content, '文件导入提示', {
                    cancelButtonText: '关闭',
                    type: 'warning',
                    dangerouslyUseHTMLString: true
                  })
                    .catch(() => {
                      // 取消
                    })
                }
                this.upload.open = false
                this.getSupervisorPersonList()
                this.formFile.fileList = []
              }
            })
          })
        } else {
          return false
        }
      })
    }
  }

}
</script>
<style scoped>

</style>
