<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>Inventory System</h2>
        </div>
      </template>

      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名 (如: IRIS)"
              :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="onLogin"
          />
        </el-form-item>

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

        <div class="tips">
          <p>默认超级管理员: IRIS / licahk</p>
        </div>
      </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 { ElMessage } from 'element-plus'
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
      const success = await userStore.handleLogin(loginForm)
      loading.value = false
      if (success) {
        ElMessage.success('登录成功')
        router.push('/dashboard') // 登录后跳转首页
      }
    }
  })
}
</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%;
}
.tips {
  margin-top: 15px;
  font-size: 12px;
  color: #999;
  text-align: center;
}
</style>