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

      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
          @submit.prevent
      >
        <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
              @keydown.enter.prevent="onLogin"
          />
        </el-form-item>

        <el-button
            type="primary"
            native-type="button"
            :loading="loading"
            class="w-100"
            @click="onLogin"
        >
          立即登录
        </el-button>

      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { usePermissionStore } from '@/stores/permission' // [新增] 引入权限Store
import { ElMessageBox } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const permissionStore = usePermissionStore() // [新增]
const loading = ref(false)
const loginFormRef = ref()

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

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const onLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        // 1. 执行登录请求
        const success = await userStore.handleLogin(loginForm)

        if (success) {
          // [新增] 2. 登录成功后，立即拉取当前用户的权限字典
          // 这样进入 Dashboard 时，所有按钮/列的显示状态就已经确定了
          await permissionStore.loadPermissions()

          // 3. 跳转
          router.push('/dashboard')
        } else {
          // 失败（业务逻辑拒绝）：弹出模态框
          showLoginFailAlert('用户名或密码错误')
        }
      } catch (error: any) {
        // 失败（系统错误）：弹出模态框
        const msg = error.response?.data?.msg || error.message || '登录遇到未知错误'
        showLoginFailAlert(msg)
      } finally {
        loading.value = false
      }
    }
  })
}

// 封装错误弹窗
const showLoginFailAlert = (msg: string) => {
  ElMessageBox.alert(msg, '登录失败', {
    confirmButtonText: '确定',
    type: 'error',
    callback: () => {
      loginForm.password = ''
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #2d3a4b;
}
.login-card {
  width: 400px;
}
.card-header h2 {
  text-align: center;
  margin: 0;
  color: #333;
}
.w-100 {
  width: 100%;
}
</style>