<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import AuthLayout from "@/layouts/AuthLayout.vue";
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from "element-plus";
import { User, Lock, Iphone, Message } from "@element-plus/icons-vue";
import { userRegister } from "@/apis/user";
import type { RegisterRequest } from "@/types/user";
import type { FormRules } from "element-plus";

// 表单数据
const registerForm = ref<RegisterRequest>({
  username: "",
  password: "",
  phone: "",
  email: "",
});

// 表单验证规则
const rules = ref<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度应在3-20个字符之间",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应在6-20个字符之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
});

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

// 处理注册
const handleRegister = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    loading.value = true;
    try {
      const response = await userRegister(registerForm.value);
      console.log("注册响应数据:", response);

      if (response.code === 200) {
        ElMessage.success("注册成功");
        // 注册成功后跳转到登录页面
        router.push("/user/login");
      } else {
        ElMessage.error(response.message || "注册失败");
      }
    } catch (_err: unknown) {
      // 错误处理，显示更具体的错误信息
      if (_err instanceof Error) {
        ElMessage.error(_err.message || "注册请求失败，请稍后再试");
      } else {
        ElMessage.error("注册请求失败，请稍后再试");
      }
    } finally {
      loading.value = false;
    }
  });
};

// 跳转到登录页面
const goToLogin = () => {
  router.push("/user/login");
};
</script>

<template>
  <AuthLayout>
    <div class="auth-form">
      <div class="text-center mb-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-2">用户注册</h2>
        <p class="text-gray-600">欢迎加入我们，请填写以下信息完成注册</p>
      </div>

      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        label-position="top"
        @keyup.enter="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="Iphone"
            size="large"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
            size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            class="w-full"
            size="large"
            :loading="loading"
            @click="handleRegister"
          >
            {{ loading ? "注册中..." : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="text-center mt-6">
        <p class="text-gray-600">
          已有账户？
          <el-button type="text" @click="goToLogin">立即登录</el-button>
        </p>
      </div>
    </div>
  </AuthLayout>
</template>

<style scoped>
.auth-form {
  width: 100%;
  max-width: 350px;
  margin: 0 auto;
}
</style>
