<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick" :style="{ padding: '20px' }">
      <el-tab-pane label="人员信息" name="first">
        <div class="app-container">
          <el-form ref="form" :model="form" size="medium" label-width="100px" :rules="rules">
            <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%' }"
                  ></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" class="dialog-footer" v-if="showOrNot" style="float: right">
            <el-button type="primary" @click="submitForm" v-preventReClick="5000">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="审批信息" name="second">
        <bns-timeline-tabs
          :items="approvalInfo"
          :show-type="1"
          :is-examine="false"
          :btn-show="false"
          :auditReason="[]"
        ></bns-timeline-tabs>
      </el-tab-pane>
    </el-tabs>
    <!-- 图片查看弹窗 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" height="650px" :src="dialogImageUrl" alt />
    </el-dialog>
    <!-- 文件预览弹窗 -->
    <el-dialog title="文件预览" :visible.sync="viewOpen" width="90%" append-to-body>
      <div style="width: 100%; height: 720px">
        <bns-kkFile-preview :items="filePreview"></bns-kkFile-preview>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { dictTableOption } from '@/api/tool/select'
import Treeselect from '@riophae/vue-treeselect'
import uploadFile from './uploadFile.vue'
import { left } from 'core-js/internals/array-reduce'
import { addAdmissionRequest, getData } from '@/api/pro/admissionRequest'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'
import { hideSensitiveInfo, parseTime } from '@/utils/bonus'
import numberUtils from '@/utils/validate'
import { approvalHistory } from '@/api/terminalEquipment/deviceInformation'
import BnsTimelineTabs from '@/components/pro-tabs/bns-timeline-tabs.vue'
import { decryptCBC } from '@/utils/aescbc'

import { addSupervisoryPersonApply } from '@/api/pro/supervisory'

export default {
  components: { BnsTimelineTabs, bnsKkFilePreview, Treeselect, uploadFile },
  data() {
    return {
      delFileIds: [],
      proId: undefined,
      //当前激活的标签页
      activeName: 'first',
      //监理信息单位弹出层
      supervisorOpen: false,
      //生成工作证弹出层
      workCardOpen: false,
      //是否显示特殊工种
      showSpecialWorkType: false,
      gutterValue: parseInt('21', 10),
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: true,
      showOrNot: true,
      approvalInfo: [],
      // 表单参数
      form: {
        name: '',
        age: '',
        sex: '',
        idCard: '',
        phone: '',
        postName: '',
        physicalExaminationFile: [],
        insuranceFile: [],
        facePhoto: [],
        otherFileList: [],
      },
      postList: [],
      //对齐方式
      labelPosition: 'top',
      // 岗位选项
      deviceOptions: [],
      accept: '.pdf, .doc, .docx, .png, .jpg, .jpeg',

      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      viewOpen: false,
      filePreview: {},
      paramsData: {},
      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',
          },
        ],
        phone: [{ required: true, validator: numberUtils.checkPhone, trigger: 'blur' }],
        idCard: [{ required: true, validator: numberUtils.checkIdCardNumber, trigger: 'blur' }],
        postName: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        physicalExaminationFile: [{ required: true, message: '请上传体检文件', trigger: 'blur' }],
        insuranceFile: [{ required: true, message: '请上传保险文件', trigger: 'blur' }],
      },
    }
  },
  created() {
    const params = this.$route.params && this.$route.params.data
    this.paramsData = JSON.parse(decryptCBC(params))
    if (this.paramsData.type !== 'view') {
      this.showOrNot = true
      if (this.paramsData.type === 'edit') {
        this.getData()
      }
    } else {
      this.showOrNot = false
      // from表单里全部都不可编辑
      this.getData()
    }
    this.getDeviceType()
    this.approvalHistory()
    this.getStatus()
  },
  methods: {
    getStatus() {
      const params = {
        dictType: 'sys_sup_post',
        dictValue: '',
      }
      dictTableOption(params).then(response => {
        this.postList = response.data
      })
    },
    approvalHistory() {
      console.log('this.paramsData.taskId:' + this.paramsData.taskId)
      approvalHistory({ taskId: this.paramsData.taskId }).then(res => {
        this.approvalInfo = res.data
      })
    },
    delFile(e) {
      console.log(e)
      if (!this.delFileIds.includes(e)) {
        this.delFileIds.push(e)
      }
      console.log(this.delFileIds)
    },
    handleFileChange(form, name) {
      // 手动校验
      this.$refs[form].validateField(name)
    },
    left,
    // 岗位选择改变事件
    handlePostChange(label) {
      // 当岗位选择为特殊工种时，显示特殊工种种类输入框
      if (label === '1') {
        this.showSpecialWorkType = true
      } else {
        this.showSpecialWorkType = false
        // 清空特殊工种种类输入框的值
        this.form.workType = ''
      }
    },
    getData() {
      const params = {
        consUserId: this.paramsData.consUserId,
        uuid: this.paramsData.uuid,
        proId: '2',
        supId: '1',
        consId: '1',
      }
      getData(params).then(response => {
        console.log(response)
        this.form = response.data
        if (this.form.post === '1') {
          this.showSpecialWorkType = true
        }
        if (this.paramsData.type === 'view') {
          this.form.phone = hideSensitiveInfo(response.data.phone)
          this.form.idCard = hideSensitiveInfo(response.data.idCard)
        }
      })
    },
    //上传组件-图片查看
    picturePreview(file) {
      console.log(file)
      //判断文件类型图片显示
      if (file.fileType === 'image') {
        this.dialogImageUrl = file.fileUrl
        this.viewOpen = false
        this.dialogVisible = true
      } else {
        this.filePreview = file
        this.dialogVisible = false
        this.viewOpen = true
      }
    },

    //获取工程地址选项
    getDeviceType() {
      const params = {
        dictType: 'sys_cons_post',
        dictValue: '',
      }
      dictTableOption(params).then(response => {
        this.deviceOptions = response.data
      })
    },

    // 表单上传，先判断文件是否按要求上传了，满足要求的话，构造formData
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          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
                this.$router.go(-1)
              })
              .catch(error => {
                console.log('error', error)
                this.loading = false
                // 增加错误处理
                this.$modal.msgError('新增失败：' + error.message)
              })
          })
        }
      })
    },

    // 提取公共方法，获取fileList中具有raw属性的文件
    getFileData(fileList) {
      return Promise.all(fileList.filter(item => item?.hasOwnProperty('raw')).map(item => item.raw))
    },

    // 点击tab事件  切换tab
    handleClick(tab, event) {
      console.log(tab, event)
    },

    // 取消按钮
    cancel() {
      this.$tab.closePage()
    },
  },
}
</script>

<style lang="scss" scoped>
.el_upload_preview_list {
  height: 100%;
  // el-uplaod组件卡片预览类型预览pdf样式
  .pdfContainer {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
