<!-- 人员登记 基本信息 -->
<script name="RegisterEducation" lang="ts" setup>
import { ElMessage, dayjs } from 'element-plus'
import type { IDictType, IStaffAbilityInfo, IStaffEducationInfo, IStaffProjectInfo } from '../person-regitster'
import { getDictTextByValue, jointDate } from '../common-register'
import { addAbilityRecList, addEducationRecList, addProjectRecList, delAbilityRecList, delEducationRecList, delProjectRecList, getAbilityList, getEducationList, getProjectList } from '@/api/resource/register'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'

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

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

const educationDictInChild = ref<Array<IDictType>>([])

const educationColumns = [
  { text: '毕业院校', value: 'graduateSchool', align: 'center', required: true },
  { text: '专业', value: 'speciality', align: 'center', required: true },
  { text: '学历', value: 'educationName', align: 'center', required: true },
  { text: '时间', value: 'timeSpan', align: 'center', required: true },
] // 表头

const abilityColumns = [
  { text: '时间', value: 'obtainDate', align: 'center', width: '160', required: true },
  { text: '名称', value: 'abilityName', align: 'center', width: '240', required: true },
  { text: '发表刊物（期号）/会议名称（获奖情况）', value: 'publication', align: 'center', width: '480', required: true },
  { text: '备注', value: 'remark', align: 'center' },
  { text: '附件', value: 'file', align: 'center' },
] // 表头

const projectColumns = [
  { text: '时间', value: 'projectDate', align: 'center', width: '160', required: true },
  { text: '名称', value: 'projectName', align: 'center', required: true },
  { text: '备注', value: 'remark', align: 'center' },
  { text: '附件', value: 'file', align: 'center' },
] // 表头

const educationList = ref<IStaffEducationInfo[]>([]) // 表格数据
const abilityList = ref<IStaffAbilityInfo[]>([])
const projectList = ref<IStaffProjectInfo[]>([])

// 表格被选中的行
const educationSelected = ref<IStaffEducationInfo[]>([])
const abilitySelected = ref<IStaffAbilityInfo[]>([])
const projectSelected = ref<IStaffProjectInfo[]>([])

const educationRecord: IStaffEducationInfo = {
  id: '',
  staffId: '',
  graduateSchool: '',
  speciality: '',
  education: '',
  startDate: '',
  endDate: '',
  editable: true,
}

const abilityRecord: IStaffAbilityInfo = {
  id: '',
  staffId: '',
  obtainDate: '',
  abilityName: '',
  publication: '',
  remark: '',
  file: '',
  editable: true,
}

const projectRecord: IStaffProjectInfo = {
  id: '',
  staffId: '',
  projectDate: '',
  projectName: '',
  remark: '',
  file: '',
  editable: true,
}

// 逻辑
const addEditableRow = (tableName: string) => {
  switch (tableName) {
    case 'education':
      educationList.value = educationList.value.map((item: any) => ({
        ...item,
        educationName: getDictTextByValue(educationDictInChild.value, item.education),
        timeSpan: jointDate(item.startDatem, item.endDate),
      }))
      if (useCheckList(educationList.value, educationColumns, '教育档案')) {
        useSetAllRowReadable(educationList.value)
        educationList.value.push({ ...educationRecord })
      }
      break

    case 'ability':
      abilityList.value = abilityList.value.map((item: any) => ({
        ...item,
        obtainDate: dayjs(item.obtainDate).format('YYYY-MM-DD'),
      }))
      if (useCheckList(abilityList.value, abilityColumns, '业务能力')) {
        useSetAllRowReadable(abilityList.value)
        abilityList.value.push({ ...abilityRecord })
      }
      break

    case 'project':
      projectList.value = projectList.value.map((item: any) => ({
        ...item,
        projectDate: dayjs(item.projectDate).format('YYYY-MM-DD'),
      }))
      if (useCheckList(projectList.value, projectColumns, '科研项目')) {
        useSetAllRowReadable(projectList.value)
        projectList.value.push({ ...projectRecord })
      }
      break

    default:
      break
  }
}

// 表格多选
const eduMultiSelect = (e: any) => {
  educationSelected.value = e
}
const abiMultiSelect = (e: any) => {
  abilitySelected.value = e
}
const proMultiSelect = (e: any) => {
  projectSelected.value = e
}

const getEducationListByStaffId = () => {
  getEducationList(listQuery).then((res) => {
    if (res.code === 200) {
      educationDictInChild.value = JSON.parse(sessionStorage.getItem('educationDict')!)
      educationList.value = res.data.rows.map((item: any) => ({
        ...item,
        educationName: getDictTextByValue(educationDictInChild.value, item.education),
        timeSpan: jointDate(item.startDatem, item.endDate),
      }))
    }
  })
}

const getAbilityListByStaffId = () => {
  getAbilityList(listQuery).then((res) => {
    if (res.code === 200) {
      abilityList.value = res.data.rows.map((item: any) => ({
        ...item,
        obtainDate: dayjs(item.obtainDate).format('YYYY-MM-DD'),
      }))
    }
  })
}

const getProjectListByStaffId = () => {
  getProjectList(listQuery).then((res) => {
    if (res.code === 200) {
      projectList.value = res.data.rows.map((item: any) => ({
        ...item,
        projectDate: dayjs(item.projectDate).format('YYYY-MM-DD'),
      }))
    }
  })
}

