<!-- 人员登记 基本信息 -->
<script name="RegisterEducation" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IStaffAbilityInfo, IStaffEducationInfo, IStaffProjectInfo } from '../person-regitster'
import { getDictTextByValue, jointDate } from '../common-register'
import ProjectDialog from './projectDialog.vue'
import AbilityDialog from './abilityDialog.vue'
import EducationDialog from './educationDialog.vue'
import type { IDictType } from '@/commonInterface/resource-interface'
import { delAbilityRecList, delEducationRecList, delProjectRecList, getAbilityList, getEducationList, getProjectList } from '@/api/resource/register'
import type { TableColumn } from '@/components/NormalTable/table_interface'

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

/** ******* 教育档案表格 ********/
const eduListQuery = {
  id: '',
  limit: 10,
  offset: 1,
}
const educationColumns = ref<Array<TableColumn>>([
  { text: '毕业院校', value: 'graduateSchool', align: 'center' },
  { text: '专业', value: 'speciality', align: 'center' },
  { text: '学历', value: 'educationName', align: 'center' },
  { text: '时间', value: 'timeSpan', align: 'center' },
]) // 表头
const eduTotal = ref<number>(0) // 数据总条数
const educationList = ref<IStaffEducationInfo[]>([]) // 表格数据
/** ******* 教育档案表格结束 ********/

/** ******* 业务能力表格 ********/
const abiListQuery = {
  id: '',
  limit: 10,
  offset: 1,
}
const abilityColumns = ref<Array<TableColumn>>([
  { text: '时间', value: 'obtainDate', align: 'center', width: '160' },
  { text: '名称', value: 'abilityName', align: 'center', width: '240' },
  { text: '发表刊物（期号）/会议名称（获奖情况）', value: 'publication', align: 'center', width: '480' },
  { text: '备注', value: 'remark', align: 'center' },
  { text: '附件', value: 'file', align: 'center' },
]) // 表头
const abiTotal = ref<number>(0) // 数据总条数
const abilityList = ref<IStaffAbilityInfo[]>([])
/** ******* 业务能力表格结束 ********/

/** ******* 科研项目表格 ********/
const proListQuery = {
  id: '',
  limit: 10,
  offset: 1,
}
const projectColumns = ref<Array<TableColumn>>([
  { text: '时间', value: 'projectDate', align: 'center', width: '180' },
  { text: '名称', value: 'projectName', align: 'center' },
  { text: '备注', value: 'remark', align: 'center' },
  { text: '附件', value: 'file', align: 'center' },
]) // 表头
const proTotal = ref<number>(0) // 数据总条数
const projectList = ref<IStaffProjectInfo[]>([])
/** ******* 科研项目表格结束 ********/

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

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

// 子组件引用
const refEducationDialog = ref()
const refProjectDialog = ref()
const refAbilityDialog = ref()

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

// 查询表格列表
const getEducationListByStaffId = () => {
  getEducationList(eduListQuery).then((res) => {
    if (res.code === 200) {
      educationDict.value = JSON.parse(sessionStorage.getItem('educationDict')!)
      eduTotal.value = res.data.total
      educationList.value = res.data.rows.map((item: any) => ({
        ...item,
        educationName: getDictTextByValue(educationDict.value, item.education),
        timeSpan: jointDate(item.startDatem, item.endDate),
      }))
    }
  })
}

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

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

// 表格换页
const changeEducationPage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    eduListQuery.limit = val.size
  }
  if (val && val.page) {
    eduListQuery.offset = val.page
  }
  getEducationListByStaffId()
}

// 表格换页
const changeAbilityPage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    abiListQuery.limit = val.size
  }
  if (val && val.page) {
    abiListQuery.offset = val.page
  }
  getAbilityListByStaffId()
}

