<template>
  <div class="px-3">
    <div class="resume-header mb-3">
      <div class="resume-title">学生信息编辑</div>
    </div>
    <div class="d-flex flex-column align-center pt-5">
      <CtForm ref="CtFormRef" :items="items" style="width: 900px;"></CtForm>
      <v-btn class="buttons mt-5 elevation-5" color="primary" @click.stop="handleSubmit">{{ $t('common.save') }}</v-btn>
    </div>
  </div>

  <Loading :visible="overlay"></Loading>
</template>

<script setup>
defineOptions({name: 'personal-personCenter-studentInformation-index'})
import { ref, onMounted } from 'vue'
import { saveStudentSimpleInfo } from '@/api/recruit/personal/shareJob'
import { useI18n } from '@/hooks/web/useI18n'
import Snackbar from '@/plugins/snackbar'
import { isValidIdCard18 } from '@/utils/validate'
import { useUserStore } from '@/store/user'
import { getSchoolList, getDepartmentListBySchoolId, getMajorList } from '@/api/recruit/personal/student'

const { t } = useI18n()
const userStore = useUserStore()
const overlay = ref(false)

const CtFormRef = ref()

// 专业名称下拉列表
let majorName = null
const getMajorData = async (name) => {
  const item = items.value.options.find(e => e.key === 'majorId')
  if (!item) return
  if (item.items?.length && (majorName === name)) return // 防抖
  majorName = name
  if (name) {
    const data = await getMajorList({ name })
    item.items = data
  }
}

const items = ref({
  options: [
    {
      type: 'autocomplete',
      key: 'schoolId',
      value: null,
      default: null,
      label: '就读学校 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'schoolId',
      rules: [v => !!v || '请选择就读学校'],
      items: [],
      change: e => getDepartmentList(e, 'schoolDeptId', 0, true),
    },
    {
      type: 'autocomplete',
      key: 'schoolDeptId',
      value: null,
      default: null,
      label: '所在院系 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      rules: [v => !!v || '请选择所在院系'],
      change: e => getDepartmentList(e, 'schoolClassId', 2, true),
      items: []
    },
    {
      type: 'combobox',
      key: 'schoolClassId',
      value: null,
      label: '所在班级 *',
      outlined: true,
      clearable: true,
      canBeInputted: true,
      itemTextName: 'schoolClassName',
      itemText: 'name',
      itemValue: 'id',
      rules: [v => !!v || '请选择所在班级'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'majorId',
      value: null,
      label: '所学专业 *',
      outlined: true,
      itemText: 'nameCn',
      itemValue: 'id',
      rules: [v => !!v || '请选择所学专业'],
      search: e => getMajorData(e),
      items: []
    },
    {
      type: 'text',
      key: 'studentNo',
      value: '',
      default: null,
      label: '学号 *',
      outlined: true,
      rules: [v => !!v || '请填写学号']
    },
    {
      type: 'text',
      key: 'idCardNo',
      value: '',
      label: '身份证号码 *',
      rules: [
        value => {
          if (!value) {
            return '请输入您的身份证号码'
          }
          return true
        },
        value => {
          if (!isValidIdCard18(value)) {
            return '请输入正确的身份证号码'
          }
          return true
        }
      ]
    },
    {
      type: 'text',
      key: 'emergencyContactName',
      value: '',
      default: null,
      label: '紧急联系人姓名 *',
      outlined: true,
      rules: [v => !!v || '请填写紧急联系人姓名']
    },
    {
      type: 'phoneNumber',
      key: 'emergencyContactPhone',
      value: '',
      label: '紧急联系人手机号 *',
      rules: [v => !!v || '请填写紧急联系人手机号']
    }
  ]
})

// 左侧加mr
items.value.options.forEach((e, index) => {
  e.col = 6
  if ((index + 2) % 2 === 0) e.flexStyle = 'mr-3'
})

// 学校下拉列表
const getSchoolListData = async () => {
  const item = items.value.options.find(e => e.key === 'schoolId')
  if (!item) return
  const data = await getSchoolList()
  item.items = data || []
}


// 根据学校id获取院系、班级列表
const getDepartmentList = async (id, key, type, isRefreshValue = false) => {
  const item = items.value.options.find(e => e.key === key)
  if (!item) return

  let params = { type } // type: 0院系|1专业|2班级
  // 查院系用schoolId，查班级用parentId
  if (key === 'schoolDeptId') params.schoolId = id
  else params.parentId = id

  const data = await getDepartmentListBySchoolId(params)
  item.items = data || []

  // 下拉框选择时需清空下级value
  if (isRefreshValue) item.value = null
}

// 获取学生基本信息
const studentInfoFun = async () => {
  // await userStore.getStudentInformation()
  const data = JSON.parse(localStorage.getItem('studentInfo') || '{}')
  if (data.schoolId) getDepartmentList(data.schoolId, 'schoolDeptId', 0)
  if (data?.schoolClassId) getDepartmentList(data.schoolDeptId, 'schoolClassId', 2)
  if (data?.majorId) {
    getMajorData(data?.major?.nameCn)
  }
  // 回显
  items.value.options.forEach(e => {
    if (data[e.key]) {
      e.value = data[e.key]
    }
  })
}
onMounted(() => {
  // 获取学校列表
  getSchoolListData()
  // 获取学生基本信息
  studentInfoFun()
})

// 提交
const handleSubmit = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  overlay.value = true
  const params = {}
  items.value.options.forEach(item => {
    // 班级有下拉选择的，需要根据选择的值赋值
    if (item.key === 'schoolClassId') {
      const classObj = item.items.find(e => e[item.itemValue] === item.value)
      if (!classObj) {
        params[item.key] = null
        params[item.itemTextName] = item.value
      } else params[item.key] = item.value
    } else params[item.key] = item.value
  })

  await saveStudentSimpleInfo(params)
  setTimeout(async () => {
    await userStore.getStudentInformation()
    studentInfoFun()
    Snackbar.success(t('common.submittedSuccessfully'))
    overlay.value = false
  }, 1000)
}

</script>

<style scoped lang="scss">
</style>
