<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone, Avatar, CircleCheck } from '@element-plus/icons-vue'
import request from '../utils/request'
import { handleAvatarUpload } from '../utils/avatarUtils'
import ParticleBackground from '../components/ParticleBackground.vue'
import { GITCC_LOGO_URL, PRODUCT_TITLE, PRODUCT_TAGLINE } from '../shellConstants'

const router = useRouter()
const username = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const first_name = ref('')
const last_name = ref('')
const avatar_file = ref(null)
const phone = ref('')
const isRegistering = ref(false)
const registerSuccess = ref(false)
const formRef = ref(null)

// 返回登录页面
const goToLogin = () => {
  router.push('/')
}

// 邮箱验证规则
const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

// 确认密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== password.value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 名字验证规则
const validateFirstName = (rule, value, callback) => {
  if (!value) {
    callback() // 名字可以为空
    return
  }
  callback()
}

// 姓氏验证规则
const validateLastName = (rule, value, callback) => {
  if (!value) {
    callback() // 姓氏可以为空
    return
  }
  callback()
}

// 头像文件验证规则
const validateAvatar = (rule, value, callback) => {
  if (!value) {
    callback() // 头像可以为空
    return
  }
  callback()
}

// 手机号验证规则
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback() // 手机号可以为空
    return
  }
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号格式'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: ['blur', 'change'] },
  ],
  first_name: [
    { validator: validateFirstName, trigger: ['blur', 'change'] },
  ],
  last_name: [
    { validator: validateLastName, trigger: ['blur', 'change'] },
  ],
  avatar_file: [
    { validator: validateAvatar, trigger: ['blur', 'change'] },
  ],
  phone: [
    { validator: validatePhone, trigger: ['blur', 'change'] },
  ],
}

// 创建头像预览 URL 的计算属性
const avatarPreviewUrl = computed(() => {
  if (avatar_file.value) {
    return URL.createObjectURL(avatar_file.value)
  }
  return ''
})

const handleAvatarChange = (file) => {
  return handleAvatarUpload(file, (rawFile) => {
    avatar_file.value = rawFile
  })
}

// 注册方法
const handleRegister = async () => {
  if (!formRef.value) {
    ElMessage.error({
      message: '【注册错误】表单实例不存在',
      duration: 5000,
    })
    return
  }

  try {
    await formRef.value.validate()
    isRegistering.value = true

    const formData = new FormData()
    formData.append('username', username.value)
    formData.append('email', email.value)
    formData.append('password', password.value)
    // 只有当这些选填字段有值时才添加到表单数据中
    if (first_name.value) {
      formData.append('first_name', first_name.value)
    }
    if (last_name.value) {
      formData.append('last_name', last_name.value)
    }
    if (avatar_file.value) {
      formData.append('avatar_file', avatar_file.value)
    }
    if (phone.value) {
      formData.append('phone', phone.value)
    }

    // 打印注册表单数据，过滤敏感信息
    const safeFormData = {
      username: username.value,
      email: email.value,
      has_password: password.value ? '已设置' : '未设置',
      has_first_name: first_name.value ? '已设置' : '未设置',
      has_last_name: last_name.value ? '已设置' : '未设置',
      has_avatar: avatar_file.value ? '已设置' : '未设置',
      has_phone: phone.value ? '已设置' : '未设置',
    }
    console.info('【注册表单数据】', safeFormData)

    // 发送注册请求
    const data = await request.post('/user/register', formData)
    console.info('【注册响应数据】', data)
    const operation = data.operation

    // 根据后端操作状态判断注册是否成功
    if (data && operation && operation.status === 'SUCCESS') {
      ElMessage.success({
        message: '【注册成功】',
        duration: 3000,
      })

      // 注册成功后自动跳转到登录页面
      router.push('/login')
    }
    // 注册失败情况已在响应拦截器中处理，这里不再重复
  } catch (error) {
    console.error('【注册错误】', error)
    ElMessage.error({
      message: '【注册错误】' + (error?.message || '请重试'),
      duration: 5000,
    })
  } finally {
    isRegistering.value = false
  }
}
</script>

