<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>系统登录</span>
        </div>
      </template>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item label="用户名" prop="identifier">
          <el-input v-model="loginForm.identifier" placeholder="请输入用户名/邮箱/手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import apiClient from '../../api';

export default {
  name: 'LoginForm',
  setup() {
    const router = useRouter();
    const loginFormRef = ref(null);
    const loading = ref(false);

    const loginForm = reactive({
      identifier: '',
      password: '',
    });

    const loginRules = reactive({
      identifier: [
        { required: true, message: '请输入用户名/邮箱/手机号', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
      ],
    });

    const handleLogin = async () => {
      if (!loginFormRef.value) return;
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            const response = await apiClient.users.login(loginForm);
            if (response.code === 2000 && response.data && response.data.token) {
              localStorage.setItem('jwt_token', response.data.token);
              localStorage.setItem('username', response.data.username); // 存储用户名
              ElMessage.success('登录成功！');
              router.push('/'); // 登录成功后跳转到首页
            } else {
              ElMessage.error(response.message || '登录失败，请检查用户名或密码！');
            }
          } catch (error) {
            console.error('登录请求失败:', error);
            ElMessage.error('登录请求失败，请稍后再试！');
          } finally {
            loading.value = false;
          }
        }
      });
    };

    return {
      loginFormRef,
      loginForm,
      loginRules,
      loading,
      handleLogin,
    };
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
  max-width: 90%;
}

.card-header {
  text-align: center;
  font-size: 1.2em;
  font-weight: bold;
}

.login-form {
  padding: 20px;
}
</style>
