<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"
          default-first
          @change="onExamChange"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          class="submit-btn"
          type="primary"
          style="width: 100%"
          @click="submit"
          >确认</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" link @click="goBack"
          >退出</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import type { FormInstance, FormRules } from 'element-plus';
  import { useAppStore } from '@/store';
  import { ExamItem } from '@/api/types/exam';
  import { switchExam } from '@/api/user';
  import { DEFAULT_ROUTE_NAME } from '@/router/constants';
  import useLoading from '@/hooks/loading';

  const appStore = useAppStore();
  const router = useRouter();
  const route = useRoute();

  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) => {
    selectExam.value = val || ({} as ExamItem);
  };

  // 确认按钮点击事件
  const { loading, setLoading } = useLoading();
  const submit = async () => {
    if (loading.value) return;
    try {
      const valid = await formRef.value?.validate().catch(() => false);
      if (!valid) return;

      setLoading(true);

      await switchExam(formData.examId);
      appStore.setInfo({ curExam: selectExam.value });

      if (route.query.backUrl) {
        router.push(route.query.backUrl as string);
      } else {
        router.push({
          name: DEFAULT_ROUTE_NAME,
        });
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

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