<template>
  <div class="login-title">
    <h1>登录账号</h1>
    <p>请输入账号与密码</p>
  </div>
  <div class="login-form" @keyup.enter="submit">
    <el-form
      ref="formRef"
      size="large"
      :model="formData"
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="account">
        <el-input
          v-model.trim="formData.account"
          placeholder="请输入登录账号"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model.trim="formData.password"
          type="password"
          placeholder="请输入登录密码"
          show-password
          clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          class="submit-btn"
          type="primary"
          :loading="loading"
          style="width: 100%"
          @click="submit"
          >登录</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="router.push({ name: 'SwitchExam' })"
          >选择考试</el-button
        >
        <el-button type="primary" @click="router.push({ name: 'ResetInfo' })"
          >个人信息</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 useLoading from '@/hooks/loading';
  import { login } from '@/api/user';
  import { useAppStore, useUserStore } from '@/store';
  import { DEFAULT_ROUTE_NAME } from '@/router/constants';

  const router = useRouter();
  const appStore = useAppStore();
  const userStore = useUserStore();
  userStore.resetInfo();
  appStore.resetInfo();

  const formRef = ref<FormInstance>();
  const formData = reactive({
    account: '',
    password: '',
  });
  const rules: FormRules = {
    account: [
      {
        required: true,
        message: '请输入登录账号',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入登录密码',
      },
    ],
  };

  /* submit */
  const { loading, setLoading } = useLoading();
  async function submit() {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    setLoading(true);
    const data = await login(formData).catch(() => {});
    setLoading(false);
    if (!data) return;

    userStore.setInfo(data);

    // 首次登录强制修个人信息
    if (data.firstLogin) {
      router.push({
        name: 'ResetInfo',
      });
      return;
    }

    router.push({
      name: DEFAULT_ROUTE_NAME,
    });
  }
</script>
