<template>
  <!-- 注册表单容器 -->
  <div class="form-container">
    <h2>注册</h2>

    <!-- 注册方式选择器(用户名/邮箱/手机) -->
    <div class="register-type">
      <span
        v-for="type in registerTypes"
        :key="type.value"
        :class="{ active: currentType === type.value }"
        @click="currentType = type.value">
        {{ type.label }}
      </span>
    </div>

    <!-- 注册表单,阻止默认提交行为 -->
    <form @submit.prevent="register" class="register-form">
      <!-- 输入框组 -->
      <div class="input-group">

        <!-- 动态输入框(根据注册方式显示相应的输入框) -->
        <input
          :type="inputType"
          v-model="registerForm[currentType]"
          :placeholder="placeholder"
          required />

        <!-- 验证码部分(邮箱/手机注册时显示) -->
        <template v-if="showVerifyCode">
          <div class="verify-code">
            <!-- 验证码输入框 -->
            <input
              type="text"
              v-model="registerForm.verifyCode"
              placeholder="验证码"
              required />
            <!-- 发送验证码按钮(带倒计时功能) -->
            <button
              type="button"
              @click="sendCode"
              :disabled="cooldown > 0 || !isValidInput">
              {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
            </button>
          </div>
        </template>

        <!-- 密码输入区域 -->
        <div class="password-group">
          <!-- 密码输入框 -->
          <input
            type="password"
            v-model="registerForm.password"
            placeholder="密码"
            required />
          <!-- 确认密码输入框 -->
          <input
            type="password"
            v-model="registerForm.confirmPassword"
            placeholder="确认密码"
            required />
        </div>

        <!-- 图形验证码区域 -->
        <div class="captcha-group">
          <!-- 图形验证码输入框 -->
          <input
            type="text"
            v-model="registerForm.captcha"
            placeholder="图形验证码"
            required />
          <!-- 验证码图片(点击刷新) -->
          <img
            :src="captchaUrl"
            @click="refreshCaptcha"
            alt="验证码"
            class="captcha-img" />
        </div>
      </div>

      <!-- 注册按钮 -->
      <button type="submit">注册</button>
    </form>

    <!-- 切换到登录表单的链接 -->
    <p class="switch-form">
      已有账号？
      <button @click="$emit('toggleForm')" class="link-button">登录</button>
    </p>
  </div>
</template>

<script setup lang="js" name="UserRegister">
import { ref, computed, onMounted } from 'vue';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['toggleForm']);

const currentType = ref('username');
const cooldown = ref(0); // 验证码倒计时

// 注册方式选项配置
const registerTypes = [
  { label: '用户名注册', value: 'username' },
  { label: '邮箱注册', value: 'email' },
  { label: '手机注册', value: 'phone' }
];

// 注册表单数据对象
const registerForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  verifyCode: '', // 验证码(邮箱/手机)
  captcha: '' // 图形验证码
});

// 前端验证格式
const isValidInput = computed(() => {
  const value = registerForm.value[currentType.value];
  if (!value) return false;
  switch (currentType.value) {
    case 'email':
      return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
    case 'phone':
      return /^1[3-9]\d{9}$/.test(value);
    default:
      return false;
  }
});

// 图形验证码URL
const captchaUrl = ref('/user/captcha');

// 输入框类型
const inputType = computed(() => {
  switch (currentType.value) {
    case 'email': return 'email';
    case 'phone': return 'tel';
    default: return 'text';
  }
});

// 输入框文本
const placeholder = computed(() => {
  switch (currentType.value) {
    case 'email': return '请输入邮箱';
    case 'phone': return '请输入手机号';
    default: return '请输入用户名';
  }
});

// 邮箱/手机注册时显示验证码输入框
const showVerifyCode = computed(() => {
  return ['email', 'phone'].includes(currentType.value);
});

