<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>登录 - Novalon 管理系统</h2>
      </template>
      <el-form
        :model="formState"
        label-position="top"
        @submit.prevent="onFinish"
      >
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
        >
          <el-input
            v-model="formState.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input
            v-model="formState.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { onMounted } from 'vue'

const router = useRouter()
const loading = ref(false)

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

onMounted(() => {
  document.title = '登录 - Novalon 管理系统'
})

const onFinish = async () => {
  loading.value = true
  try {
    const res: any = await request.post('/auth/login', formState)
    if (res.code === 401) {
      ElMessage.error(res.message || '登录失败')
      return
    }
    localStorage.setItem('token', res.token)
    localStorage.setItem('userId', res.userId)
    localStorage.setItem('username', res.username)
    ElMessage.success('登录成功')
    
    await router.push('/')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="css">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: var(--el-color-primary-light-9);

  .login-card {
    width: 400px;
  }
}
</style>
