<template>
  <div class="login-title">
    <h1>请选择评卷科目</h1>
    <p></p>
  </div>
  <div class="login-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      size="large"
      label-position="top"
    >
      <el-form-item prop="examId">
        <SelectExam
          v-model="formData.examId"
          size="large"
          @change="onExamChange"
        />
      </el-form-item>

      <el-form-item prop="subjectCode">
        <SelectSubject
          v-model="formData.subjectCode"
          size="large"
          :disabled="!formData.examId"
          @change="onSubjectChange"
        />
      </el-form-item>

      <el-form-item prop="groupId">
        <el-select
          v-model="formData.groupId"
          placeholder="请选择分组"
          size="large"
          :disabled="!formData.subjectCode"
          filterable
          clearable
          @change="onGroupChange"
        >
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :label="`分组：${item.groupNumber} - ${item.title} ${item.percent}%`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button class="submit-btn" type="primary" @click="handleSubmit"
          >确认</el-button
        >
        <el-button @click="handleGoBack">退出</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ExamItem } from '@/api/types/exam';
  import { MarkGroupItem } from '@/api/types/mark';
  import { getMarkGroupList } from '@/api/mark';
  import SelectExam from '@/components/select-exam/index.vue';
  import SelectSubject from '@/components/select-subject/index.vue';

  const router = useRouter();
  const formRef = ref<FormInstance>();
  const formData = reactive({
    examId: null,
    subjectCode: null,
    groupId: null,
  });

  const rules: FormRules = {
    examId: [
      {
        required: true,
        message: '请选择考试',
        trigger: 'change',
      },
    ],
    subjectCode: [
      {
        required: true,
        message: '请选择科目',
        trigger: 'change',
      },
    ],
    groupId: [
      {
        required: true,
        message: '请选择分组',
        trigger: 'change',
      },
    ],
  };

  const selectExam = ref({} as ExamItem);
  const selectSubject = ref({} as any);
  const selectGroup = ref({} as MarkGroupItem);
  const groupList = ref<MarkGroupItem[]>([]);

  const onExamChange = (val: ExamItem) => {
    console.log('选择的考试:', val);
    selectExam.value = val || ({} as ExamItem);
    // 重置科目和分组
    formData.subjectCode = null;
    formData.groupId = null;
    groupList.value = [];
  };

  // 加载分组列表
  const loadGroupList = async () => {
    if (!formData.subjectCode) {
      groupList.value = [];
      return;
    }

    try {
      const res = await getMarkGroupList({
        pageNumber: 1,
        pageSize: 1000,
        subjectCode: formData.subjectCode,
      });
      groupList.value = res || [];
    } catch (error) {
      console.error('加载分组列表失败:', error);
      groupList.value = [];
    }
  };

  const onSubjectChange = (val: any) => {
    console.log('选择的科目:', val);
    selectSubject.value = val || {};
    // 重置分组
    formData.groupId = null;
    loadGroupList();
  };

  const onGroupChange = (val: number) => {
    console.log('选择的分组ID:', val);
    const group = groupList.value.find((item) => item.id === val);
    selectGroup.value = group || ({} as MarkGroupItem);
  };

  // 确认按钮点击事件
  const handleSubmit = async () => {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    console.log('选择的信息:', {
      exam: selectExam.value,
      subject: selectSubject.value,
      group: selectGroup.value,
    });

    // 保存选择的信息到

    // TODO:提交成功后的操作，例如跳转到评卷页面
    // router.push({ name: 'MarkPage' });
  };

  // 回退按钮点击事件
  const handleGoBack = () => {
    router.push({ name: 'Login' });
  };
</script>
