<!-- 人员登记 检定员信息 -->
<script name="RegisterVerifier" lang="ts" setup>
import { ElMessage, dayjs } from 'element-plus'
import type { IStaffVerifierInfo } from '../person-regitster'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { addVerifierRecList, delVerifierRecList, getVerifierList } from '@/api/resource/register'

const props = defineProps({
  operation: { type: String, default: '' },
  staffId: { type: String, default: '' },
})

const listQuery = {
  id: '',
  limit: 1000,
  offset: 1,
}

const verifierColumns = [
  { text: '证书号', value: 'certNo', align: 'center', width: '160', required: true },
  { text: '证书名称', value: 'certName', align: 'center', required: true },
  { text: '发放日期', value: 'grantDate', align: 'center', width: '160', required: true },
  { text: '有效日期', value: 'effectiveDate', align: 'center', width: '160', required: true },
  { text: '发放单位', value: 'grantCompany', align: 'center', required: true },
  { text: '附件', value: 'file', align: 'center' },
] // 表头

const verifierList = ref<IStaffVerifierInfo[]>([]) // 表格数据

// 表格被选中的行
const verifierSelected = ref<IStaffVerifierInfo[]>([])

const verifierRecord: IStaffVerifierInfo = {
  id: '',
  staffId: '',
  certNo: '',
  certName: '',
  grantDate: '',
  effectiveDate: '',
  grantCompany: '',
  file: '',
  editable: true,
}

// 逻辑
const addEditableRow = (tableName: string) => {
  switch (tableName) {
    case 'verifier':
      verifierList.value = verifierList.value.map((item: any) => ({
        ...item,
        grantDate: dayjs(item.grantDate).format('YYYY-MM-DD'),
        effectiveDate: dayjs(item.effectiveDate).format('YYYY-MM-DD'),
      }))
      if (useCheckList(verifierList.value, verifierColumns, '检定员信息')) {
        useSetAllRowReadable(verifierList.value)
        verifierList.value.push({ ...verifierRecord })
      }
      break

    default:
      break
  }
}

const verMultiSelect = (e: any) => {
  verifierSelected.value = e
}

const getVerifierListByStaffId = () => {
  getVerifierList(listQuery).then((res) => {
    if (res.code === 200) {
      verifierList.value = res.data.rows.map((item: any) => ({
        ...item,
        grantDate: dayjs(item.grantDate).format('YYYY-MM-DD'),
        effectiveDate: dayjs(item.effectiveDate).format('YYYY-MM-DD'),
      }))
    }
  })
}

// 增加检定员信息记录
const addVerifierRecords = () => {
  if (useCheckList(verifierList.value, verifierColumns, '检定员信息') === false) {
    return
  }

  const newRecords = ref<Array<IStaffVerifierInfo>>([])
  newRecords.value = verifierList.value.filter(item => item.id === '')

  if (newRecords.value.length > 0) {
    addVerifierRecList(newRecords.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('添加检定员信息记录成功')
        getVerifierListByStaffId()
      }
      else {
        ElMessage.error(`添加检定员信息记录失败：${res.message}`)
      }
    })
  }
}

// 删除检定员信息记录
const delVerifierRecords = () => {
  if (verifierSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

  // 前端界面删除
  verifierList.value = verifierList.value.filter(item => verifierSelected.value.includes(item) === false)

  // 调用后端接口进行删除
  const verIdsSelected = ref<string[]>([])
  verIdsSelected.value = verifierSelected.value.map((item: { id: string }) => item.id)
  verIdsSelected.value = verIdsSelected.value.filter(item => item !== '')
  if (verIdsSelected.value.length > 0) {
    delVerifierRecList({ ids: verIdsSelected.value }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('删除检定员信息记录成功')
      }
      else {
        ElMessage.error(`删除检定员信息记录失败：${res.message}`)
      }

      getVerifierListByStaffId()
    })
  }
}

watch(() => props.staffId, (newVal: string) => {
  listQuery.id = newVal
  verifierRecord.staffId = newVal

  getVerifierListByStaffId()
})

defineExpose({
  addVerifierRecords,
})
</script>

<template>
  <app-container>
    <el-form ref="verifierFormRef" label-position="right" label-width="110px" border stripe>
      <table-container title="检定员信息">
        <template v-if="props.operation !== 'detail'" #btns-right>
          <el-button type="primary" @click="addEditableRow('verifier')">
            增加行
          </el-button>
          <el-button type="info" @click="delVerifierRecords">
            删除行
          </el-button>
        </template>

        <!-- 表格区域 -->
        <el-table :data="verifierList" border style="width: 100%;" @selection-change="verMultiSelect">
          <el-table-column v-if="props.operation !== 'detail'" type="selection" align="center" width="38" />
          <el-table-column align="center" label="序号" width="55" type="index" />
          <el-table-column
            v-for="item in verifierColumns"
            :key="item.value"
            :prop="item.value"
            :label="item.text"
            :width="item.width"
            align="center"
          >
            <template #header>
              <span v-show="item.required && props.operation !== 'detail'" style="color: red;">*</span><span>{{ item.text }}</span>
            </template>
            <template #default="scope">
              <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
              <el-date-picker v-else-if="item.value === 'grantDate'" v-model="scope.row.grantDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" type="date" style="width: 100%;" />
              <el-date-picker v-else-if="item.value === 'effectiveDate'" v-model="scope.row.effectiveDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" type="date" style="width: 100%;" />
              <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
            </template>
          </el-table-column>
        </el-table>
      </table-container>
    </el-form>
  </app-container>
</template>
