<template>
  <div class="login-container">
    <div class="login-card">
      <h1>⚡ 工时管理系统</h1>
      <p class="subtitle">跨部门工时管理与项目协同平台</p>
      <el-form :model="form" :rules="rules" ref="formRef" @keyup.enter="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" prefix-icon="User" size="large" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password prefix-icon="Lock" size="large" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" :loading="loading" @click="handleLogin" style="width: 100%; height: 48px; font-size: 16px; border-radius: 10px;">
            登 录
          </el-button>
        </el-form-item>
      </el-form>
      <div style="text-align: center; color: var(--text-muted); font-size: 12px; margin-top: 16px;">
        默认管理员账号: admin / admin123
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { authApi } from '../api'
import { useUserStore } from '../stores/user'
import { getHomeRoute } from '../router'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)
const loading = ref(false)

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

async function handleLogin() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  loading.value = true
  try {
    const res = await authApi.login(form)
    userStore.setLogin(res.data.token, res.data.user)
    ElMessage.success(`欢迎回来，${res.data.user.realname}`)
    router.push(getHomeRoute(res.data.user.role))
  } catch (e) {
    // error handled by interceptor
  } finally {
    loading.value = false
  }
}
</script>
