<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">后台管理系统</h2>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            clearable
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../store/auth'

// 表单引用
const loginFormRef = ref()

// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: 'Admin',
  password: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 路由实例
const router = useRouter()

// 认证状态管理
const authStore = useAuthStore()

// 处理键盘按键事件
const handleKeyPress = (event) => {
  if (event.key === 'Enter') {
    handleLogin()
  }
}

// 登录处理
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 调用登录方法
    const success = authStore.login(loginForm.username, loginForm.password)
    
    if (success) {
      // 登录成功，跳转到首页
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      // 登录失败，显示错误消息
      ElMessage.error('用户名或密码错误')
    }
  } catch (error) {
    // 表单验证失败
    console.error('login form validate error:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时添加键盘监听
onMounted(() => {
  // 自动回填：如果曾经成功登录过，直接从 localStorage 取出密码
  const rememberedPassword = localStorage.getItem('rememberedPassword')
  if (rememberedPassword) {
    loginForm.password = rememberedPassword
  }
  window.addEventListener('keypress', handleKeyPress)
})

// 组件卸载时移除键盘监听
onUnmounted(() => {
  window.removeEventListener('keypress', handleKeyPress)
})
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--background-color);
  transition: background-color 0.3s;
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 32px;
  background-color: var(--background-color);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: var(--box-shadow-light);
  transition: all 0.3s;
}

.login-title {
  text-align: center;
  margin-bottom: 24px;
  color: var(--text-color);
}

.login-btn {
  width: 100%;
  margin-top: 16px;
}

.login-footer {
  margin-top: 24px;
  text-align: center;
}

/* 响应式样式 */
@media (max-width: 767px) {
  .login-box {
    margin: 0 6px;
    padding: 10px;
  }
}
</style>
