<!-- 计量人员新增 -->
<script lang="ts" setup name="addNotice">
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import type { technologyJobType } from '../person-interface'
import personListDialog from './personListDialog.vue'
import { getUserList } from '@/api/system/user'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { TreeStructure, userType } from '@/views/system/user/user-interface'
import { getDictByCode } from '@/api/system/dict'
import { addCertificateList, getCertificateDetail, getCertificateUpdate } from '@/api/measure/person'
const ruleFormRef1 = ref<FormInstance>() // from组件
const ruleFormRef2 = ref<FormInstance>() // from组件
const $route = useRoute()
const $router = useRouter()
const meterStaff = ref({
  staffNo: '', // 人员编号
  name: '', // 姓名
  idCard: '', // 身份证号
  sex: '', // 性别
  education: '', // 文化程度
  technologyJob: '', // 技术职务
  administrationJob: '', // 行政职务
  deptId: '', // 工作部门
  major: '', // 专业
  workDate: '', // 从事日期
  id: '',
})
const baseInfo = ref({
  certificateCompany: '',
  certificateDate: '',
  certificateName: '',
  certificateNo: '',
  validDate: '',
  id: '',
  isDel: 0,
  minioFileName: '',
  remark: '',
})
const ruleForm = ref({
  meterStaff: {}, // 人员信息
  staffId: '', // 计量人员id
}) // 表单
const title = ref('')
const name = ref('')
// 身份证号码验证规则
// const validateIDcard = (rule: any, value: any, callback: any) => {
//   const rr = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[X])$)$/
//   if (rr.test(value)) {
//     callback()
//   }
//   else {
//     callback(new Error('验证失败'))
//   }
// }
const rules = ref({
  staffNo: [{ required: true, message: '人员编号不能为空', trigger: 'blur' }],
  // idCard: [{ required: false, validator: validateIDcard, message: '身份证号码不符合规范', trigger: 'change' }],
}) // 表单验证规则
const rules2 = ref({
  certificateCompany: [{ required: true, message: '发证单位不能为空', trigger: 'blur' }],
  certificateDate: [{ required: true, message: '发证日期不能为空', trigger: 'blur' }],
  certificateName: [{ required: true, message: '证书名称不能为空', trigger: 'blur' }],
  certificateNo: [{ required: true, message: '证书编号不能为空', trigger: 'blur' }],
  validDate: [{ required: true, message: '有效日期不能为空', trigger: 'blur' }],
}) // 表单验证规则
const dialogVisible = ref<boolean>(false) // 弹窗显示
const userList = ref<userType[]>([]) // 可使用人列表
const getuser = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
} // 获取创建人列表
const deptProps = reactive({
  parent: 'pid', value: 'id', label: 'name', children: 'children',
})
const PubList = ref<TreeStructure[]>([])
const PubListTree = ref([])
// 获取组织列表
const getPubList = () => {
  getDeptTreeList().then((res) => {
    // 转成树结构
    PubList.value = res.data
    PubListTree.value = toTreeList(res.data, '0', true)
  })
}
const sexList = ref<{ id: string; value: string; name: string }[]>()
// 获取性别
const getSexList = () => {
  getDictByCode('sex').then((response) => {
    sexList.value = response.data
  })
}
const educationList = ref<technologyJobType[]>([])
// 获取文化程度列表
const geteducationList = () => {
  getDictByCode('education').then((response) => {
    educationList.value = response.data
  })
}
// 重置表单内容
const resetFormData = () => {
  meterStaff.value.staffNo = ''
  meterStaff.value.name = ''
  meterStaff.value.idCard = ''
  meterStaff.value.sex = ''
  meterStaff.value.education = ''
  meterStaff.value.technologyJob = ''
  meterStaff.value.administrationJob = ''
  meterStaff.value.deptId = ''
  meterStaff.value.major = ''
  meterStaff.value.workDate = ''
  meterStaff.value.id = ''
  baseInfo.value = {
    certificateCompany: '',
    certificateDate: '',
    certificateName: '',
    certificateNo: '',
    validDate: '',
    id: '',
    isDel: 0,
    minioFileName: '',
    remark: '',
  }
}
const technologyJobList = ref<technologyJobType[]>([])
// 获取技术职务列表
const getTechnologyJobList = () => {
  getDictByCode('technologyJob').then((response) => {
    technologyJobList.value = response.data
  })
}
const administrationJobList = ref<technologyJobType[]>([])
// 获取行政职务列表
const getAdministrationJob = () => {
  getDictByCode('administrationJob').then((response) => {
    administrationJobList.value = response.data
  })
}
const personListRef = ref()
// 选择人员
const selectPerson = () => {
  personListRef.value.initDialog()
}
// 保存选择人员信息
const confirmPerson = (row: any) => {
  ruleForm.value.staffId = row.staffNo
  meterStaff.value = row
  ruleFormRef1.value?.clearValidate('staffNo')
}
// 提交
const submitForm = async (formEl1: FormInstance | undefined, formEl2: FormInstance | undefined) => {
  if (!formEl1 || !formEl2) { return }
  Promise.all([formEl1.validate(), formEl2.validate()]).then((res) => {
    ElMessageBox.confirm(
      '确认提交吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      (title.value === '新建'
        ? addCertificateList
        : getCertificateUpdate)(title.value === '新建'
        ? [{
            ...baseInfo.value,
            staffId: meterStaff.value.id,
            createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            certificateStatus: dayjs(baseInfo.value.validDate).diff(baseInfo.value.certificateDate, 'day') < 0 ? '1' : '0',
            meterStaff: undefined,
          }]
        : {
            ...baseInfo.value,
            staffId: meterStaff.value.id,
            createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            certificateStatus: dayjs(baseInfo.value.validDate).diff(baseInfo.value.certificateDate, 'day') < 0 ? '1' : '0',
            meterStaff: undefined,
          }).then((res) => {
        formEl1?.resetFields()
        formEl2?.resetFields()
        ElMessage.success('提交成功')
        $router.go(-1)
        resetFormData()
      })
    })
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined, formEl2: FormInstance | undefined) => {
  formEl?.resetFields()
  formEl2?.resetFields()
  $router.go(-1)
  resetFormData()
}
// 弹窗初始化
const initDialog = (row: any) => {
  resetFormData()
  dialogVisible.value = true
  title.value = row.title
  name.value = row.name
  getuser()
  getPubList()
  getSexList()
  geteducationList()
  getTechnologyJobList()
  getAdministrationJob()
  if (row.title === '新建') {
    console.log()
  }
  else {
    getCertificateDetail({ id: row.id }).then((res) => {
      if (res.code === 200) {
        console.log(res, '证书记录')
        meterStaff.value = res.data.meterStaff
        baseInfo.value = res.data
      }
    })
  }
}
onMounted(() => {
  initDialog($route.query)
})
</script>

