<template>
  <div class="page">
    <el-card class="card">
      <h2 class="title">注册账号</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="3-32位字符" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="显示名称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="用于验证和找回密码" />
        </el-form-item>
        <el-form-item label="邮箱验证码" prop="emailCode">
          <div class="code-row">
            <el-input v-model="form.emailCode" placeholder="6位验证码" style="flex:1" />
            <el-button :loading="codeSending" :disabled="countdown > 0"
              @click="sendCode">
              {{ countdown > 0 ? `${countdown}s 后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="手机号（选填）">
          <el-input v-model="form.phone" placeholder="选填" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" style="width:100%" @click="handleRegister">
            注 册
          </el-button>
        </el-form-item>
      </el-form>
      <div class="link">
        已有账号？<router-link to="/login">立即登录</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { authApi } from '@/api/auth'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const codeSending = ref(false)
const countdown = ref(0)

const form = reactive({
  username: '', nickname: '', email: '',
  emailCode: '', password: '', confirmPassword: '', phone: '',
})

const rules: FormRules = {
  username: [{ required: true, min: 3, max: 32, message: '用户名3-32位', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [{ required: true, type: 'email', message: '请输入正确邮箱', trigger: 'blur' }],
  emailCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [{ required: true, min: 6, message: '密码至少6位', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule: unknown, value: string, callback: (e?: Error) => void) => {
        if (value !== form.password) callback(new Error('两次密码不一致'))
        else callback()
      },
    },
  ],
}

async function sendCode() {
  if (!form.email) { ElMessage.warning('请先填写邮箱'); return }
  codeSending.value = true
  try {
    await authApi.sendEmailCode(form.email, 'REGISTER')
    ElMessage.success('验证码已发送')
    countdown.value = 60
    const timer = setInterval(() => {
      if (--countdown.value <= 0) clearInterval(timer)
    }, 1000)
  } finally {
    codeSending.value = false
  }
}

async function handleRegister() {
  await formRef.value?.validate()
  loading.value = true
  try {
    await authApi.register({
      username: form.username, password: form.password,
      email: form.email, nickname: form.nickname,
      phone: form.phone || undefined, emailCode: form.emailCode,
    })
    ElMessage.success('注册成功，请登录')
    router.push('/login')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.page { min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #f0f2f5; }
.card { width: 480px; }
.title { text-align: center; margin-bottom: 20px; }
.code-row { display: flex; gap: 8px; width: 100%; }
.link { text-align: center; font-size: 14px; }
</style>
