<template>
  <section class="login-page">
    <h1>登录</h1>
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="rules"
      label-position="top"
      class="login-form"
    >
      <el-form-item label="用户名" prop="email">
        <el-input v-model="loginForm.email" placeholder="请输入用户名"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm()">登录</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuth } from '../stores/useAuth';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus'


interface LoginForm {
  email: string;
  password: string;
}

const auth = useAuth();
const router = useRouter();
const loginForm = ref<LoginForm>({
  email: '',
  password: ''
});
const loginFormRef = ref<FormInstance>();

const rules: FormRules = {
  email: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 3, max: 20, message: '用户名长度 3~20 个字符', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, message: '密码至少 6 位', trigger: 'change' }
  ]
};

const submitForm = () => {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      return;
    }

    auth.login(loginForm.value).then((res) => {
      loginSuccess()
    }).catch(res => loginFail(res));
  });
};

const loginSuccess = () => {
  router.push({ path: "/" });
};

const loginFail = (res: any) => {
  ElMessage.error(`${res?.message || '登录失败，请重试'}`);
};
</script>

<style scoped>
.login-page {
  max-width: 420px;
  margin: 0 auto;
}
.login-form {
  background: #ffffff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 12px 30px rgba(62, 94, 148, 0.08);
}
.el-form-item {
  margin-bottom: 18px;
}
.error-alert {
  margin-top: 16px;
}
</style>
