<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 :label-position="labelPosition" :disabled="!showOrNot" ref="form" :model="form" :rules="rules"
                   label-width="80px"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="姓名：" prop="consName">
                  <el-input v-model="form.consName" placeholder="请输入姓名" v-no-whitespace maxlength="15" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="6">
                <el-form-item label="性别：" prop="sex">
                  <el-select v-model="form.sex" placeholder="请选择性别" 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>
              <el-col :span="6">
                <el-form-item label="年龄：" prop="age">
                  <el-input v-model="form.age" placeholder="请输入年龄" v-no-whitespace maxlength="2" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="6">
                <el-form-item label="联系方式：" prop="phone" label-width="150">
                  <el-input v-model="form.phone" placeholder="请输入联系方式" v-no-whitespace maxlength="11" :disabled="this.paramsData.type !== 'add'" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="籍贯：" prop="natives">
                  <el-input v-model="form.natives" placeholder="请输入籍贯" v-no-whitespace maxlength="30" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="6">
                <el-form-item label="民族：" prop="nation">
                  <el-input v-model="form.nation" placeholder="请输入民族" v-no-whitespace maxlength="30" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="身份证号码：" prop="idCard">
                  <el-input v-model="form.idCard" placeholder="请输入身份证号码" v-no-whitespace maxlength="18" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="6">
                <el-form-item label="家庭住址：" prop="homeAddress">
                  <el-input v-model="form.homeAddress" placeholder="请输入家庭住址" v-no-whitespace maxlength="30" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="现住址：" prop="address">
                  <el-input v-model="form.address" placeholder="请输入现住址" v-no-whitespace maxlength="30" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="6">
                <el-form-item label="岗位：" prop="post">
                  <el-select v-model="form.post" placeholder="请选择岗位" @change="handlePostChange"  style="width: 100%">
                    <el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6" v-if="showSpecialWorkType">
                <el-form-item label="特殊工种种类：" prop="workType">
                  <el-input v-model="form.workType" placeholder="请输入特殊工种种类" v-no-whitespace maxlength="30" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 文件格式下载，图片格式预览 -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="人脸照片" prop="facePhotoList">
                  <uploadFile :limit="1" :accept="`.png, .jpg, .jpeg`" :uploadList.sync="form.facePhotoList"
                              @picturePreview="picturePreview"
                  ></uploadFile>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体检文件" prop="medicalExaminationList">
                  <uploadFile :limit="5" :multiple=true :accept="accept" :uploadList.sync="form.medicalExaminationList"
                              @picturePreview="picturePreview"
                              :class="{disabled:this.paramsData.type === 'view'}"
                              v-on:delFile="delFile"
                              v-on:up="handleFileChange('form','medicalExaminationList')"
                  ></uploadFile>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="保险文件" prop="elseImgList">
                  <uploadFile :limit="5" :accept="accept" :uploadList.sync="form.elseImgList"
                              @picturePreview="picturePreview"
                              :class="{disabled:this.paramsData.type === 'view'}"
                              v-on:delFile="delFile"
                              v-on:up="handleFileChange('form','elseImgList')"
                  ></uploadFile>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="其它文件" prop="otherFilesList">
                  <img src="@/assets/file/no_data.png" alt="暂无数据" width="150" height="150" v-if="form.otherFilesList.length == 0 && this.paramsData.type === 'view'" style="">
                  <uploadFile :limit="5" :accept="accept" :uploadList.sync="form.otherFilesList"
                              v-else
                              @picturePreview="picturePreview"
                              :class="{disabled:this.paramsData.type === 'view'}"
                              v-on:delFile="delFile"
                              v-on:up="handleFileChange('form','otherFilesList')"
                  ></uploadFile>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="特殊工种文件" prop="specialTypeOfWorkList"  v-if="showSpecialWorkType">
                  <uploadFile :limit="5" :accept="accept" :uploadList.sync="form.specialTypeOfWorkList"
                              @picturePreview="picturePreview"
                              :class="{disabled:this.paramsData.type === 'view'}"
                              v-on:delFile="delFile"
                              v-on:up="handleFileChange('form','specialTypeOfWorkList')"
                  ></uploadFile>
                </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"
        ></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'

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: {
        facePhotoList: [],
        medicalExaminationList: [],
        elseImgList: [],
        specialTypeOfWorkList: [],
        otherFilesList: [],
        workType: undefined
      },
      //对齐方式
      labelPosition: 'top',
      // 岗位选项
      deviceOptions: [],
      accept: '.pdf, .doc, .docx, .png, .jpg, .jpeg',

      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      viewOpen: false,
      filePreview:{},
      paramsData: {},
      rules: {
        consName: [
          { 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' },
        ],
        natives: [
          { required: true, message: '请输入籍贯', trigger: 'blur' }
        ],
        nation: [
          { required: true, message: '请输入民族', trigger: 'blur' }
        ],
        idCard: [
          { required: true, validator: numberUtils.checkIdCardNumber, trigger: 'blur' },
        ],
        homeAddress: [
          { required: true, message: '请输入家庭住址', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入现住址', trigger: 'blur' }
        ],
        post: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ],
        workType: [
          { required: true, message: '请填写特殊工种', trigger: 'blur' }
        ],
        // facePhotoList: [
        //   { required: true, message: '请上传人脸照片', trigger: 'blur' }
        // ],
        medicalExaminationList: [
          { required: true, message: '请上传体检文件', trigger: 'blur' }
        ],
        elseImgList: [
          { required: true, message: '请上传保险文件', trigger: 'blur' }
        ],
        specialTypeOfWorkList: [
          { 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()
  },
  methods: {
    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) {
          this.form.proId = this.$store.state.user.thisIds.proId;
          this.form.subUuid = this.$store.state.user.thisIds.subUuid;
          this.form.contUuid = this.$store.state.user.thisIds.consUuid;
          this.form.userType = this.$store.state.user.userType;
          this.form.delFileIds = this.delFileIds.join(",");
          if (this.paramsData.type === 'edit'){
            this.form.uuid = this.paramsData.uuid
          }
          console.log(this.form)
          const reqData = new FormData()
          reqData.append('params', JSON.stringify(this.form))

          // 使用 Promise.all 并行处理文件数据获取，提高效率
          Promise.all([
            this.getFileData(this.form.facePhotoList),
            this.getFileData(this.form.medicalExaminationList),
            this.getFileData(this.form.elseImgList),
            this.getFileData(this.form.specialTypeOfWorkList),
            this.getFileData(this.form.otherFilesList)
          ]).then(([facePhotoList, medicalExaminationList, elseImgList, specialTypeOfWorkList, otherFilesList]) => {
            if (!facePhotoList || facePhotoList.length === 0) {
              reqData.append('facePhotoList', new Blob())
            } else {
              facePhotoList.forEach(item => reqData.append('facePhotoList', item))
            }
            if (!medicalExaminationList || medicalExaminationList.length === 0) {
              reqData.append('medicalExaminationList', new Blob())
            } else {
              medicalExaminationList.forEach(item => reqData.append('medicalExaminationList', item))
            }
            if (!elseImgList || elseImgList.length === 0) {
              reqData.append('elseImgList', new Blob())
            } else {
              elseImgList.forEach(item => reqData.append('elseImgList', item))
            }
            if (!specialTypeOfWorkList || specialTypeOfWorkList.length === 0) {
              reqData.append('specialTypeOfWorkList', new Blob())
            } else {
              specialTypeOfWorkList.forEach(item => reqData.append('specialTypeOfWorkList', item))
            }
            if (!otherFilesList || otherFilesList.length === 0) {
              reqData.append('otherFilesList', new Blob())
            } else {
              otherFilesList.forEach(item => reqData.append('otherFilesList', item))
            }
            addAdmissionRequest(reqData).then(response => {
             if (this.paramsData.type === 'edit') {
               this.$modal.msgSuccess('修改成功')
             }else{
               this.$modal.msgSuccess('新增成功')
             }
              this.$tab.closePage()
              this.fileList = []
            })
          })
        }
      })
    },

    // 提取公共方法，获取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>
