<template>
  <section class="auth-page page">
    <div class="auth-panel panel">
      <div class="panel-header">
        <h1 class="panel-title">登录 EasyCode</h1>
      </div>
      <el-form :model="form" label-position="top" class="auth-form">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-button type="primary" :loading="loading" @click="handleLogin">登录</el-button>
        <el-button text @click="router.push('/register')">没有账号？去注册</el-button>
      </el-form>
    </div>
  </section>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/auth'
import { setToken, setUser } from '@/utils/auth'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const form = reactive({
  username: '',
  password: ''
})

function pickPayload(result) {
  return result?.data || result || {}
}

async function handleLogin() {
  if (!form.username || !form.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    const result = await login(form)
    const payload = pickPayload(result)
    const token = payload.token || payload.access_token

    if (!token) {
      throw new Error('登录成功但未返回 token')
    }

    setToken(token)
    setUser(payload.user || { userName: form.username })
    ElMessage.success('登录成功')
    router.push(route.query.redirect || '/generate')
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.auth-page {
  display: grid;
  place-items: start center;
}

.auth-panel {
  width: min(440px, 100%);
}

.auth-form {
  display: grid;
  gap: 4px;
  padding: 22px;
}
</style>
