<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <img src="../assets/logo.png" alt="logo" class="login-logo">
          <h2>管理员登录</h2>
        </div>
      </template>
      
      <el-form 
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="100px"
        @keyup.enter="handleLogin">
        
        <el-form-item label="管理员账号" prop="username">
          <el-input 
            v-model="loginForm.username"
            placeholder="请输入管理员账号"
            :prefix-icon="User"
            clearable />
        </el-form-item>

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

        <el-button 
          type="primary" 
          class="login-button"
          :loading="loading"
          @click="handleLogin">
          登录
        </el-button>
        <div class="guest-login">
          <el-button 
            type="info" 
            link
            @click="handleGuestLogin">
            游客登录>>
          </el-button>
          <el-divider direction="vertical" />
          <el-button 
            type="primary" 
            link
            @click="handleRegister">
            注册账号
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { UserAPI } from '../api/user'
import { UserMask } from '@/utils/permission'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = ref({
  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, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 游客登录处理
const handleGuestLogin = () => {
  localStorage.setItem('isAuthenticated', 'true')
  localStorage.setItem('userRole', 'guest')
  router.push('/dashboard')
  ElMessage.success('游客登录成功')
}

// 管理员登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await UserAPI.login(loginForm.value)
        if (response.retcode === 0) {
          localStorage.setItem('token', JSON.stringify(response.data))
          localStorage.setItem('isAuthenticated', 'true')
          localStorage.setItem('userRole', 'admin')

          // 获取用户信息
          const userInfoResponse = await UserAPI.getUserInfo()
          if (userInfoResponse.retcode === 0) {
            localStorage.setItem('userInfo', JSON.stringify(userInfoResponse.data))
            
            // 根据用户权限决定跳转页面
            if (userInfoResponse.data.mask >= UserMask.Admin) {
              router.push('/admin/dashboard')  // 管理员及以上跳转到概览页
            } else {
              router.push('/admin/events')     // 普通用户跳转到事件记录页
            }
            
            ElMessage.success('登录成功')
          }
        } else {
          ElMessage.error(response.message || '登录失败')
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 添加注册处理函数
const handleRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
  background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"%3E%3Cpath fill="%230099ff" fill-opacity="0.1" d="M0,160L48,144C96,128,192,96,288,106.7C384,117,480,171,576,165.3C672,160,768,96,864,90.7C960,85,1056,139,1152,144C1248,149,1344,107,1392,85.3L1440,64L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"%3E%3C/path%3E%3C/svg%3E');
  background-repeat: no-repeat;
  background-position: bottom;
  background-size: cover;
}

.login-card {
  width: 480px;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

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

.login-logo {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
}

.login-button {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-group__append) {
  padding: 0;
  width: 120px;
}

:deep(.el-input-group__append button) {
  border: none;
  height: 100%;
  padding: 0;
  width: 100%;
  font-size: 13px;
}

.code-button {
  white-space: nowrap;
}

.guest-login {
  text-align: center;
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.form-footer {
  padding: 0 0 0 100px;  /* 左内边距与label宽度相同 */
  margin-top: 20px;
}
</style> 