<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { setToken, setSessionAuth } from '@/utils/auth'
import { userInfoStore } from '@/store/UserInfo'

const router = useRouter()
const userInfo = userInfoStore()
const form = ref({
  username: '',
  password: ''
})

const loading = ref(false)

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

const formRef = ref()

const onSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ username: form.value.username, password: form.value.password })
      })
      if (!res.ok) throw new Error('登录失败')
      const ct = res.headers.get('content-type') || ''
      let token = ''
      if (ct.includes('application/json')) {
        const data = await res.json()
        token = data?.token || ''
      } else {
        const text = await res.text()
        if (!/success/i.test(text)) throw new Error(text || '登录失败')
      }
      if (token) {
        setToken(token)
      } else {
        setSessionAuth(true)
      }
      ElMessage.success('登录成功')
      await userInfo.fetchUserInfo(true)
      router.push('/')
    } catch (e: any) {
      ElMessage.error(e?.message || '登录失败')
    } finally {
      loading.value = false
    }
  })
}

const goRegister = () => {
  router.push({ name: 'register' })
}
</script>

<template>
  <div class="auth-page">
    <h1 style="color: white;text-align: center;">探索F1方程式世界</h1>
    <el-card class="auth-card">
      <h2 class="title">用户登录</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="onSubmit">登录</el-button>
          <el-button type="text" @click="goRegister">没有账号？去注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  </template>

<style scoped>
.auth-page {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;  /*calc(100vh - 90px);*/
  background-image: url('@/assets/rb.jpg');
  background-size: cover;
}
.auth-card {
  width: 420px;
  border-radius: 10px;
}
.title {
  margin: 0 0 20px;
  text-align: center;
}
</style>
