<template>
  <div class="register-container">
    <!-- 背景装饰 -->
    <div class="register-background">
      <div class="background-shape shape-1"></div>
      <div class="background-shape shape-2"></div>
      <div class="background-shape shape-3"></div>
    </div>

    <!-- 注册卡片 -->
    <el-card class="register-card" shadow="always">
      <!-- 头部 -->
      <div class="register-header">
        <img src="@/assets/image/logo.png" alt="Logo" class="logo" />
        <h1 class="title">用户注册</h1>
        <p class="subtitle">创建您的账号</p>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        label-position="top"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="accountName">
          <el-input
            v-model="registerForm.accountName"
            placeholder="3-20位字符，支持字母、数字、下划线"
            size="large"
            clearable
            :prefix-icon="User"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="accountPassword">
          <el-input
            v-model="registerForm.accountPassword"
            type="password"
            placeholder="8-20位字符，必须包含字母和数字"
            size="large"
            show-password
            clearable
            :prefix-icon="Lock"
          />
        </el-form-item>

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

        <!-- 手机号 -->
        <el-form-item label="手机号码" prop="accountPhone">
          <el-input
            v-model="registerForm.accountPhone"
            placeholder="请输入手机号（可选）"
            size="large"
            clearable
            :prefix-icon="Phone"
          />
        </el-form-item>

        <!-- 用户类型 -->
        <el-form-item label="用户类型" prop="accountType">
          <el-select
            v-model="registerForm.accountType"
            placeholder="请选择用户类型"
            size="large"
            style="width: 100%"
          >
            <el-option value="customer" label="客户">
              <el-icon><User /></el-icon>
              <span style="margin-left: 8px">客户</span>
            </el-option>
            <el-option value="manager" label="商户">
              <el-icon><Shop /></el-icon>
              <span style="margin-left: 8px">商户</span>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="accountGender">
          <el-radio-group v-model="registerForm.accountGender" size="large">
            <el-radio value="male">男</el-radio>
            <el-radio value="female">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 用户协议 -->
        <el-form-item prop="acceptTerms">
          <el-checkbox v-model="registerForm.acceptTerms">
            我已阅读并同意
            <el-link type="primary" @click="showTerms">《用户服务协议》</el-link>
            和
            <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-button"
            :loading="registerLoading"
            @click="handleRegister"
          >
            {{ registerLoading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>

        <!-- 登录链接 -->
        <div class="login-link">
          <span>已有账号？</span>
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
    </el-card>

    <!-- 页脚 -->
    <div class="register-footer">
      <p>&copy; 2024 餐厅管理系统. All rights reserved.</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, Phone, Shop } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import type { UserType, Gender } from '@/types/auth'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const registerFormRef = ref<FormInstance>()
const registerLoading = ref(false)

// 注册表单数据
const registerForm = reactive({
  accountName: '',
  accountPassword: '',
  confirmPassword: '',
  accountPhone: '',
  accountType: 'customer' as UserType,
  accountGender: 'male' as Gender,
  acceptTerms: false,
})

// 自定义验证函数
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.accountPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validateTerms = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请阅读并同意用户协议'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules: FormRules = {
  accountName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' },
  ],
  accountPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在 8 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).*$/,
      message: '密码必须同时包含字母和数字',
      trigger: 'blur',
    },
  ],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }],
  accountPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  accountType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  acceptTerms: [{ validator: validateTerms, trigger: 'change' }],
}

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

  try {
    // 表单验证
    await registerFormRef.value.validate()

    registerLoading.value = true

    // 构建注册数据
    const registerData = {
      accountName: registerForm.accountName,
      accountPassword: registerForm.accountPassword,
      confirmPassword: registerForm.confirmPassword,
      accountPhone: registerForm.accountPhone || undefined,
      accountType: registerForm.accountType,
      accountGender: registerForm.accountGender,
    }

    // 调用注册API
    const result = await authStore.register(registerData)

    if (result.success) {
      ElMessage.success(result.message)
      ElMessageBox.confirm('注册成功！是否立即登录？', '注册成功', {
        confirmButtonText: '立即登录',
        cancelButtonText: '稍后登录',
        type: 'success',
      })
        .then(() => {
          router.push('/login')
        })
        .catch(() => {
          // 用户选择稍后登录
        })
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    registerLoading.value = false
  }
}

// 显示用户协议
const showTerms = () => {
  ElMessageBox.alert('这里是用户服务协议内容...', '用户服务协议', {
    confirmButtonText: '确定',
    type: 'info',
  })
}

// 显示隐私政策
const showPrivacy = () => {
  ElMessageBox.alert('这里是隐私政策内容...', '隐私政策', {
    confirmButtonText: '确定',
    type: 'info',
  })
}

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

<style scoped lang="scss">
.register-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  padding: 20px 0;
}

.register-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;

  .background-shape {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    animation: float 6s ease-in-out infinite;

    &.shape-1 {
      width: 300px;
      height: 300px;
      top: 10%;
      left: 10%;
      animation-delay: 0s;
    }

    &.shape-2 {
      width: 200px;
      height: 200px;
      top: 70%;
      right: 15%;
      animation-delay: 2s;
    }

    &.shape-3 {
      width: 150px;
      height: 150px;
      bottom: 20%;
      left: 20%;
      animation-delay: 4s;
    }
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.register-card {
  width: 100%;
  max-width: 450px;
  z-index: 2;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  border: none;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.register-header {
  text-align: center;
  margin-bottom: 25px;

  .logo {
    width: 60px;
    height: 60px;
    margin-bottom: 15px;
  }

  .title {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #2c3e50;
  }

  .subtitle {
    margin: 0;
    color: #7f8c8d;
    font-size: 14px;
  }
}

.register-form {
  .el-form-item {
    margin-bottom: 18px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #2c3e50;
      margin-bottom: 5px;
    }
  }

  .register-button {
    width: 100%;
    height: 45px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
  }

  .login-link {
    text-align: center;
    margin-top: 15px;
    font-size: 14px;
    color: #7f8c8d;

    .el-link {
      margin-left: 5px;
    }
  }
}

.register-footer {
  position: fixed;
  bottom: 20px;
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  z-index: 2;
}

// 响应式设计
@media (max-width: 768px) {
  .register-card {
    margin: 20px;
    padding: 16px;
  }

  .register-header .title {
    font-size: 20px;
  }

  .background-shape {
    &.shape-1 {
      width: 200px;
      height: 200px;
    }

    &.shape-2 {
      width: 150px;
      height: 150px;
    }

    &.shape-3 {
      width: 100px;
      height: 100px;
    }
  }
}
</style>
