<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import AuthLayout from "@/layouts/AuthLayout.vue";
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { userLogin } from "@/apis/user";
import { useUserStore } from "@/stores/UserStore";
import type { LoginRequest } from "@/types/user";
import type { FormRules } from "element-plus";

// 表单数据
const loginForm = ref<LoginRequest>({
  username: "",
  password: "",
});

// 表单验证规则
const rules = ref<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度应在3-20个字符之间",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应在6-20个字符之间", trigger: "blur" },
  ],
});

const formRef = ref();
const loading = ref(false);
const router = useRouter();
const userStore = useUserStore();

// 处理登录
const handleLogin = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    loading.value = true;
    try {
      const response = await userLogin(loginForm.value);
      console.log("登录响应数据:", response);

      if (response.code === 200) {
        // 保存 token 和用户信息到 store
        userStore.setToken(response.data.token);
        userStore.setUserInfo({
          id: response.data.id,
          username: response.data.username,
          nickname: response.data.nickname,
          isAdmin: response.data.isAdmin,
        });

        ElMessage.success("登录成功");
        // 跳转到首页
        router.push("/");
      } else {
        ElMessage.error(response.message || "登录失败");
      }
    } catch (_err: unknown) {
      // 错误处理，显示更具体的错误信息
      if (_err instanceof Error) {
        ElMessage.error(_err.message || "登录请求失败，请稍后再试");
      } else {
        ElMessage.error("登录请求失败，请稍后再试");
      }
    } finally {
      loading.value = false;
    }
  });
};

// 跳转到注册页面
const goToRegister = () => {
  router.push("/user/register");
};

// 忘记密码功能（占位）
const handleForgetPassword = () => {
  ElMessage.info("忘记密码功能开发中");
};
</script>

<template>
  <AuthLayout>
    <div class="auth-form">
      <div class="text-center mb-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-2">用户登录</h2>
        <p class="text-gray-600">欢迎回来，请登录您的账户</p>
      </div>

      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        label-position="top"
        @keyup.enter="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <div class="flex justify-end mb-4">
          <el-button type="text" @click="handleForgetPassword">
            忘记密码？
          </el-button>
        </div>

        <el-form-item>
          <el-button
            type="primary"
            class="w-full"
            size="large"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? "登录中..." : "登录" }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="text-center mt-6">
        <p class="text-gray-600">
          还没有账户？
          <el-button type="text" @click="goToRegister">立即注册</el-button>
        </p>
      </div>
    </div>
  </AuthLayout>
</template>

<style scoped>
.auth-form {
  width: 100%;
  max-width: 350px;
  margin: 0 auto;
}
</style>