<template>
  <div class="hud-auth">
    <aside class="hud-auth-brand" aria-labelledby="reg-brand-title">
      <div class="hud-auth-brand-inner">
        <img :src="GITCC_LOGO_URL" :alt="PRODUCT_TITLE" class="brand-logo" width="56" height="56" />
        <h2 id="reg-brand-title">
          创建账号 · <span class="accent">{{ PRODUCT_TITLE }}</span>
        </h2>
        <p class="brand-lead">{{ PRODUCT_TAGLINE }}</p>
        <ul>
          <li>邮箱与用户名用于登录与找回</li>
          <li>头像与手机号为可选项</li>
          <li>提交后由业务后端完成注册校验</li>
        </ul>
      </div>
    </aside>

    <div class="hud-auth-panel">
      <div class="hud-auth-particles" aria-hidden="true">
        <ParticleBackground />
      </div>

      <div class="hud-auth-form-card">
        <div class="form-head">
          <h1 class="form-title">注册账号</h1>
          <p class="form-sub">{{ PRODUCT_TITLE }}</p>
        </div>

        <div v-if="!registerSuccess">
          <el-form
            ref="formRef"
            :model="{ username, email, password, confirmPassword, first_name, last_name, phone, avatar_file }"
            :rules="formRules"
            class="register-form"
            status-icon
            @submit.prevent="handleRegister"
            @keyup.enter="handleRegister"
          >
            <el-form-item prop="avatar_file" class="avatar-upload">
              <el-upload
                class="avatar-uploader"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                accept="image/png, image/jpg, image/jpeg"
                :on-change="handleAvatarChange"
                :auto-upload="false"
                :show-file-list="false"
              >
                <img v-if="avatarPreviewUrl" :src="avatarPreviewUrl" class="avatar-preview" />
                <div v-else class="avatar-placeholder">
                  <el-icon class="avatar-icon">
                    <Avatar />
                  </el-icon>
                  <span>点击上传</span>
                </div>
              </el-upload>
            </el-form-item>

            <el-form-item prop="username">
              <el-input v-model="username" placeholder="用户名" :prefix-icon="User" />
            </el-form-item>

            <el-form-item prop="email">
              <el-input v-model="email" placeholder="邮箱" :prefix-icon="Message" />
            </el-form-item>

            <div class="password-group">
              <el-form-item prop="password" class="password-item">
                <el-input v-model="password" type="password" placeholder="密码" :prefix-icon="Lock" show-password />
              </el-form-item>
              <el-form-item prop="confirmPassword" class="password-item">
                <el-input
                  v-model="confirmPassword"
                  type="password"
                  placeholder="确认密码"
                  :prefix-icon="Lock"
                  show-password
                />
              </el-form-item>
            </div>

            <div class="name-group">
              <el-form-item prop="last_name" class="name-item">
                <el-input v-model="last_name" placeholder="姓氏（可选）" :prefix-icon="User" />
              </el-form-item>
              <el-form-item prop="first_name" class="name-item">
                <el-input v-model="first_name" placeholder="名字（可选）" :prefix-icon="User" />
              </el-form-item>
            </div>

            <el-form-item prop="phone">
              <el-input v-model="phone" placeholder="手机号（可选）" :prefix-icon="Phone" />
            </el-form-item>

            <el-button type="primary" :loading="isRegistering" class="submit-btn" @click="handleRegister">
              {{ isRegistering ? '注册中...' : '注册' }}
            </el-button>

            <div class="form-footer">
              <el-button link type="primary" @click="goToLogin" class="text-btn">已有账号？返回登录</el-button>
            </div>
          </el-form>
        </div>
        <div v-else class="success-message">
          <el-icon class="success-icon" :size="52"><CircleCheck /></el-icon>
          <p>注册成功！</p>
          <p class="sub-text">您可以立即登录使用</p>
          <el-button type="primary" class="back-btn" @click="goToLogin">前往登录</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.brand-logo {
  border-radius: 14px;
  margin-bottom: 18px;
  box-shadow: 0 0 0 1px rgba(79, 70, 229, 0.35);
}
.brand-lead {
  margin: 0 0 8px;
  font-size: 0.95rem;
  color: var(--muted);
  line-height: 1.55;
  max-width: 36ch;
}
.hud-auth-particles {
  position: absolute;
  inset: 0;
  z-index: 0;
  pointer-events: none;
  overflow: hidden;
}
.hud-auth-particles :deep(canvas) {
  pointer-events: none;
}
.form-head {
  margin-bottom: 14px;
}
.form-title {
  margin: 0;
  font-size: 1.35rem;
  font-weight: 800;
  letter-spacing: -0.02em;
  color: var(--foreground);
}
.form-sub {
  margin: 6px 0 0;
  font-size: 0.88rem;
  color: var(--muted);
}
.register-form {
  display: flex;
  flex-direction: column;
  gap: 2px;
  width: 100%;
}
:deep(.el-form-item) {
  margin-bottom: 14px;
}
:deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 0 0 1px var(--border) inset;
  background: color-mix(in srgb, var(--card-solid) 92%, transparent);
}
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary) 45%, var(--border)) inset,
    0 0 0 3px color-mix(in srgb, var(--primary) 18%, transparent);
}
.submit-btn {
  width: 100%;
  margin-top: 6px;
  height: 42px;
  font-weight: 600;
  border-radius: 10px;
  background: linear-gradient(180deg, color-mix(in srgb, var(--primary) 100%, #000), var(--primary));
  border-color: color-mix(in srgb, var(--primary) 85%, #000);
  box-shadow: 0 8px 22px color-mix(in srgb, var(--primary) 28%, transparent);
}
.submit-btn:active {
  transform: translateY(1px) scale(0.98);
  filter: brightness(0.96);
}
.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}
.text-btn {
  font-size: 13px;
}
.success-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 12px 0 8px;
  color: var(--foreground);
}
.success-icon {
  font-size: 52px;
  margin-bottom: 12px;
  color: var(--el-color-success);
}
.success-message p {
  margin: 4px 0;
  font-size: 1.1rem;
  font-weight: 600;
}
.sub-text {
  color: var(--muted);
  font-size: 0.9rem !important;
  font-weight: 400 !important;
}
.back-btn {
  margin-top: 18px;
  min-width: 140px;
  border-radius: 10px;
}
.name-group,
.password-group {
  display: flex;
  gap: 10px;
  width: 100%;
}
.name-item,
.password-item {
  flex: 1;
}
.avatar-upload {
  margin-top: 4px;
}
.avatar-uploader {
  width: 100%;
  display: flex;
  justify-content: center;
}
.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: color-mix(in srgb, var(--foreground) 4%, transparent);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.2s, background 0.2s;
  border: 2px dashed color-mix(in srgb, var(--primary) 35%, var(--border));
}
.avatar-placeholder:hover {
  background: color-mix(in srgb, var(--primary) 6%, transparent);
  border-color: color-mix(in srgb, var(--primary) 55%, var(--border));
}
.avatar-icon {
  font-size: 24px;
  color: var(--muted);
  margin-bottom: 5px;
}
.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid color-mix(in srgb, var(--primary) 40%, var(--border));
}
@media (max-width: 640px) {
  .name-group {
    flex-direction: column;
    gap: 0;
  }
}
@media (prefers-reduced-motion: reduce) {
  .submit-btn:active {
    transform: none;
  }
}
</style>