<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="教师" prop="teacherNo">
            <el-select 
              v-model="form.teacherNo" 
              placeholder="请选择教师" 
              filterable
              style="width: 100%"
              @change="handleTeacherChange">
              <el-option
                v-for="item in teacherList"
                :key="item.teacherNo"
                :label="item.realName"
                :value="item.teacherNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable 
              filterable 
              style="width: 100%"
              @change="handleClassChange">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker
              v-model="form.beginTime"
              type="date"
              placeholder="选择开始时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              @change="handleBeginTimeChange" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="履历备注" prop="resumeRemark">
            <el-input
              v-model="form.resumeRemark"
              type="textarea"
              :rows="3"
              placeholder="请输入履历备注"
              maxlength="250"
              show-word-limit />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              maxlength="250"
              show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </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="ClassMasterResumeDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/classmasterresume'
import request from "/@/utils/request";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const teacherList = ref([])
const classList = ref([])

// 提交表单数据
const form = reactive({
  id: '',
  teacherNo: '',
  teacherNoVal: '',
  telPhone: '',
  classCode: '',
  className: '',
  beginTime: '',
  endTime: '',
  resumeRemark: '',
  remarks: ''
});

// 定义校验规则
const dataRules = ref({
  teacherNo: [
    { required: true, message: '教师不能为空', trigger: 'blur' }
  ],
  classCode: [
    { required: true, message: '班级不能为空', trigger: 'blur' }
  ],
  beginTime: [
    { required: true, message: '开始时间不能为空', trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: '结束时间不能为空', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || !form.beginTime) {
          callback()
          return
        }
        const beginTime = new Date(form.beginTime).getTime()
        const endTime = new Date(value).getTime()
        if (endTime < beginTime) {
          callback(new Error('结束时间不能小于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  resumeRemark: [
    { required: true, message: '履历备注不能为空', trigger: 'blur' }
  ]
})

// 获取教师列表
const getTeacherList = async () => {
  try {
    const res = await request({
      url: '/professional/teacherbase/TeacherBaseList',
      method: 'get'
    })
    teacherList.value = res.data || []
  } catch (err) {
  }
}

// 获取班级列表
const getClassList = async () => {
  try {
    const res = await request({
      url: '/basic/basicclass/listByRole',
      method: 'get'
    })
    classList.value = res.data || []
  } catch (err) {
  }
}

// 教师选择变化
const handleTeacherChange = (teacherNo: string) => {
  const teacher = teacherList.value.find((item: any) => item.teacherNo === teacherNo)
  if (teacher) {
    form.teacherNoVal = teacher.teacherNo || ''
    form.telPhone = teacher.telPhone || ''
  }
}

// 班级选择变化
const handleClassChange = (classCode: string) => {
  const classItem = classList.value.find((item: any) => item.classCode === classCode)
  if (classItem) {
    form.className = classItem.classNo || ''
  }
}

// 开始时间变化时，重新验证结束时间
const handleBeginTimeChange = () => {
  if (form.endTime) {
    nextTick(() => {
      dataFormRef.value?.validateField('endTime')
    })
  }
}

// 打开弹窗
const openDialog = (idOrData?: string | any) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    teacherNo: '',
    teacherNoVal: '',
    telPhone: '',
    classCode: '',
    className: '',
    beginTime: '',
    endTime: '',
    resumeRemark: '',
    remarks: ''
  })

  // 重置表单验证
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 如果传入的是对象（表格行数据），直接使用
  if (idOrData && typeof idOrData === 'object') {
    Object.assign(form, {
      id: idOrData.id || '',
      teacherNo: idOrData.teacherNo || '',
      teacherNoVal: idOrData.teacherNoVal || '',
      telPhone: idOrData.telPhone || '',
      classCode: idOrData.classCode || '',
      className: idOrData.className || '',
      beginTime: idOrData.beginTime || '',
      endTime: idOrData.endTime || '',
      resumeRemark: idOrData.resumeRemark || '',
      remarks: idOrData.remarks || ''
    })
  } 
  // 如果传入的是字符串（ID），调用接口获取详情
  else if (idOrData && typeof idOrData === 'string') {
    form.id = idOrData
    getClassMasterResumeData(idOrData)
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  // 前端验证：结束时间必须大于等于开始时间
  if (form.beginTime && form.endTime) {
    const beginTime = new Date(form.beginTime).getTime()
    const endTime = new Date(form.endTime).getTime()
    if (endTime < beginTime) {
      useMessage().error('结束时间不能小于开始时间')
      return false
    }
  }

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    // 响应拦截器已经处理了错误提示，这里不再重复提示
    // 但如果错误信息为空，则显示默认提示
    if (!err.msg) {
      useMessage().error('操作失败');
    }
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getClassMasterResumeData = (id: string) => {
  loading.value = true
  getObj({ id: id }).then((res: any) => {
    if (res.data) {
      // 处理返回数据，可能是数组或对象
      const data = Array.isArray(res.data) ? res.data[0] : res.data
      if (data) {
        // 先重置，再赋值
        Object.assign(form, {
          id: data.id || '',
          teacherNo: data.teacherNo || '',
          teacherNoVal: data.teacherNoVal || '',
          telPhone: data.telPhone || '',
          classCode: data.classCode || '',
          className: data.className || '',
          beginTime: data.beginTime || '',
          endTime: data.endTime || '',
          resumeRemark: data.resumeRemark || '',
          remarks: data.remarks || ''
        })
      }
    }
  }).catch((err: any) => {
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
  })
};

// 初始化
onMounted(() => {
  getTeacherList()
  getClassList()
})

// 暴露变量
defineExpose({
  openDialog
});
</script>