<template>
  <app-container style="overflow: hidden;">
    <detail-page :title=" `${name}-${title}`">
      <template #btns>
        <el-button v-if="title !== '详情'" type="primary" @click="submitForm(ruleFormRef1, ruleFormRef2)">
          完成
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef1, ruleFormRef2)">
          关闭
        </el-button>
      </template>
      <el-form ref="ruleFormRef1" :model="meterStaff" :rules="rules" label-position="right" label-width="110px" class="form" :class="[title === '详情' ? 'isDetail' : '']" border stripe>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="人员编号" prop="staffNo">
              <el-input v-model.trim="meterStaff.staffNo" placeholder="人员编号" :disabled="title === '详情'" @focus="selectPerson">
                <template #append>
                  <el-button size="small" :disabled="title === '详情'" @click="selectPerson">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名" prop="meterStaff.name">
              <el-input v-model.trim="meterStaff.name" placeholder="姓名" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号" prop="idCard">
              <el-input ref="cardRef" v-model.trim="meterStaff.idCard" placeholder="身份证号" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="meterStaff.sex">
              <el-select v-model="meterStaff.sex" placeholder="请选择性别" :disabled="title === '详情'" style="width: 100%;">
                <el-option v-for="item in sexList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="文化程度" prop="meterStaff.education">
              <el-select v-model="meterStaff.education" placeholder="文化程度" :disabled="title === '详情'" style="width: 100%;">
                <el-option v-for="item in educationList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="技术职务" prop="meterStaff.technologyJob">
              <el-select v-model="meterStaff.technologyJob" placeholder="技术职务" :disabled="title === '详情'" style="width: 100%;">
                <el-option v-for="item in technologyJobList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="行政职务" prop="meterStaff.administrationJob">
              <el-select v-model="meterStaff.administrationJob" placeholder="行政职务" :disabled="title === '详情'" style="width: 100%;">
                <el-option v-for="item in administrationJobList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="工作部门" prop="deptId">
              <dept-select v-model="meterStaff.deptId" :data="PubListTree" :placeholder="title === '详情' ? ' ' : '选择组织机构'" :disabled="title === '详情'" style="width: 100%;" />
              <!-- <el-select v-if="title === '详情'" v-model="meterStaff.deptId" disabled style="width: 100%;">
                <el-option v-for="item in PubList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <com-tree-select
                v-else
                ref="selectTreeRef" v-model="meterStaff.deptId" :options="PubListTree"
                placeholder="选择组织机构"
                :tree-props="deptProps"
                style="width: 100%;"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量专业" prop="major">
              <el-input v-model.trim="meterStaff.major" placeholder="计量专业" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="从事日期" prop="workDate">
              <el-date-picker
                v-model="meterStaff.workDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" :disabled="title === '详情'"
                placeholder="请选择从事日期" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="证书基本信息">
      <el-form ref="ruleFormRef2" :model="baseInfo" :rules="rules2" label-position="right" label-width="110px" class="form" :class="[title === '详情' ? 'isDetail' : '']" border stripe>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="证书号" prop="certificateNo">
              <el-input v-model.trim="baseInfo.certificateNo" placeholder="计量专业" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书名称" prop="certificateName">
              <el-input v-model.trim="baseInfo.certificateName" placeholder="计量专业" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发证单位" prop="certificateCompany">
              <el-input v-model.trim="baseInfo.certificateCompany" placeholder="计量专业" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="发证日期" prop="certificateDate">
              <el-date-picker
                v-model="baseInfo.certificateDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" :disabled="title === '详情'"
                placeholder="请选择发证日期" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书有效日期" prop="validDate">
              <el-date-picker
                v-model="baseInfo.validDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" :disabled="title === '详情'"
                placeholder="请选择有效日期" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block>
    <!-- 选择用户列表组件 -->
    <person-list-dialog ref="personListRef" @add="confirmPerson" />
  </app-container>
</template>

<style lang="scss" scoped>
  :deep(.el-radio__label) {
    display: none;
  }

  .isDetail {
    ::v-deep {
      .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
      .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
        display: none;
      }
    }
  }
</style>

