<template>
  <main class="login-page">
    <section class="login-box">
      <h1>后台登录</h1>
      <el-form label-position="top">
        <el-form-item label="账号">
          <el-input v-model.trim="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" show-password @keyup.enter="login" />
        </el-form-item>
        <el-button type="primary" 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 { 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: linear-gradient(180deg, #f7fafb 0%, #eef4f6 100%);
  padding: 24px;
}

.login-box {
  width: min(440px, 100%);
  padding: 32px;
  border: 1px solid #dbe6ea;
  border-radius: 14px;
  background: #ffffff;
  box-shadow: 0 18px 48px rgba(42, 64, 78, 0.09);
}

h1 {
  margin: 0 0 22px;
  color: #172033;
  font-size: 26px;
  font-weight: 800;
}

.submit {
  width: 100%;
  height: 38px;
  font-weight: 700;
}

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