<template>
  <main class="login-page">
    <section class="login-box">
      <header class="login-head">
        <span class="login-mark"><img src="/brand/huiyu-logo.png" alt="" /></span>
        <div>
          <p>慧遇书院</p>
          <h1>证书管理后台</h1>
        </div>
      </header>
      <p class="login-copy">请使用管理员账号登录</p>
      <el-form label-position="top" size="large">
        <el-form-item label="账号">
          <el-input v-model.trim="form.username" placeholder="请输入账号">
            <template #prefix><el-icon><User /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" show-password placeholder="请输入密码" @keyup.enter="login">
            <template #prefix><el-icon><Lock /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-button type="primary" :icon="Right" class="submit" :loading="loading" @click="login">登录后台</el-button>
      </el-form>
      <el-alert v-if="message" class="message" :title="message" type="error" :closable="false" />
    </section>
  </main>
</template>

<script setup lang="ts">
import { Lock, Right, User } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";

import { http } from "../api";

const router = useRouter();
const loading = ref(false);
const message = ref("");
const form = reactive({
  username: "",
  password: "",
});

async function login() {
  loading.value = true;
  message.value = "";
  try {
    const { data } = await http.post("/admin/auth/login", form);
    localStorage.setItem("admin_token", data.access_token);
    await router.push("/admin");
  } catch (error: any) {
    message.value = error?.response?.data?.detail || "登录失败，请重试";
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: grid;
  place-items: center;
  background: #f1f4f5;
  padding: 24px;
}

.login-box {
  width: min(440px, 100%);
  padding: 34px;
  border: 1px solid #dbe2e5;
  border-top: 3px solid #b28a43;
  border-radius: 7px;
  background: #ffffff;
  box-shadow: 0 18px 48px rgba(31, 47, 57, 0.1);
}

.login-head {
  display: flex;
  align-items: center;
  gap: 13px;
}

.login-mark {
  width: 42px;
  height: 42px;
  display: grid;
  place-items: center;
}

.login-mark img {
  width: 40px;
  height: 35px;
  object-fit: contain;
}

.login-head p,
.login-head h1 {
  margin: 0;
}

.login-head p {
  color: #9a7637;
  font-size: 12px;
  font-weight: 700;
}

.login-head h1 {
  margin-top: 2px;
  color: #17212b;
  font-size: 23px;
  font-weight: 750;
}

.login-copy {
  margin: 22px 0 18px;
  padding-bottom: 16px;
  border-bottom: 1px solid #edf1f2;
  color: #6b7982;
  font-size: 13px;
}

.submit {
  width: 100%;
  height: 42px;
  margin-top: 4px;
  font-weight: 700;
}

.message {
  margin-top: 16px;
}
</style>
