<!-- 计量人员新增 -->
<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 certificateAddDialog from './certificateAddDialog.vue'
import personListDialog from './personListDialog.vue'
import { getUserList } from '@/api/system/user'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { userType } from '@/views/system/user/user-interface'
import { getDictByCode } from '@/api/system/dict'
import comTreeSelect from '@/views/system/user/selecTree.vue'
import { addCertificateList, getCertificateDetail, getCertificateUpdate } from '@/api/measure/person'
const emits = defineEmits(['resetData'])
const ruleFormRef = ref<FormInstance>() // from组件
const meterStaff = ref({
  staffNo: '', // 人员编号
  name: '', // 姓名
  idCard: '', // 身份证号
  sex: '', // 性别
  education: '', // 文化程度
  technologyJob: '', // 技术职务
  administrationJob: '', // 行政职务
  deptId: '', // 工作部门
  major: '', // 专业
  workDate: '', // 从事日期
  id: '',
})
const ruleForm = ref({
  meterStaff: {}, // 人员信息
  staffId: '', // 计量人员id
}) // 表单
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const title = 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 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([])
// 获取组织列表
const getPubList = () => {
  getDeptTreeList().then((res) => {
    // 转成树结构
    PubList.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 = ''
}
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
  ruleFormRef.value?.clearValidate('staffNo')
}
const changeList = ref([
  {
    name: '证书基本信息',
    data: [] as any[],
    column: [
      {
        label: '证书号',
        data: 'certificateNo',
        id: 'zs02',
      },
      {
        label: '证书名称',
        data: 'certificateName',
        id: 'zs03',
      },
      {
        label: '发证日期',
        data: 'certificateDate',
        id: 'zs04',
      },
      {
        label: '发证单位',
        data: 'certificateCompany',
        id: 'zs01',
      },
      {
        label: '有效日期',
        data: 'validDate',
        id: 'zs05',
      },
    ],
  },
  {
    name: '计量工作培训记录',
    data: [],
    column: [],
  },
  {
    name: '业务记录',
    data: [],
    column: [],
  },
])
const current = ref('证书基本信息')
const currentShow = computed(() => {
  return changeList.value.filter(item => item.name === current.value)[0]
})
const certificateRef = ref() // 添加证书信息弹窗
// 添加行
const addRow = () => {
  certificateRef.value.initDialog({ title: '添加' })
}
// 编辑行
const editRow = () => {
  certificateRef.value.initDialog({ ...changeList.value[0].data[0], title: '编辑' })
}
// 证书信息行内添加数据
const addRowcertificate = (row: any, flag: string) => {
  const diff = dayjs(row.validDate).diff(row.certificateDate, 'day')
  if (flag === 'update') {
    changeList.value[0].data = [{
      ...changeList.value[0].data[0],
      ...row,
      certificateStatus: diff < 0 ? '1' : '0',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }]
  }
  else {
    changeList.value[0].data.push(
      {
        ...row,
        certificateStatus: diff < 0 ? '1' : '0',
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        id: null,
        isDel: 0,
        minioFileName: '',
        remark: '',
        staffId: meterStaff.value.id,
        updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
  }
}
const currenSelect = ref<number>(-1) // 当前选中行
// 删除行
const removeRow = () => {
  console.log(currenSelect.value)
  if (currenSelect.value >= 0) {
    ElMessageBox.confirm(
      '确认删除选中的数据吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      changeList.value[0].data = changeList.value[0].data.filter((item, index) => index !== currenSelect.value)
      currenSelect.value = -1
      ElMessage.success('删除成功')
    })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认提交吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        let params
        if (changeList.value[0].data.length) {
          params = changeList.value[0].data
        }
        else {
          params = [
            {
              certificateCompany: '',
              certificateDate: '',
              certificateName: '',
              certificateNo: '',
              certificateStatus: '',
              createTime: '',
              id: null,
              isDel: 0,
              minioFileName: '',
              remark: '',
              staffId: meterStaff.value.id,
              updateTime: '',
              validDate: '',
            },
          ]
        }
        (title.value === '新建'
          ? addCertificateList
          : getCertificateUpdate)(title.value === '新建' ? params : changeList.value[0].data[0]).then((res) => {
          formEl?.resetFields()
          ElMessage.success('提交成功')
          emits('resetData')
          resetFormData()
        })
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  changeList.value[0].data = []
  emits('resetData')
  resetFormData()
}
// 弹窗初始化
const initDialog = (row: any) => {
  changeList.value[0].data = []
  resetFormData()
  dialogVisible.value = true
  title.value = row.title
  resetFormData()
  getuser()
  getPubList()
  getSexList()
  geteducationList()
  getTechnologyJobList()
  getAdministrationJob()
  if (row.title === '新建') {
    console.log()
  }
  else {
    getCertificateDetail({ id: row.id }).then((res) => {
      if (res.code === 200) {
        meterStaff.value = res.data.meterStaff
        changeList.value[0].data = [{ ...res.data, meterStaff: undefined }]
      }
    })
  }
}
defineExpose({ initDialog })
</script>

<template>
  <app-container style="overflow: hidden;">
    <div class="body-container">
      <div class="header">
        <div class="title">
          证书记录-{{ title }}
        </div>
        <span class="btns">
          <el-button v-if="title !== '详情'" type="primary" @click="submitForm(ruleFormRef)">
            完成
          </el-button>
          <el-button type="info" @click="resetForm(ruleFormRef)">
            关闭
          </el-button>
        </span>
      </div>
      <el-form ref="ruleFormRef" :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" />
            </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 === '详情'">
                <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 === '详情'">
                <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 === '详情'">
                <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 === '详情'">
                <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">
              <el-input v-if="title === '详情'" v-model.trim="meterStaff.deptId" placeholder="" :disabled="title === '详情'" />
              <com-tree-select
                v-else
                v-model="meterStaff.deptId" :options="PubList" placeholder="选择组织机构"
                :tree-props="deptProps"
              />
            </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="请选择从事日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="header" style="margin-top: 10px;">
        <div class="title">
          {{ current }}
        </div>
        <span class="btns">
          <el-button v-if="title === '新建'" type="info" @click="removeRow">
            删除行
          </el-button>
          <el-button v-if="title === '新建'" type="primary" @click="addRow">
            添加行
          </el-button>
          <el-button v-if="title === '编辑'" type="primary" @click="editRow">
            编辑行
          </el-button>
        </span>
      </div>
      <el-table ref="multipleTableRef" :data="currentShow.data" style="width: 100%;margin-top: 10px;">
        <el-table-column width="55" align="center">
          <template #default="scope">
            <el-radio-group v-model="currenSelect" class="ml-4">
              <el-radio :label="scope.$index" />
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column v-for="item in currentShow.column" :key="item.id" :prop="item.data" :label="item.label" align="center" />
      </el-table>
    </div>
    <!-- 添加证书信息组件 -->
    <certificate-add-dialog ref="certificateRef" @add="addRowcertificate" />
    <!-- 选择用户列表组件 -->
    <person-list-dialog ref="personListRef" @add="confirmPerson" />
  </app-container>
</template>

<style lang="scss" scoped>
.body-container {
  .form {
    background-color: #fff;
    border-radius: 8px;
    padding-top: 10px;
    margin-top: 10px;
  }

  .header {
    background-color: #fff;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    position: relative;

    .title {
      font-weight: 700;
    }

    .btns {
      position: absolute;
      right: 40px;
      top: 5px;
    }
  }

  :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;
      }
    }
  }
}

.marg {
  margin-top: 20px;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
