<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>
        <el-button
          class="submit-btn"
          type="primary"
          style="width: 100%"
          @click="handleSubmit"
          >确认</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" link @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/base';
  import { useAppStore } from '@/store';

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

  const rules: FormRules = {
    examId: [
      {
        required: true,
        message: '请选择考试',
        trigger: 'change',
      },
    ],
  };

  const selectExam = ref({} as ExamItem);

  const onExamChange = (val: ExamItem) => {
    console.log('选择的考试ID:', val);
    selectExam.value = val || ({} as ExamItem);
  };

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

    console.log('选择的考试ID:', formData.examId);
    appStore.setInfo({ curExam: selectExam.value });
    // 提交成功后的操作，例如跳转到其他页面
  };

  // 回退按钮点击事件
  const handleGoBack = () => {
    // 假设登录页面的路由名称是 'Login' 或路径是 '/login'
    // 你可能需要根据项目的实际路由配置进行调整
    router.push({ name: 'Login' }); // 或者 router.back(); 如果是从登录页跳转过来的
  };
</script>
