<template>
  <el-dialog 
    title="指定带班教师" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="600px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px"
      v-loading="loading">
      <el-form-item label="学年" prop="schoolYear">
        <el-select 
          v-model="form.schoolYear" 
          placeholder="请选择学年" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in schoolYearList"
            :key="item.year"
            :label="item.year"
            :value="item.year">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学期" prop="schoolTerm">
        <el-select 
          v-model="form.schoolTerm" 
          placeholder="请选择学期" 
          clearable
          style="width: 100%">
          <el-option
            v-for="item in schoolTermList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班号" prop="classNo">
        <el-input 
          v-model="form.classNo" 
          placeholder="请输入班号" 
          clearable
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="教师" prop="teacherNo">
        <el-select 
          v-model="form.teacherNo" 
          placeholder="请选择教师" 
          clearable
          filterable
          style="width: 100%"
          @search="handleTeacherSearch">
          <el-option
            v-for="item in teacherList"
            :key="item.teacherNo"
            :label="`${item.realName}(${item.teacherNo})`"
            :value="item.teacherNo">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="StuWorkStudyAlternateTeacherDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { chooseTeacherAttendance } from '/@/api/stuwork/stuworkstudyalternate'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { getDicts } from '/@/api/admin/dict'
import { getTeacherInfoCommon } from '/@/api/professional/professionaluser/teacherbase'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const teacherList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  schoolYear: '',
  schoolTerm: '',
  classNo: '',
  teacherNo: ''
})

// 定义校验规则
const dataRules = {
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  classNo: [
    { required: true, message: '请输入班号', trigger: 'blur' }
  ],
  teacherNo: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ]
}

// 教师搜索
const handleTeacherSearch = async (keyword: string) => {
  if (!keyword) {
    teacherList.value = []
    return
  }
  try {
    const res = await getTeacherInfoCommon({ searchKeywords: keyword })
    if (res.data && Array.isArray(res.data)) {
      teacherList.value = res.data
    }
  } catch (err) {
    teacherList.value = []
  }
}

// 打开弹窗
const openDialog = async () => {
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.schoolYear = ''
    form.schoolTerm = ''
    form.classNo = ''
    form.teacherNo = ''
    teacherList.value = []
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return

  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    loading.value = true
    try {
      await chooseTeacherAttendance({
        schoolYear: form.schoolYear,
        schoolTerm: form.schoolTerm,
        classNo: form.classNo,
        teacherNo: form.teacherNo
      })
      useMessage().success('指定成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || '指定失败')
    } finally {
      loading.value = false
    }
  })
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

// 获取学期列表
const getSchoolTermList = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data
    }
  } catch (err) {
    schoolTermList.value = []
  }
}

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermList()
})

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

