<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" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <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-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="学期" prop="schoolTerm">
            <el-input 
              v-model="form.schoolTerm" 
              placeholder="请输入学期（如：1）" 
              clearable />
          </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-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="ClassAssessmentSettleDialog">
import { ref, reactive, nextTick, onMounted, computed } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/classassessmentsettle'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'

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

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

// 提交表单数据
const form = reactive({
  id: '',
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  classCode: '',
  virtualClassNo: ''
});

// 定义校验规则
const dataRules = ref({
  schoolYear: [
    { required: true, message: '学年不能为空', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '学期不能为空', trigger: 'blur' }
  ],
  classCode: [
    { required: true, message: '班号不能为空', trigger: 'change' }
  ]
})

// 班号选择变化
const handleClassChange = (classCode: string) => {
  const selectedClass = classList.value.find((item: any) => item.classCode === classCode)
  if (selectedClass) {
    form.virtualClassNo = selectedClass.classNo || ''
    // 后端会根据班号自动绑定学院，这里设置 deptCode 以便提交时使用
    form.deptCode = selectedClass.deptCode || ''
  }
}

// 打开弹窗
const openDialog = async (id?: string) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    schoolYear: '',
    schoolTerm: '',
    deptCode: '',
    classCode: '',
    virtualClassNo: ''
  })

  // 如果是新增，确保学年列表已加载，然后设置学年为列表中的第一条数据
  if (!id) {
    // 如果列表为空，先加载列表
    if (schoolYearList.value.length === 0) {
      await getSchoolYearList()
    }
    // 设置学年为列表中的第一条数据
    if (schoolYearList.value.length > 0) {
      form.schoolYear = schoolYearList.value[0].year
    }
    form.schoolTerm = '1' // 新增时默认学期为1
  }

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

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

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) 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) {
    useMessage().error(err.msg || '操作失败');
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getClassAssessmentSettleData = (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 || '',
          schoolYear: data.schoolYear || '',
          schoolTerm: data.schoolTerm || '',
          deptCode: data.deptCode || '',
          classCode: data.classCode || '',
          virtualClassNo: data.virtualClassNo || ''
        })
      }
    }
  }).catch((err: any) => {
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
    // 数据加载完成后，清除验证状态，避免触发验证
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  })
}

// 获取班号列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

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

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

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