<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 { ElMessageBox } from 'element-plus' // 引入 ElMessageBox
import { User, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
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 {
        // 执行登录请求
        const success = await userStore.handleLogin(loginForm)

        if (success) {
          // 成功：跳转
          router.push('/dashboard')
        } else {
          // 失败（业务逻辑拒绝，如账号密码错）：弹出模态框
          showLoginFailAlert('用户名或密码错误')
        }
      } catch (error: any) {
        // 失败（系统错误，如网络断开/500报错）：弹出模态框
        // 优先取后端的报错信息，没有则显示默认
        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>