<!-- 管理后台登录页，负责管理员凭据校验和登录后页面跳转。 -->
<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import AppIcon from "@/components/AppIcon.vue";
import logoUrl from "@/assets/logo";
import { apiError } from "@/api/http";
import { useAuthStore } from "@/stores/auth";
import { useToastStore } from "@/stores/toast";
import { DEFAULT_ADMIN_PATH } from "@/router/adminNavigation";

const auth = useAuthStore();
const toast = useToastStore();
const router = useRouter();
const route = useRoute();
const form = reactive({ username: "", password: "" });
const formRef = ref<FormInstance>();
const rules: FormRules = {
  username: [{ required: true, message: "请输入管理员账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};
async function submit() {
  if (auth.loading) return;
  if (!(await formRef.value?.validate().catch(() => false))) return;
  try {
    await auth.login(form.username, form.password);
    router.replace(String(route.query.redirect || DEFAULT_ADMIN_PATH));
  } catch (error) {
    const detail = apiError(error);
    toast.error(detail.message, detail.copyText);
  }
}
</script>

<template>
  <main class="login-page">
    <section class="login-panel">
      <div class="login-brand">
        <span class="brand-mark"
          ><img
            :src="logoUrl"
            alt="" /></span
        ><span>剧游AI</span>
      </div>
      <div class="login-heading"><h1 id="login-title">管理后台登录</h1></div>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        size="large"
        @submit.prevent="submit"
      >
        <el-form-item
          label="管理员账号"
          prop="username"
          ><el-input
            v-model.trim="form.username"
            autocomplete="username"
            placeholder="请输入管理员账号"
            ><template #prefix><AppIcon name="User" /></template></el-input
        ></el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          ><el-input
            v-model="form.password"
            type="password"
            autocomplete="current-password"
            show-password
            placeholder="请输入密码"
            ><template #prefix><AppIcon name="Lock" /></template></el-input
        ></el-form-item>
        <el-button
          class="login-submit"
          type="primary"
          native-type="submit"
          :loading="auth.loading"
          >登录</el-button
        >
      </el-form>
    </section>
  </main>
</template>
