<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { login } from '../api/user'
import { clearStorage } from '../utils/clearStorage'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

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

// 登录表单验证规则
const loginRules = {
  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 loginFormRef = ref(null)
const loading = ref(false)

// 登录方法
const handleLogin = () => {
  // 清理本地存储
  clearStorage()

  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用登录API
        const res = await login(loginForm)
        if (res.code === 200) {
          const userData = res.data

          // 存储用户信息到状态管理
          userStore.login(userData)

          // 存储token和相关信息已经在userStore.login中完成
          // 这里不需要重复存储

          // 打印登录成功信息
          console.log('登录成功，完整响应数据:', res)
          console.log('登录成功，用户数据:', userData)
          console.log('登录成功，用户信息:', userData.user)
          console.log('是否为管理员:', userData.user.role === 1)

          // 检查本地存储的token
          setTimeout(() => {
            console.log('登录后的本地存储:', {
              token: localStorage.getItem('token'),
              tokenName: localStorage.getItem('tokenName'),
              tokenPrefix: localStorage.getItem('tokenPrefix'),
              isAdmin: localStorage.getItem('isAdmin'),
              user: localStorage.getItem('user')
            })
          }, 100)

          ElMessage.success(res.msg || '登录成功')

          // 如果是管理员，跳转到后台管理页面
          if (userData.user.role === 1) {
            router.push('/admin')
          } else {
            // 如果有重定向地址，则跳转到重定向地址
            const redirect = route.query.redirect || '/'
            router.push(redirect)
          }
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-actions">
        <el-button text @click="goToRegister">没有账号？立即注册</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 140px);
  padding: 20px;
  background-color: transparent;
}

.login-box {
  width: 450px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(255, 107, 129, 0.15);
  transition: all 0.3s ease;
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 25px rgba(255, 107, 129, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 35px;
}

.login-header h2 {
  margin: 0;
  color: #ff6b81;
  font-size: 1.8rem;
  font-weight: 600;
}

.login-form {
  margin-bottom: 25px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 20px;
  padding: 0 15px;
}

.login-form :deep(.el-input__inner) {
  padding: 0 5px;
}

.login-button {
  width: 100%;
  background-color: #ffb6c1;
  border: none;
  border-radius: 20px;
  height: 45px;
  font-size: 1rem;
  transition: all 0.3s;
}

.login-button:hover {
  background-color: #ff8a9b;
  transform: scale(1.02);
}

.login-actions {
  display: flex;
  justify-content: center;
}

.login-actions .el-button {
  color: #ff6b81;
  font-weight: 500;
}

.login-actions .el-button:hover {
  color: #ff4757;
}
</style>
