<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="施工人员" prop="consName">
        <el-input
          v-model="queryParams.consName"
          placeholder="请输入施工人员姓名"
          v-no-whitespace
          maxlength="20"
          show-word-limit
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
          <el-option v-for="dict in statusDict" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:addPersonnel:query']"
        >
          新增
        </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-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceInformation" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="姓名" show-overflow-tooltip width="150" align="center" prop="consName" />
      <el-table-column label="岗位" width="150" align="center" prop="post" />
      <el-table-column label="特殊工种种类" width="150" align="center" prop="workType" />
      <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, 3)">查看</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="性别" width="60" align="center" prop="sex" />
      <el-table-column label="年龄" width="60" 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="籍贯" show-overflow-tooltip width="150" align="center" prop="natives" />
      <el-table-column label="身份证号码" width="160" align="center">
        <template slot-scope="scope">
          <!-- 检查是否存在身份证号 -->
          <span v-if="scope.row.idCard">{{ hideSensitiveInfo(scope.row.idCard) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="民族" width="60" align="center" prop="nation" />
      <el-table-column label="家庭住址" show-overflow-tooltip width="150" align="center" prop="homeAddress" />
      <el-table-column label="现住址" show-overflow-tooltip width="150" align="center" prop="address" />
      <el-table-column label="人脸照片" align="center" prop="faceUrl">
        <template slot-scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img
              :src="`${scope.row.facePath ? lookFaceFile + scope.row.facePath : ''}`"
              :min-width="300"
              :height="300"
              alt="照片"
            />
            <img
              slot="reference"
              :src="`${scope.row.facePath ? lookFaceFile + scope.row.facePath : ''}`"
              style="max-height: 50px; max-width: 50px"
              :alt="`${scope.row.facePath ? lookFaceFile + scope.row.facePath : ''}`"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="intoStatus">
        <template slot-scope="scope">
          <!-- 检查是否存在身份证号 -->
          <span v-if="scope.row.intoStatus">{{ updateStatus(scope.row.intoStatus) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.intoStatus == '0'"
            size="mini"
            type="text"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['system:addPersonnel:query']"
          >
            提交审核
          </el-button>
          <el-button
            v-if="scope.row.intoStatus == '3' || scope.row.intoStatus == '2'"
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['system:addPersonnel:query']"
          >
            查看
          </el-button>
          <el-button
            v-if="scope.row.intoStatus == '0' || scope.row.intoStatus == '4' || scope.row.intoStatus == '5'"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:addPersonnel:query']"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.intoStatus == '1'"
            size="mini"
            type="text"
            @click="retractApproval(scope.row)"
            v-hasPermi="['system:addPersonnel:query']"
          >
            撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="auditRecord(scope.row)"
            :style="{ color: '#f59a24' }"
            v-hasPermi="['system:audit:query']"
          >
            审核记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <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="statusUpload" 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%;
              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>
            <el-button type="text" style="float: left; margin-top: 10px; width: 60px" @click="downloadTemplate">
              下载模板
            </el-button>
            <!--                      <span style="font-size: 16px;color: #8a8a8a;margin-top: 10px;cursor: pointer" @click="downloadTemplate"-->
            <!--                      >下载模板</span>-->
          </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="120" align="center" />
              <el-table-column prop="arg5" width="120" align="center" />
              <el-table-column prop="arg6" width="120" align="center" />
              <el-table-column prop="arg7" width="120" align="center" />
              <el-table-column prop="arg8" width="120" align="center" />
              <el-table-column prop="arg9" width="120" align="center" />
              <el-table-column prop="arg10" width="120" align="center" />
              <el-table-column prop="arg11" 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>
    <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="filePreview"></bns-kkFile-preview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFileData,getParams,hideSensitiveInfo, indexContinuous, lookFaceFile } from '@/utils/bonus'
import { dictTableOption, downloadFile, getTemplateLink, selectFile } from '@/api/tool/select'
import { listAdmissionRequest, submitApproval } from '@/api/pro/admissionRequest'
import store from '../../../store'

import { delDeviceInformation, retractApproval } from '@/api/terminalEquipment/deviceInformation'
import { encryptCBC } from '@/utils/aescbc'
import { importPersonData, importPersonZip } from '@/api/importData/importData'
import { StrUtil } from '@/utils/StrUtil'
import * as XLSX from 'xlsx'
import BnsFileListTabs from '@/components/pro-tabs/bns-file-list-tabs.vue'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'
import debounce from 'lodash/debounce'

export default {
  name: 'Post',
  components: { bnsKkFilePreview, BnsFileListTabs },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      userId: store.state.user.id,
      status: ['待提交', '审核中', '已通过', '未通过', '待审批', '已审核'],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      deviceInformation: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      document: false,
      documentPreview: false,
      fileList: [],
      filePreview: {
        filePreviewUrl: '',
        fileName: '',
        showDownloadButton: false,
      },
      // 角色选项
      deviceOptions: [],
      // 控制显示或隐藏的变量
      showDeviceName: false,
      // 默认为新增模式，可编辑
      isEditing: false,
      // 地图是否显示弹出层
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: undefined,
        createUser: undefined,
        deviceUser: undefined,
        deviceType: undefined,
        proId: this.$store.state.user.thisIds.proId,
        supUuid: this.$store.state.user.thisIds.supUuid,
        contUuid: this.$store.state.user.thisIds.contUuid,
        subUuid: this.$store.state.user.thisIds.subUuid,
        userType: this.$store.state.user.thisIds.userType,
        consName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      statusDict: [],
      auditStatusDict: {
        1: '待审批',
        2: '审批中',
        3: '已通过',
        4: '已驳回',
        5: '已撤销',
      },
      lookFaceFile: '',
      active: 1,
      importedCount: 0,
      importProgress: 0,
      statusUpload: 'success',
      excelData: [],
      errorLine: [],
      errorPhone: [],
      errorCode: '',
      type: '',
      formPerson: {
        fileList: [],
        proId: undefined,
        uploadType: undefined,
      },
      rulesPerson: {
        fileList: [{ required: true, message: '请先选择需要导入的excel文件', trigger: 'blur' }],
      },
      personBasicOpen: false,
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '上传压缩文件',
      },
      formFile: {
        fileList: [],
      },
      ruleFile: {
        fileList: [{ required: true, message: '请上传文件', trigger: 'blur' }],
      },
      templateLink: '',
    }
  },
  created() {
    this.lookFaceFile = lookFaceFile()
    this.getStatus()
    this.getList()
  },
  methods: {
    lookFaceFile,
    indexContinuous,
    hideSensitiveInfo,
    getFileData,
    getParams,
    store() {
      return store
    },
    /** 文件查看按钮操作 */
    handleShow(row, informationType) {
      this.loading = true
      const arr = {
        1: '体检文件',
        2: '保险文件',
        3: '特殊工种文件',
        4: '其他文件',
      }
      selectFile({ classification: 9, uuid: row.uuid, informationType: informationType, fromType: 2 }).then(
        response => {
          console.log(response)
          if (response.data.length === 0) {
            this.fileList = []
            this.$message.warning(arr[informationType] + '暂无')
          } else if (response.data.length === 1) {
            this.filePreview = {
              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
        }
      )
    },
    getTemplateLink() {
      const params = {
        dictType: 'sys_template_link',
        dictValue: '2',
      }
      getTemplateLink(params).then(response => {
        this.templateLink = response.msg
      })
    },
    updateStatus(status) {
      return this.auditStatusDict[status]
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true
      this.queryParams.proId = this.$store.state.user.thisIds.proId
      this.queryParams.contUuid = this.$store.state.user.thisIds.consUuid
      this.queryParams.subUuid = this.$store.state.user.thisIds.subUuid
      this.queryParams.userType = this.$store.state.user.userType
      listAdmissionRequest(this.queryParams).then(response => {
        this.deviceInformation = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //获取审核类型下拉选
    getStatus() {
      const params = {
        dictType: 'sys_approval_state',
        dictValue: '',
      }
      dictTableOption(params).then(response => {
        this.statusDict = response.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push(
        '/project/admission-request-auth/addPersonnel/' +
          encryptCBC(
            JSON.stringify({
              type: 'add',
              uuid: 0,
              consUserId: 0,
            })
          )
      )
      this.getList()
    },
    /** 查看按钮操作 */
    handleView(row) {
      const uuid = row.uuid
      const consUserId = row.consUserId
      console.log(uuid)
      this.$router.push(
        '/project/admission-request-auth/addPersonnel/' +
          encryptCBC(
            JSON.stringify({
              type: 'view',
              uuid: uuid,
              consUserId: consUserId,
              taskId: row.taskId,
            })
          )
      )
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const uuid = row.uuid
      const consUserId = row.consUserId
      console.log(uuid)
      this.$router.push(
        '/project/admission-request-auth/addPersonnel/' +
          encryptCBC(
            JSON.stringify({
              type: 'edit',
              uuid: uuid,
              consUserId: consUserId,
              taskId: row.taskId,
            })
          )
      )
    },
    /** 提交审批**/
    handleSubmit(row) {
      console.log(this.getParams())
      let taskId
      if (row.taskId === null || row.taskId === '' || row.taskId === undefined) {
        taskId = ''
      } else {
        taskId = row.taskId
      }
      const param = {
        ...this.getParams(),
        taskId: taskId,
        taskType: this.$store.state.user.userType === '02' ? '5' : '10',
        uuid: row.uuid,
      }
      console.log('param=' + JSON.stringify(param))
      submitApproval(param)
        .then(response => {
          console.log('response=' + JSON.stringify(response))
          if (response.code === 200) {
            this.$message.success(response.msg)
            this.getList()
          } else {
            this.$message.error(response.msg)
          }
        })
        .catch(error => {
          console.log('error=' + JSON.stringify(error))
        })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const addressIds = row.deviceId || this.ids
      this.$modal
        .confirm('是否确认删除工程编号为"' + addressIds + '"的数据项？')
        .then(function () {
          return delDeviceInformation(addressIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    retractApproval(row) {
      const taskId = row.taskId
      const param = {
        taskId: taskId,
        uuid: row.uuid,
        procInstId: row.procInsId,
        taskType: this.$store.state.user.userType === '02' ? '5' : '10',
      }
      console.log('param=' + JSON.stringify(param))
      this.$modal
        .confirm('是否撤回此人员审核申请？')
        .then(function () {
          return retractApproval(param)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('流程撤回成功！')
        })
        .catch(() => {})
    },
    auditRecord(row) {
      this.$router.push(
        '/flow/auditRecord/' +
          encryptCBC(
            JSON.stringify({
              taskId: row.taskId,
              checkType: '2',
            })
          )
      )
    },
    /**
     * 人员基础数据上传
     */
    handlePersonImport() {
      this.getTemplateLink()
      this.personBasicOpen = true
      this.formPerson.fileList = []
    },
    next() {
      if (this.formPerson.fileList.length === 0) {
        this.$message.warning('请先选择需要导入的excel文件')
        return
      }
      this.active++
      this.statusUpload = 'success'
    },
    personClose() {
      this.personBasicOpen = false
      this.formPerson.fileList = []
    },
    before() {
      this.active--
      this.statusUpload = 'success'
      if (this.active === 1) {
        this.excelData = []
        this.errorCode = ''
        this.errorPhone = []
        this.errorLine = []
        this.fileList = []
        this.formPerson.fileList = []
      }
    },
    downloadTemplate() {
      downloadFile(this.templateLink, '施工人员.zip')
    },

    importExcel: debounce(function () {
      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.getSubPersonList()
            this.loading = false
          } else {
            this.errorCode = response.msg
            this.active = 3
            this.statusUpload = 'error'
          }
        }
      })
    }, 500),

    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 !== 12) {
                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]) ||
                  StrUtil.isBlank(jsonData[i][7]) ||
                  StrUtil.isBlank(jsonData[i][8]) ||
                  StrUtil.isBlank(jsonData[i][9]) ||
                  StrUtil.isBlank(jsonData[i][10])
                ) {
                  this.errorLine.push(jsonData[i][0])
                } else {
                  if (jsonData[i][10] === '特殊工种' && StrUtil.isBlank(jsonData[i][11])) {
                    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],
                  arg7: jsonData[i][7],
                  arg8: jsonData[i][8],
                  arg9: jsonData[i][9],
                  arg10: jsonData[i][10],
                  arg11: jsonData[i][11],
                  uuid: uuid,
                  personType: jsonData[i][10] === '特殊工种' ? '1' : jsonData[i][10] === '普通职工' ? '2' : '0',
                  sex: jsonData[i][2] === '男' ? '0' : '1',
                }
                const isDuplicate = this.excelData.some(item => item.arg4 === rowData.arg4)
                if (isDuplicate) {
                  this.errorPhone.push(rowData.arg4)
                }
                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 * 200) {
        // 10MB 限制
        this.$message.warning('文件大小不能超过200MB')
        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 => {
        console.log("--->")
        console.log(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('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.getSubPersonList()
                this.formFile.fileList = []
              }
            })
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>
