<script setup>
import { Lock, User } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { apiPost } from "../api/http";
import { setSession } from "../auth/session";

const router = useRouter();
const loading = ref(false);
const formState = reactive({
  username: "admin",
  password: "admin123456",
});

async function submitLogin() {
  if (!formState.username.trim() || !formState.password.trim()) {
    ElMessage.warning("请输入用户名和密码");
    return;
  }

  loading.value = true;
  try {
    const data = await apiPost("/api/auth/login", {
      username: formState.username.trim(),
      password: formState.password,
    });
    setSession(data.token, data.user);
    ElMessage.success("登录成功");
    router.replace("/");
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : "登录失败");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="login-page">
    <div class="login-page__backdrop"></div>
    <el-card class="login-card" shadow="never">
      <div class="login-card__meta">
        <span class="login-card__eyebrow">QUALITY INSPECTION</span>
        <h1>登录质量检测平台</h1>
        <p>资源按创建人隔离，超管可查看全量数据。</p>
      </div>

      <el-form label-position="top" @submit.prevent="submitLogin">
        <el-form-item label="用户名">
          <el-input v-model="formState.username" :prefix-icon="User" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="formState.password"
            :prefix-icon="Lock"
            type="password"
            show-password
            placeholder="请输入密码"
            @keyup.enter="submitLogin"
          />
        </el-form-item>
        <el-button type="primary" class="login-card__submit" :loading="loading" @click="submitLogin">
          登录
        </el-button>
      </el-form>

      <div class="login-card__hint">
        <span>默认超管账号：admin</span>
        <span>默认密码：admin123456</span>
      </div>
    </el-card>
  </div>
</template>