// 增加教育档案记录
const addEducationRecords = () => {
  educationList.value = educationList.value.map((item: any) => ({
    ...item,
    educationName: getDictTextByValue(educationDictInChild.value, item.education),
    timeSpan: jointDate(item.startDatem, item.endDate),
  }))
  if (useCheckList(educationList.value, educationColumns, '教育档案') === false) {
    return
  }

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

  if (newRecords.value.length > 0) {
    addEducationRecList(newRecords.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('添加教育档案记录成功')
        getEducationListByStaffId()
      }
      else {
        ElMessage.error(`添加教育档案记录失败：${res.message}`)
      }
    })
  }
}

// 删除教育档案记录
const delEducationRecords = () => {
  if (educationSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

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

  // 调用后端接口进行删除
  const eduIdsSelected = ref<string[]>([])
  eduIdsSelected.value = educationSelected.value.map((item: { id: string }) => item.id)
  eduIdsSelected.value = eduIdsSelected.value.filter(item => item !== '')
  if (eduIdsSelected.value.length > 0) {
    delEducationRecList({ ids: eduIdsSelected.value }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('删除教育档案记录成功')
      }
      else {
        ElMessage.error(`删除教育档案记录失败：${res.message}`)
      }

      getEducationListByStaffId()
    })
  }
}

// 增加业务能力记录
const addAbilityRecords = () => {
  if (useCheckList(abilityList.value, abilityColumns, '业务能力') === false) {
    return
  }

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

  if (newRecords.value.length > 0) {
    addAbilityRecList(newRecords.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('添加业务能力记录成功')
        getAbilityListByStaffId()
      }
      else {
        ElMessage.error(`添加业务能力记录失败：${res.message}`)
      }
    })
  }
}

// 删除业务能力记录
const delAbilityRecords = () => {
  if (abilitySelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

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

  // 调用后端接口进行删除
  const abiIdsSelected = ref<string[]>([])
  abiIdsSelected.value = abilitySelected.value.map((item: { id: string }) => item.id)
  abiIdsSelected.value = abiIdsSelected.value.filter(item => item !== '')
  if (abiIdsSelected.value.length > 0) {
    delAbilityRecList({ ids: abiIdsSelected.value }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('删除业务能力记录成功')
      }
      else {
        ElMessage.error(`删除业务能力记录失败：${res.message}`)
      }

      getAbilityListByStaffId()
    })
  }
}

// 增加科研项目记录
const addProjectRecords = () => {
  if (useCheckList(projectList.value, projectColumns, '科研项目') === false) {
    return
  }

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

  if (newRecords.value.length > 0) {
    addProjectRecList(newRecords.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('添加科研项目记录成功')
        getProjectListByStaffId()
      }
      else {
        ElMessage.error(`添加科研项目记录失败：${res.message}`)
      }
    })
  }
}

// 删除科研项目记录
const delProjectRecords = () => {
  if (projectSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

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

  // 调用后端接口进行删除
  const proIdsSelected = ref<string[]>([])
  proIdsSelected.value = projectSelected.value.map((item: { id: string }) => item.id)
  proIdsSelected.value = proIdsSelected.value.filter(item => item !== '')
  if (proIdsSelected.value.length > 0) {
    delProjectRecList({ ids: proIdsSelected.value }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('删除科研项目记录成功')
      }
      else {
        ElMessage.error(`删除科研项目记录失败：${res.message}`)
      }

      getProjectListByStaffId()
    })
  }
}

watch(() => props.staffId, (newVal: string) => {
  listQuery.id = newVal
  educationRecord.staffId = newVal
  abilityRecord.staffId = newVal
  projectRecord.staffId = newVal

  getEducationListByStaffId()
  getAbilityListByStaffId()
  getProjectListByStaffId()
})

defineExpose({
  addEducationRecords,
  addAbilityRecords,
  addProjectRecords,
})
</script>

<template>
  <app-container>
    <el-form ref="educationFormRef" 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('education')">
            增加行
          </el-button>
          <el-button type="info" @click="delEducationRecords">
            删除行
          </el-button>
        </template>

        <!-- 表格区域 -->
        <el-table :data="educationList" border style="width: 100%;" @selection-change="eduMultiSelect">
          <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 educationColumns"
            :key="item.value"
            :prop="item.value"
            :label="item.text"
            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-select v-else-if="item.value === 'educationName'" v-model="scope.row.education" style="width: 100%;" placeholder="请选择学历">
                <el-option v-for="dict in educationDictInChild" :key="dict.value" :label="dict.name" :value="dict.value" />
              </el-select>
              <template v-else-if="item.value === 'timeSpan'">
                <el-date-picker v-model="scope.row.startDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" type="date" style="width: 45%;display: inline-block;" /> 至
                <el-date-picker v-model="scope.row.endDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" type="date" style="width: 45%;display: inline-block;" />
              </template>
              <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>

      <table-container title="业务能力">
        <template v-if="props.operation !== 'detail'" #btns-right>
          <el-button type="primary" @click="addEditableRow('ability')">
            增加行
          </el-button>
          <el-button type="info" @click="delAbilityRecords">
            删除行
          </el-button>
        </template>

        <!-- 表格区域 -->
        <el-table :data="abilityList" border style="width: 100%;" @selection-change="abiMultiSelect">
          <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 abilityColumns"
            :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 === 'obtainDate'" v-model="scope.row.obtainDate" 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>

      <table-container title="科研项目">
        <template v-if="props.operation !== 'detail'" #btns-right>
          <el-button type="primary" @click="addEditableRow('project')">
            增加行
          </el-button>
          <el-button type="info" @click="delProjectRecords">
            删除行
          </el-button>
        </template>

        <!-- 表格区域 -->
        <el-table :data="projectList" border style="width: 100%;" @selection-change="proMultiSelect">
          <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 projectColumns"
            :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 === 'projectDate'" v-model="scope.row.projectDate" 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>
