<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>🚀 设备监控系统登录</h2>
      <el-form :model="loginForm" @keyup.enter="handleLogin">
        <el-form-item>
          <el-input
              v-model="loginForm.username"
              placeholder="用户名"
              prefix-icon="User"
          />
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>
        <el-button type="primary" :loading="loading" style="width: 100%" @click="handleLogin">
          登录
        </el-button>
      </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 request from '../utils/request'

const router = useRouter()
const loading = ref(false)
const loginForm = ref({ username: '', password: '' })

const handleLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    return ElMessage.warning('请输入用户名和密码')
  }

  loading.value = true
  try {
    const res = await request.post('/api/login', loginForm.value)
    const data = res.data

    // 兼容部分后端可能不返回 code 的情况，默认为 200
    const code = data.code !== undefined ? data.code : 200

    if (code === 200) {
      if (!data.token) {
        ElMessage.error('登录异常：服务器未返回 Token')
        return
      }

      console.log('登录成功:', data)

      // === 💾 核心修改：保存所有必要信息 ===
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('token', data.token)
      localStorage.setItem('role', data.role || 'client')
      localStorage.setItem('user_id', data.user_id || '')

      // ✅ 关键：保存用户名，Dashboard 才能获取到
      localStorage.setItem('username', data.username || loginForm.value.username)

      ElMessage.success('欢迎回来')
      router.push('/dashboard')
    } else {
      ElMessage.error(data.message || '登录失败')
    }
  } catch (error) {
    console.error(error)
    // request.js 通常会处理网络错误，这里主要处理业务逻辑错误
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #1d2b64 0%, #f8cdda 100%);
}
.login-card {
  width: 400px;
  padding: 40px 20px;
  text-align: center;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
h2 {
  margin-bottom: 30px;
  color: #303133;
}
</style>
