<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import api from '../api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

const form = ref({
  username: 'admin',
  password: ''
})

const loading = ref(false)

const handleLogin = async () => {
  loading.value = true
  try {
    const formData = new FormData()
    formData.append('username', form.value.username)
    formData.append('password', form.value.password)
    
    const res = await api.post('/login', formData)
    authStore.setToken(res.data.access_token, form.value.username)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    ElMessage.error('登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-card class="login-card">
    <template #header>
      <div class="card-header">
        <span>AI 值班平台登录</span>
      </div>
    </template>
    <el-form :model="form" label-width="0px">
      <el-form-item>
        <el-input v-model="form.username" placeholder="用户名" prefix-icon="User" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="form.password" type="password" placeholder="密码" prefix-icon="Lock" show-password @keyup.enter="handleLogin" />
      </el-form-item>
      <el-button type="primary" :loading="loading" style="width: 100%;" @click="handleLogin">登录</el-button>
    </el-form>
  </el-card>
</template>

<style scoped>
.login-card {
  width: 400px;
}
.card-header {
  text-align: center;
  font-weight: bold;
}
</style>

