<template>
  <div class="resume-box">
    <div class="resume-header mb-3">
      <div class="resume-title">{{ $t('resume.educationExp') }}</div>
      <v-btn  variant="text" color="primary" prepend-icon="mdi-plus-box" @click="handle(0)">{{ $t('common.add') }}</v-btn>
    </div>
    <!-- 编辑-表单 -->
    <div v-if="isEdit" class="educExpItem-edit">
      <h4 class="color6 my-3 mx-2"> {{ titleStatus ? $t('common.edit') : $t('common.add') }}{{ $t('resume.educationExp') }}</h4>
      <CtForm ref="CtFormRef" :items="formItems" style="width: 100%;"></CtForm>
      <div class="text-end mt-3">
        <v-btn class="half-button mr-3" variant="tonal" @click="isEdit = false">{{ $t('common.cancel') }}</v-btn>
        <v-btn color="primary" class="half-button" @click="handleSave">{{ $t('common.save') }}</v-btn>
      </div>
    </div>
    <!-- 展示 -->
    <div v-else-if="!dataList?.length" class="resumeNoDataText">{{ $t('resume.dataDefaultPrompt') }}{{ $t('resume.educationExp') }}...</div>
    <div
      v-else
      v-for="(item, index) in dataList" :key="'educationExp' + index"
      :class="[' mx-n2', {'mt-5': index }]"
    >
      <div class="educExpItem" @mouseenter="item.active = true" @mouseleave="item.active = false">
        <div class="level1 d-flex align-center justify-space-between" style="height: 40px;">
          <div>
            <span style="font-size: 18px; font-weight: bold;">{{ item.schoolName }}</span>
            <span class="color6 font15 ml-5">
              <span>{{ timesTampChange(item.startTime, 'Y-M') }}</span>
              <span class="mx-1">至</span>
              <span>{{ timesTampChange(item.endTime, 'Y-M') }}</span>
            </span>
          </div>
          <div v-if="item.active">
            <v-btn  variant="text" color="primary" prepend-icon="mdi-square-edit-outline" @click="handle(item)">{{ $t('common.edit') }}</v-btn>
            <v-btn  variant="text" color="primary" prepend-icon="mdi-trash-can-outline" @click="handleDelete(item)">{{ $t('common.delete') }}</v-btn>
          </div>
        </div>
        <div class="level2 my-2">
          <span class="color6 font15">{{ item.major }}</span>
          <span class="septal-line"  v-if="item.educationSystemType"></span>
          <span class="color6 font15">{{ getText(item.educationSystemType, dictItemsObj.educationSystemType) }}</span>
        </div>
        <div class="level3">
          <span class="color6 font15">在校经历：{{ item.content || '暂无描述' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="educationExp">
import CtForm from '@/components/CtForm'
import Snackbar from '@/plugins/snackbar'
import { getDict } from '@/hooks/web/useDictionaries'
import { getTimeStamp, timesTampChange } from '@/utils/date'
import { saveResumeEduExp, getResumeEduExp, deleteResumeEduExp, schoolSearchByName, schoolMajorByName } from '@/api/recruit/personal/resume'
import Confirm from '@/plugins/confirm'
import { getText, dealCanBeInputtedSave, dealCanBeInputtedValueAndLabel } from '@/utils/getText'
import { debounce } from 'lodash'
import { nextTick, reactive, ref } from 'vue'
const editId = ref(null)
const CtFormRef = ref()
const dictItemsObj = reactive({})

// 学校下拉列表
const getSchoolListData = async (name, init = '') => {
  const item = formItems.value.options.find(e => e.key === 'schoolId')
  if (!item) return
  item[item.itemTextName] = name
  if (!init) item.value = null
  const data = await schoolSearchByName({ name })
  item.items = data
}
const debouncedCallbackSchool = debounce(newValue => {
  if (!newValue) return
  getSchoolListData(newValue)
}, 500)

// 专业下拉列表
const getMajorListData = async (name, init = '') => {
  if (name === '') return // 此接口不支持传空值
  const item = formItems.value.options.find(e => e.key === 'majorId')
  item[item.itemTextName] = name
  if (!init) item.value = null
  const data = await schoolMajorByName({ name })
  item.items = data
}
const debouncedCallbackMajor = debounce(newValue => {
  getMajorListData(newValue)
}, 500)

const formItems = ref({
  options: [
    {
      type: 'combobox',
      key: 'schoolId',
      value: null,
      default: null,
      label: '学校名称 *',
      col: 6,
      outlined: true,
      clearable: true,
      canBeInputted: true, //
      itemTextName: 'schoolName',
      itemText: 'value',
      itemValue: 'key',
      rules: [v => !!v || '请选择学校名称'],
      search: debouncedCallbackSchool,
      items: []
    },
    {
      type: 'combobox',
      key: 'majorId',
      value: null,
      default: null,
      label: '所学专业 *',
      col: 6,
      outlined: true,
      clearable: true,
      canBeInputted: true, //
      itemTextName: 'major',
      itemText: 'nameCn',
      itemValue: 'id',
      rules: [v => !!v || '请选择所学专业'],
      search: debouncedCallbackMajor,
      items: []
    },
    {
      type: 'autocomplete',
      key: 'educationType',
      value: null,
      default: null,
      label: '学历 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      rules: [v => !!v || '请选择学历'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'educationSystemType',
      value: null,
      default: null,
      label: '学制类型 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      rules: [v => !!v || '请选择学制类型'],
      items: dictItemsObj.educationSystemType,
    },
    {
      type: 'datePicker',
      key: 'startTime',
      dateType: 'month', // 时间类型 year month date time
      value: null,
      label: '起始时间 *',
      col: 6,
      outlined: true,
      clearable: true,
      rules: [v => !!v || '请选择起始时间']
      // options: {},
    },
    {
      type: 'datePicker',
      key: 'endTime',
      dateType: 'month', // 时间类型 year month date time
      value: null,
      label: '结束时间 *',
      col: 6,
      outlined: true,
      clearable: true,
      rules: [v => !!v || '请选择结束时间']
      // options: {},
    },
    {
      type: 'textarea',
      key: 'content',
      value: null,
      default: null,
      rows: 5,
      resize: true,
      counter: 1600,
      label: '在校经历',
      outlined: true
    },
  ]
})
// 左侧加mr
formItems.value.options.forEach((e, index) => {
  if (((index + 2) % 2 === 0) && Boolean(e.col) && e.col !== 12) e.flexStyle = 'mr-3'
})

// 获取数据
const dataList = ref([])
const getData = async () => {
  const data = await getResumeEduExp()
  dataList.value = data
}
getData()

// 新增 或 编辑
const isEdit = ref(false)
const titleStatus = ref(0)
const handle = (item) => {
  titleStatus.value = item ? 1 : 0
  if (item) { // 编辑
    editId.value = item.id
    formItems.value.options.forEach(e => { // 回显
      if (e.canBeInputted) { // 特殊处理可输入下拉框
        dealCanBeInputtedValueAndLabel(e, item)
        // if (item[e.key] && item[e.itemTextName]) { e.search(item[e.itemTextName], '触发下拉框内容'); e.value = item[e.key] }
        // else { e.value = item[e.itemTextName]; e[e.itemTextName] = item[e.itemTextName] }
      }
      else if (e.type === 'datepicker') e.value = timesTampChange(item[e.key], 'Y-M')
      else if (item[e.key]) e.value = item[e.key]
    })
  } else { // 新增
    editId.value = null
    formItems.value.options.forEach(e => e.value = e.default || null)
  }
  nextTick(() => {
    isEdit.value = true
  })
}

// 保存-基础信息
const handleSave = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  const obj = {}
  formItems.value.options.forEach(e => {
    if (e.canBeInputted) { // 特殊处理可输入下拉框
      dealCanBeInputtedSave(e, obj)
      // if (e.value === e[e.itemTextName]) { obj[e.key] = ''; obj[e.itemTextName] = e[e.itemTextName] }
      // else { obj[e.key] = e.value; obj[e.itemTextName] = e[e.itemTextName] }
    }
    else if (e.type === 'datepicker') obj[e.key] = getTimeStamp(e.value)
    else obj[e.key] = e.value
  })
  if (editId.value) obj.id = editId.value
  await saveResumeEduExp(obj)
  Snackbar.success('保存成功！')
  isEdit.value = false
  await getData()
}

// 删除数据
const handleDelete = ({ id }) => {
  Confirm('系统提示', '是否确认删除此教育经历？').then(async () => {
    await deleteResumeEduExp(id)
    getData(id)
    Snackbar.success('删除成功！')
  })
}

// 获取字典内容
const dictList = [
  { type: 'menduner_education_type', key: 'educationType' },
  { type: 'menduner_education_system_type', key: 'educationSystemType' }
]
const getDictData = async (obj) => {
  const item = formItems.value.options.find(e => e.key === obj.key)
  if (item) { //  && !item.items?.length
    const { data } = await getDict(obj.type)
    item.items = data || []
    dictItemsObj[obj.key] = data || []
  }
}
const getOptions = () => {
  dictList.forEach(obj =>  getDictData(obj))
}
getOptions()

</script>

<style scoped lang="scss">
.font15 { font-size: 15px;; }
.color9 { color: var(--color-999); }
.color6 { color: var(--color-666); }
.educExpItem {
  cursor: pointer;
  border-radius: 6px;
  padding: 2px 10px 8px;
  &:hover {
    background-color: var(--color-f8);
  }
}
.educExpItem-edit {
  border-radius: 6px;
  padding: 2px 10px 8px;
  background-color: var(--color-f8);
}
</style>