// 表格换页
const changeProjectPage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    proListQuery.limit = val.size
  }
  if (val && val.page) {
    proListQuery.offset = val.page
  }
  getProjectListByStaffId()
}

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

  ElMessageBox.confirm('是否删除教育档案记录，此操作不可恢复', '提示', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 前端界面删除
    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 delAbilityRecords = () => {
  if (abilitySelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

  ElMessageBox.confirm('是否删除业务能力记录，此操作不可恢复', '提示', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
  // 前端界面删除
    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 delProjectRecords = () => {
  if (projectSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

  ElMessageBox.confirm('是否删除科研项目记录，此操作不可恢复', '提示', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
  // 前端界面删除
    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()
      })
    }
  })
}

// 编辑
const showEditDialog = (row: IStaffEducationInfo | IStaffAbilityInfo | IStaffProjectInfo, tableName: string) => {
  switch (tableName) {
    case 'education' :
      refEducationDialog.value.initRecordData(row)
      refEducationDialog.value.showRecordDialog(true, '编辑')
      break

    case 'ability':
      refAbilityDialog.value.initRecordData(row)
      refAbilityDialog.value.showRecordDialog(true, '编辑')
      break

    case 'project':
      refProjectDialog.value.initRecordData(row)
      refProjectDialog.value.showRecordDialog(true, '编辑')
      break

    default:
      break
  }
}

// 新增
const addEditableRow = (tableName: string) => {
  switch (tableName) {
    case 'education':
      refEducationDialog.value.showRecordDialog(true, '新增')
      break

    case 'ability':
      refAbilityDialog.value.showRecordDialog(true, '新增')
      break

    case 'project':
      refProjectDialog.value.showRecordDialog(true, '新增')
      break

    default:
      break
  }
}

watch(() => props.staffId, (newVal: string) => {
  eduListQuery.id = newVal
  abiListQuery.id = newVal
  proListQuery.id = newVal

  getEducationListByStaffId()
  getAbilityListByStaffId()
  getProjectListByStaffId()
})
</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>

        <!-- 表格区域 -->
        <normal-table
          id="educationTabel"
          :data="educationList" :total="eduTotal" :columns="educationColumns"
          :query="{ limit: eduListQuery.limit, offset: eduListQuery.offset }"
          :is-showmulti-select="props.operation !== 'detail'"
          @change="changeEducationPage"
          @multi-select="eduMultiSelect"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (eduListQuery.offset - 1) * eduListQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>

          <template #columns>
            <el-table-column v-if="props.operation !== 'detail'" fixed="right" label="操作" align="center" width="130">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="showEditDialog(row, 'education')">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>

      <table-container title="业务能力" style="margin-top: 30px;">
        <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>

        <!-- 表格区域 -->
        <normal-table
          id="abilityTabel"
          :data="abilityList" :total="abiTotal" :columns="abilityColumns"
          :query="{ limit: abiListQuery.limit, offset: abiListQuery.offset }"
          :is-showmulti-select="props.operation !== 'detail'"
          @change="changeAbilityPage"
          @multi-select="abiMultiSelect"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (abiListQuery.offset - 1) * abiListQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>

          <template #columns>
            <el-table-column v-if="props.operation !== 'detail'" fixed="right" label="操作" align="center" width="130">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="showEditDialog(row, 'ability')">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>

      <table-container title="科研项目" style="margin-top: 30px;">
        <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>

        <!-- 表格区域 -->
        <normal-table
          id="projectTabel"
          :data="projectList" :total="proTotal" :columns="projectColumns"
          :query="{ limit: proListQuery.limit, offset: proListQuery.offset }"
          :is-showmulti-select="props.operation !== 'detail'"
          @change="changeProjectPage"
          @multi-select="proMultiSelect"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (proListQuery.offset - 1) * proListQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>

          <template #columns>
            <el-table-column v-if="props.operation !== 'detail'" fixed="right" label="操作" align="center" width="130">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="showEditDialog(row, 'project')">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </el-form>

    <education-dialog ref="refEducationDialog" :staff-id="props.staffId" @record-saved="getEducationListByStaffId" />
    <ability-dialog ref="refAbilityDialog" :staff-id="props.staffId" @record-saved="getAbilityListByStaffId" />
    <project-dialog ref="refProjectDialog" :staff-id="props.staffId" @record-saved="getProjectListByStaffId" />
  </app-container>
</template>
