<!-- 人员登记 基本信息 -->
<script name="RegisterResume" lang="ts" setup>
import { ElMessage, dayjs } from 'element-plus'
import type { IStaffPromoteInfo, IStaffResumeInfo } from '../person-regitster'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { addPromoteRecList, addResumeRecList, delPromoteRecList, delResumeRecList, getPromoteList, getResumeList } from '@/api/resource/register'

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

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

const resumeColumns = [
  { text: '履历名称', value: 'resumeName', align: 'center', required: true },
  { text: '详细介绍', value: 'details', align: 'center', required: true },
  { text: '时间', value: 'resumeDate', align: 'center', width: '160', required: true },
] // 表头

const promoteColumns = [
  { text: '晋升经历', value: 'promoteExperience', align: 'center', required: true },
  { text: '晋升单位', value: 'company', align: 'center', required: true },
  { text: '时间', value: 'promoteDate', align: 'center', width: '160', required: true },
] // 表头

const resumeList = ref<IStaffResumeInfo[]>([]) // 表格数据
const promoteList = ref<IStaffPromoteInfo[]>([])

// 表格被选中的行
const resumeSelected = ref<IStaffResumeInfo[]>([])
const promoteSelected = ref<IStaffPromoteInfo[]>([])

const resumeRecord: IStaffResumeInfo = {
  id: '',
  staffId: '',
  resumeName: '',
  details: '',
  resumeDate: '',
  editable: true,
}

const promoteRecord: IStaffPromoteInfo = {
  id: '',
  staffId: '',
  promoteExperience: '',
  company: '',
  promoteDate: '',
  editable: true,
}

// 逻辑
const addEditableRow = (tableName: string) => {
  switch (tableName) {
    case 'resume':
      resumeList.value = resumeList.value.map((item: any) => ({
        ...item,
        resumeDate: dayjs(item.resumeDate).format('YYYY-MM-DD'),
      }))
      if (useCheckList(resumeList.value, resumeColumns, '经验履历')) {
        useSetAllRowReadable(resumeList.value)
        resumeList.value.push({ ...resumeRecord })
      }
      break

    case 'promote':
      promoteList.value = promoteList.value.map((item: any) => ({
        ...item,
        promoteDate: dayjs(item.promoteDate).format('YYYY-MM-DD'),
      }))
      if (useCheckList(promoteList.value, promoteColumns, '晋升情况')) {
        useSetAllRowReadable(promoteList.value)
        promoteList.value.push({ ...promoteRecord })
      }
      break

    default:
      break
  }
}

// 表格多选
const rsmMultiSelect = (e: any) => {
  resumeSelected.value = e
}
const prmMultiSelect = (e: any) => {
  promoteSelected.value = e
}

const getResumeListByStaffId = () => {
  getResumeList(listQuery).then((res) => {
    if (res.code === 200) {
      resumeList.value = res.data.rows.map((item: any) => ({
        ...item,
        resumeDate: dayjs(item.resumeDate).format('YYYY-MM-DD'),
      }))
    }
  })
}

const getPromoteListByStaffId = () => {
  getPromoteList(listQuery).then((res) => {
    if (res.code === 200) {
      promoteList.value = res.data.rows.map((item: any) => ({
        ...item,
        promoteDate: dayjs(item.promoteDate).format('YYYY-MM-DD'),
      }))
    }
  })
}

// 增加经验履历记录
const addResumeRecords = () => {
  if (useCheckList(resumeList.value, resumeColumns, '经验履历') === false) {
    return
  }

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

  if (newRecords.value.length > 0) {
    addResumeRecList(newRecords.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('添加经验履历记录成功')
        getResumeListByStaffId()
      }
      else {
        ElMessage.error(`添加经验履历记录失败：${res.message}`)
      }
    })
  }
}

// 删除经验履历记录
const delResumeRecords = () => {
  if (resumeSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

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

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

      getResumeListByStaffId()
    })
  }
}

// 增加晋升情况记录
const addPromoteRecords = () => {
  if (useCheckList(promoteList.value, promoteColumns, '晋升情况') === false) {
    return
  }

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

  if (newRecords.value.length > 0) {
    addPromoteRecList(newRecords.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('添加晋升情况记录成功')
        getPromoteListByStaffId()
      }
      else {
        ElMessage.error(`添加晋升情况记录失败：${res.message}`)
      }
    })
  }
}

// 删除晋升情况记录
const delPromoteRecords = () => {
  if (promoteSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

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

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

      getPromoteListByStaffId()
    })
  }
}

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

  getResumeListByStaffId()
  getPromoteListByStaffId()
})

defineExpose({
  addResumeRecords,
  addPromoteRecords,
})
</script>

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

        <!-- 表格区域 -->
        <el-table :data="resumeList" border style="width: 100%;" @selection-change="rsmMultiSelect">
          <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 resumeColumns"
            :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 === 'resumeDate'" v-model="scope.row.resumeDate" 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('promote')">
            增加行
          </el-button>
          <el-button type="info" @click="delPromoteRecords">
            删除行
          </el-button>
        </template>

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