<template>
  <div class="login login-box">
    <div class="login-theme">
      <h2>
        欢迎登录 <br />
        预约报名系统
      </h2>

      <p class="login-webinfo">
        <a href="http://www.qmth.com.cn" target="_blank"
          >Copyright © 2024 启明泰和</a
        >
        <!-- <br /> -->
        <!-- <a href="https://beian.miit.gov.cn/" target="_blank">
          启明泰和 鄂ICP备12000033号-9</a
        > -->
        <span v-if="appStore.version"> v{{ appStore.version }}</span>
      </p>
    </div>
    <div class="login-body" @keyup.enter="submit">
      <div class="login-title">
        <h1>输入信息</h1>
        <p>请输入账号与密码</p>
      </div>
      <div class="login-form">
        <a-form
          ref="formRef"
          size="large"
          :model="formData"
          :rules="rules"
          :label-col-props="{ span: 0, offset: 0 }"
          :wrapper-col-props="{ span: 24, offset: 0 }"
        >
          <a-form-item field="account">
            <a-input
              v-model.trim="formData.account"
              placeholder="请输入账号"
              allow-clear
            >
            </a-input>
          </a-form-item>
          <a-form-item field="password">
            <a-input-password
              v-model.trim="formData.password"
              placeholder="请输入密码"
              allow-clear
            >
            </a-input-password>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" :loading="loading" long @click="submit"
              >登录</a-button
            >
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import type { FormInstance, FieldRule } from '@arco-design/web-vue/es/form';
  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: Record<string, FieldRule[]> = {
    account: [
      {
        required: true,
        message: '请输入用户名',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
      },
    ],
  };

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

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

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