// 发送验证码方法（邮箱/手机注册时使用）
async function sendCode() {
  if (cooldown.value > 0 || !isValidInput.value) return;
  try {
    // TODO：发送验证码请求
    const response = await request.post(`/user/send-code`, {
      type: currentType.value,
      target: registerForm.value[currentType.value]
    });

    if (response.success) {
      ElMessage({
        message: '验证码已发送',
        type: 'info'
      });

      // 开始60秒倒计时
      cooldown.value = 60;
      const timer = setInterval(() => {
        cooldown.value--;
        if (cooldown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    }
  } catch (error) {
    console.error('发送验证码失败:', error);
    alert('发送验证码失败，请稍后重试');
  }
}

// 刷新图形验证码
function refreshCaptcha() {
  // 添加时间戳防止缓存
  captchaUrl.value = `/user/captcha?t=${new Date().getTime()}`;
}

// 注册
async function register() {
  try {
    // 校验图形验证码
    const captchaResponse = await request.post('/user/verify-captcha', {
      captcha: registerForm.value.captcha
    });

    if (captchaResponse.code !== 200) {
      ElMessage({
        message: captchaResponse.msg,
        type: 'error',
        duration: 500
      });
      refreshCaptcha();
      return;
    }

    // 密码确认校验
    if (registerForm.value.password !== registerForm.value.confirmPassword) {
      ElMessage({
        message: '两次输入的密码不一致',
        type: 'error',
        duration: 500
      });
      return;
    }

    // 构建注册数据
    const registerData = {
      username: registerForm.value.username,
      password: registerForm.value.password
    };

    // 根据注册类型添加对应字段
    switch (currentType.value) {
      case 'email':
        registerData.email = registerForm.value.email;
        break;
      case 'phone':
        registerData.phone = registerForm.value.phone;
        break;
    }

    const response = await request.post('/user/register', registerData);

    if (response.code === 200) {
      ElMessage({
        message: '注册成功',
        type: 'success',
        duration: 500
      });
      // 触发切换到登录表单
      emit('toggleForm');
    } else {
      ElMessage({
        message: '注册失败，请稍后重试',
        type: 'error',
        duration: 500
      });
    }
  }
  catch (error) {
    console.error('注册失败:', error);
    alert(error.response?.message || '注册失败，请稍后重试');
    refreshCaptcha();
  }
}

onMounted(() => {
  // 初始化图形验证码
  refreshCaptcha();
});
</script>

<style scoped>
/* 注册表单容器样式 - 为整个注册表单提供白色背景和阴影效果 */
.form-container {
  background: rgba(255, 255, 255, 0.90);
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
  margin: auto;
}

/* 注册方式切换栏样式 - 包含用户名/邮箱/手机注册选项 */
.register-type {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

/* 注册方式选项样式 - 每个注册方式的基本样式 */
.register-type span {
  font-size: 14px;
  padding: 6px 12px;
  cursor: pointer;
  position: relative;
  color: #666;
}

/* 当前选中的注册方式样式 - 突出显示当前选中的注册方式 */
.register-type span.active {
  color: #6FBD87;
  background: #f5f5f5;
}

/* 当前选中注册方式的下划线样式 - 为选中项添加绿色下划线 */
.register-type span.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #6FBD87;
}

/* 输入框组样式 - 包含所有输入框的容器 */
.input-group {
  margin-bottom: 20px;
}

/* 通用输入框样式 - 适用于用户名/邮箱/手机号/密码输入框 */
input {
  width: 93%;
  padding: 11px;
  margin: 8px 0;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

/* 输入框获得焦点时的样式 - 突出显示当前正在输入的框 */
input:focus {
  border-color: #6FBD87;
  outline: none;
}

/* 验证码输入区域样式 - 包含验证码输入框和获取验证码按钮 */
.verify-code {
  display: flex;
  gap: 10px;
}

/* 验证码输入框样式 */
.verify-code input {
  flex: 1;
}

/* 获取验证码按钮样式 */
.verify-code button {
  width: 88px;
  height: 40px;
  margin: 8px 0;
  font-size: 12px;
}

/* 密码输入区域样式 - 包含密码和确认密码输入框 */
.password-group {
  display: flex;
  flex-direction: column;
}

/* 图形验证码区域样式 - 包含验证码输入框和验证码图片 */
.captcha-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 图形验证码图片样式 */
.captcha-img {
  width: 180px;
  height: 30px;
  border-radius: 4px;
  cursor: pointer;
}

/* 注册按钮样式 */
button {
  width: 93%;
  padding: 10px;
  background: #6FBD87;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s;
}

/* 注册按钮悬停效果 */
button:hover {
  background: #5aa76f;
}

/* 禁用状态的按钮样式（用于验证码倒计时） */
button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 切换到登录的提示文字样式 */
.switch-form {
  margin-top: 20px;
  text-align: center;
  color: #666;
}

/* 切换到登录的链接按钮样式 */
.link-button {
  background: none;
  border: none;
  color: #6FBD87;
  text-decoration: underline;
  padding: 0 2px;
  width: auto;
  font-size: inherit;
}

/* 切换到登录的链接按钮悬停效果 */
.link-button:hover {
  color: #5aa76f;
  background: none;
}
</style>