<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="120px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="入学日期" prop="enterDate">
            <el-date-picker
              v-model="form.enterDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="专业" prop="majorCode">
            <el-select 
              v-model="form.majorCode" 
              placeholder="请选择" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in majorList"
                :key="item.majorCode"
                :label="item.majorName"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="form.deptCode" 
              placeholder="请选择" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in deptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班级代码" prop="classCode">
            <el-input 
              v-model="form.classCode" 
              placeholder="请输入班级代码" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班号" prop="classNo">
            <el-input 
              v-model="form.classNo" 
            placeholder="自动填充班号" 
            :disabled="true" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班级名称" prop="className">
            <el-input 
              v-model="form.className" 
              placeholder="请输入班级名称" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班级规范名称" prop="classProName">
            <el-input 
              v-model="form.classProName" 
            placeholder="自动拼接班级规范名称" 
            :disabled="true" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="入学年份" prop="grade">
            <el-input 
              v-model="form.grade" 
            placeholder="自动填充入学年份" 
            :disabled="true" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班主任" prop="teacherNos">
            <el-select 
              v-model="form.teacherNos" 
              placeholder="请选择班主任" 
              clearable
              filterable
              style="width: 100%">
              <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="preStuNum">
            <el-input-number
              v-model="form.preStuNum"
              :precision="0"
              :step="1"
              :min="0"
              placeholder="请输入预计招生人数"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入备注"
              maxlength="500"
              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="BasicClassDialog">
import { ref, reactive, nextTick, onMounted, watch, computed } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getDetail, addObj, putObj, getMajorNameList, getDeptList } from '/@/api/basic/basicclass'
import { getTeacherBaseList } from '/@/api/professional/professionaluser/teacherbase'

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

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const majorList = ref<any[]>([])
const deptList = ref<any[]>([])
const teacherList = ref<any[]>([])
const yearLast = ref('') // 年份后两位
const majorName = ref('') // 专业名称

// 提交表单数据
const form = reactive({
  id: '',
  enterDate: '',
  majorCode: '',
  deptCode: '',
  classCode: '',
  classNo: '',
  className: '',
  classProName: '',
  grade: '',
  teacherNos: '',
  preStuNum: 0,
  remark: ''
});

// 定义校验规则
const dataRules = ref({
  enterDate: [
    { required: true, message: '入学日期不能为空', trigger: 'change' }
  ],
  majorCode: [
    { required: true, message: '专业不能为空', trigger: 'change' }
  ],
  deptCode: [
    { required: true, message: '学院不能为空', trigger: 'change' }
  ],
  classCode: [
    { required: true, message: '班级代码不能为空', trigger: 'blur' },
    { min: 4, message: '班级代码至少4位（班号取后4位）', trigger: 'blur' }
  ],
  classNo: [
    { required: true, message: '班号不能为空', trigger: 'blur' }
  ],
  className: [
    { required: true, message: '班级名称不能为空', trigger: 'blur' }
  ],
  classProName: [
    { required: true, message: '班级规范名称不能为空', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '入学年份不能为空', trigger: 'blur' }
  ],
  teacherNos: [
    { required: true, message: '请选择班主任', trigger: 'change' }
  ],
  preStuNum: [
    { required: true, message: '预计招生人数不能为空', trigger: 'blur' }
  ]
})

// 打开弹窗
const openDialog = (id?: string) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    enterDate: '',
    majorCode: '',
    deptCode: '',
    classCode: '',
    classNo: '',
    className: '',
    classProName: '',
    grade: '',
    teacherNos: '',
    preStuNum: 0,
    remark: ''
  })
  
  // 重置辅助变量
  yearLast.value = ''
  majorName.value = ''

  // 清除表单验证状态，不触发验证
  nextTick(() => {
    dataFormRef.value?.clearValidate();
    dataFormRef.value?.resetFields();
  });

  // 获取详情
  if (id) {
    form.id = id
    getBasicClassData(id)
  } else {
    // 新增时，确保验证状态已清除
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  }
};

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

  try {
    loading.value = true;
    // 构建提交数据，将班主任工号放到 teacherNo 字段
    const submitData = {
      ...form,
      teacherNo: form.teacherNos // 将 teacherNos 的值赋值给 teacherNo
    };
    
    if (form.id) {
      await putObj(submitData);
      useMessage().success('编辑成功');
    } else {
      await addObj(submitData);
      useMessage().success('新增成功');
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || (form.id ? '编辑失败' : '新增失败'));
  } finally {
    loading.value = false;
  }
};

// 获取详情
const getBasicClassData = async (id: string) => {
  loading.value = true
  try {
    const res = await getDetail(id)
    if (res.data) {
      Object.assign(form, {
        id: res.data.id || '',
        enterDate: res.data.enterDate || '',
        majorCode: res.data.majorCode || '',
        deptCode: res.data.deptCode || '',
        classCode: res.data.classCode || '',
        classNo: res.data.classNo || '',
        className: res.data.className || '',
        classProName: res.data.classProName || '',
        grade: res.data.grade || '',
        teacherNos: res.data.teacherNos || '',
        preStuNum: res.data.preStuNum || 0,
        remark: res.data.remark || ''
      })
      
      // 设置辅助变量（编辑时不自动填充，保持原有数据）
      if (res.data.enterDate && res.data.enterDate.length >= 4) {
        yearLast.value = res.data.enterDate.substring(2, 4)
      }
      // 确保专业列表已加载后再设置专业名称
      if (res.data.majorCode && majorList.value.length > 0) {
        const major = majorList.value.find(item => item.majorCode === res.data.majorCode)
        if (major) {
          majorName.value = major.majorName || ''
        }
      }
    }
  } catch (err: any) {
    console.error('获取详情失败', err)
    useMessage().error('获取详情失败')
  } finally {
    loading.value = false
    // 数据加载完成后，清除验证状态，避免触发验证
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  }
}

// 获取专业列表
const getMajorListData = async () => {
  try {
    const res = await getMajorNameList()
    if (res.data) {
      majorList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取专业列表失败', err)
    majorList.value = []
  }
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学院列表失败', err)
    deptList.value = []
  }
}

// 获取班主任列表
const getTeacherListData = async () => {
  try {
    const res = await getTeacherBaseList()
    if (res.data) {
      teacherList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取班主任列表失败', err)
    teacherList.value = []
  }
}

// 拼接班级规范名称
const montageClassProName = () => {
  // 只在新增模式下自动填充，编辑模式下不覆盖已有数据
  if (!form.id && yearLast.value && majorName.value) {
    form.classProName = yearLast.value + majorName.value
    if (form.classNo) {
      form.classProName = yearLast.value + majorName.value + '(' + form.classNo + ')'
    }
    console.log('classProName', form.classProName)
  }
}

// 监听入学日期,取年份后两位
watch(() => form.enterDate, (newVal) => {
  if (newVal && newVal.length >= 4) {
    console.log('newdate:', newVal)
    yearLast.value = newVal.substring(2, 4)
    // 只在新增模式下自动填充入学年份
    if (!form.id) {
      form.grade = newVal.substring(0, 4)
    }
    montageClassProName()
  }
})

// 监听班级代码,取后四位为班号（班级代码至少4位）
watch(() => form.classCode, (newVal) => {
  if (newVal) {
    const length = newVal.length
    if (length >= 4) {
      // 只在新增模式下自动填充班号，编辑模式下如果班号为空才填充
      if (!form.id || !form.classNo) {
        form.classNo = newVal.substring(length - 4, length)
        montageClassProName()
      }
    }
  }
})

// 监听专业代码变化，获取专业名称
watch(() => form.majorCode, (newVal) => {
  if (newVal) {
    const major = majorList.value.find(item => item.majorCode === newVal)
    if (major) {
      majorName.value = major.majorName || ''
      montageClassProName()
    }
  } else {
    majorName.value = ''
    montageClassProName()
  }
})

// 初始化
onMounted(() => {
  getMajorListData()
  getDeptListData()
  getTeacherListData()
})

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