<template>
  <div class="auth-container">
    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-circle circle-1"></div>
      <div class="bg-circle circle-2"></div>
      <div class="bg-circle circle-3"></div>
    </div>

    <!-- 注册表单卡片 -->
    <div class="auth-card">
      <!-- 关闭按钮 - 点击返回商城 -->
      <div class="close-btn" @click="goToShop" title="返回商城">
        <i class="el-icon-close"></i>
      </div>
      
      <!-- Logo和标题 -->
      <div class="auth-header">
        <h1 class="auth-title">欢迎注册</h1>
        <p class="auth-subtitle">创建您的 Power Leasing 账号</p>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerForm"
        :model="registerForm"
        :rules="registerRules"
        class="auth-form"
        @submit.native.prevent="handleRegister"
      >
        <!-- 邮箱输入框 -->
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            prefix-icon="el-icon-message"
            size="large"
            clearable
          >
          </el-input>
        </el-form-item>

        <!-- 验证码输入框 -->
        <el-form-item prop="code">
          <div class="code-input-wrapper">
            <el-input
              v-model="registerForm.code"
              placeholder="请输入邮箱验证码"
              prefix-icon="el-icon-key"
              size="large"
              maxlength="6"
              clearable
            >
            </el-input>
            <el-button
              type="primary"
              size="large"
              class="send-code-btn"
              :disabled="countdown > 0"
              :loading="sendingCode"
              @click="handleSendCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            prefix-icon="el-icon-lock"
            size="large"
            show-password
            clearable
          >
          </el-input>
          <!-- 密码强度提示 -->
          <div v-if="registerForm.password" class="password-strength">
            <span class="strength-label">密码强度：</span>
            <span :class="['strength-bar', passwordStrengthClass]">
              {{ passwordStrengthText }}
            </span>
          </div>
        </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"
            size="large"
            show-password
            clearable
            @keyup.enter.native="handleRegister"
          >
          </el-input>
        </el-form-item>

        <!-- 用户协议 -->
        <el-form-item prop="agree">
          <el-checkbox v-model="registerForm.agree">
            我已阅读并同意
            <a href="#" class="link-text" @click.prevent>《用户协议》</a>
            和
            <a href="#" class="link-text" @click.prevent>《隐私政策》</a>
          </el-checkbox>
        </el-form-item>

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

        <!-- 登录链接 -->
        <div class="auth-footer">
          <span class="footer-text">已有账号？</span>
          <router-link to="/login" class="link-text link-primary">
            立即登录
          </router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { register, sendEmailCode } from '../../api/user'
import { rsaEncrypt, rsaEncryptSync } from '@/utils/rsaEncrypt'

export default {
  name: 'RegisterPage',
  
  data() {
    /**
     * 邮箱格式验证
     */
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
        return
      }
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
      if (!emailReg.test(value)) {
        callback(new Error('请输入有效的邮箱地址'))
        return
      }
      callback()
    }

    /**
     * 密码格式验证
     */
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
        return
      }
      if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'))
        return
      }
      if (value.length > 20) {
        callback(new Error('密码长度不能超过20位'))
        return
      }
      callback()
    }

    /**
     * 确认密码验证
     */
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
        return
      }
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
        return
      }
      callback()
    }

    /**
     * 用户协议验证
     */
    const validateAgree = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请阅读并同意用户协议'))
        return
      }
      callback()
    }

    return {
      // 注册表单数据
      registerForm: {
        email: '',
        code: '',
        password: '',
        confirmPassword: '',
        agree: false
      },
      
      // 表单验证规则
      registerRules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ],
        agree: [
          { required: true, validator: validateAgree, trigger: 'change' }
        ]
      },
      
      // 加载状态
      loading: false,
      sendingCode: false,
      
      // 验证码倒计时
      countdown: 0,
      timer: null
    }
  },
  
  computed: {
    /**
     * 计算密码强度
     */
    passwordStrength() {
      const pwd = this.registerForm.password
      if (!pwd) return 0
      
      let strength = 0
      
      // 长度加分
      if (pwd.length >= 6) strength += 1
      if (pwd.length >= 10) strength += 1
      
      // 包含数字
      if (/\d/.test(pwd)) strength += 1
      
      // 包含小写字母
      if (/[a-z]/.test(pwd)) strength += 1
      
      // 包含大写字母
      if (/[A-Z]/.test(pwd)) strength += 1
      
      // 包含特殊字符
      if (/[^a-zA-Z0-9]/.test(pwd)) strength += 1
      
      return strength
    },
    
    /**
     * 密码强度文本
     */
    passwordStrengthText() {
      const strength = this.passwordStrength
      if (strength <= 2) return '弱'
      if (strength <= 4) return '中'
      return '强'
    },
    
    /**
     * 密码强度样式类名
     */
    passwordStrengthClass() {
      const strength = this.passwordStrength
      if (strength <= 2) return 'weak'
      if (strength <= 4) return 'medium'
      return 'strong'
    }
  },
  
  beforeDestroy() {
    // 清理定时器
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  
  methods: {
    /**
     * 返回商城页面
     * 先检查是否已经在商城页面，避免重复跳转警告
     */
    goToShop() {
      // 如果当前不在商城页面，才跳转
      if (this.$route.path !== '/productList') {
        this.$router.push('/productList')
      } else {
        // 已经在商城页面，直接返回上一页
        this.$router.go(-1)
      }
    },
    
    /**
     * 发送邮箱验证码
     */
    async handleSendCode() {
      // 先验证邮箱
      try {
        await this.$refs.registerForm.validateField('email')
      } catch (error) {
        return
      }
      
      this.sendingCode = true
      
      try {
        // 发送验证码接口参数：email（邮箱）
        const res = await sendEmailCode({
          email: this.registerForm.email
        })
        
        if (res && res.code === 200) {
          this.$message.success(res.msg || '验证码已发送，请查收邮箱')
          
          // 开发环境显示验证码（方便测试）
          if (process.env.NODE_ENV === 'development' && res.data && res.data.code) {
            this.$message.info(`测试验证码：${res.data.code}`)
          }
          
          // 开始倒计时
          this.startCountdown()
        } else {
          this.$message.error(res.msg || '发送验证码失败')
        }
      } catch (error) {
        console.error('发送验证码失败:', error)
        this.$message.error('发送验证码失败，请重试')
      } finally {
        this.sendingCode = false
      }
    },
    
    /**
     * 开始倒计时
     */
    startCountdown() {
      this.countdown = 60
      this.timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    },
    
    /**
     * 处理注册
     */
    async handleRegister() {
      // 表单验证
      try {
        await this.$refs.registerForm.validate()
      } catch (error) {
        return
      }
      
      this.loading = true
      
      try {
        // 密码RSA加密（优先使用同步方法，失败则使用异步方法）
        const passwordPlain = this.registerForm.password
        let encryptedPassword = passwordPlain
        
        // 尝试同步加密
        const syncEncrypted = rsaEncryptSync(passwordPlain)
        if (syncEncrypted) {
          encryptedPassword = syncEncrypted
        } else {
          // 同步加密失败，尝试异步加密
          const asyncEncrypted = await rsaEncrypt(passwordPlain)
          if (asyncEncrypted) {
            encryptedPassword = asyncEncrypted
          } else {
            this.$message.error('密码加密失败，请重试')
            this.loading = false
            return
          }
        }
        
        // 注册接口参数：
        // - code: 邮箱验证码
        // - password: RSA加密后的密码
        // - userEmail: 邮箱
        const res = await register({
          code: this.registerForm.code,
          password: encryptedPassword,
          userEmail: this.registerForm.email
        })
        
        if (res && res.code === 200) {
          this.$message.success('注册成功，请登录')
          
          // 跳转到登录页，并带上邮箱
          this.$router.push({
            path: '/login',
            query: {
              email: this.registerForm.email
            }
          })
        } else {
          this.$message.error(res.msg || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        this.$message.error('注册失败，请重试')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
/* 容器样式 - 全屏背景 */
.auth-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

/* 背景装饰圆圈 */
.auth-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

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

.circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-delay: 0s;
}

.circle-2 {
  width: 200px;
  height: 200px;
  bottom: -50px;
  right: -50px;
  animation-delay: 5s;
}

.circle-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  left: 50%;
  animation-delay: 10s;
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) scale(1);
  }
  50% {
    transform: translate(30px, -30px) scale(1.1);
  }
}

/* 注册卡片样式 */
.auth-card {
  background: white;
  border-radius: 16px;
  padding: 48px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 1;
  animation: slideUp 0.6s ease-out;
}

/* 关闭按钮样式 */
.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f5f5f5;
  color: #999;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
}

.close-btn:hover {
  background: #667eea;
  color: white;
  transform: rotate(90deg);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 头部样式 */
.auth-header {
  text-align: center;
  margin-bottom: 32px;
}

.auth-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin: 0 0 8px 0;
}

.auth-subtitle {
  font-size: 14px;
  color: #999;
  margin: 0;
}

/* 表单样式 */
.auth-form {
  margin-top: 24px;
}

.auth-form .el-form-item {
  margin-bottom: 20px;
}

/* 验证码输入框组合样式 */
.code-input-wrapper {
  display: flex;
  gap: 12px;
  align-items: center;
}

.code-input-wrapper .el-input {
  flex: 1;
}

.send-code-btn {
  flex-shrink: 0;
  min-width: 120px;
  height: 40px;
}

/* 密码强度提示 */
.password-strength {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
}

.strength-label {
  color: #666;
  margin-right: 8px;
}

.strength-bar {
  padding: 2px 12px;
  border-radius: 4px;
  font-weight: 600;
}

.strength-bar.weak {
  background: #fff1f0;
  color: #ff4d4f;
}

.strength-bar.medium {
  background: #fff7e6;
  color: #fa8c16;
}

.strength-bar.strong {
  background: #f6ffed;
  color: #52c41a;
}

/* 提交按钮样式 */
.auth-submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.auth-submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4);
}

/* 页脚样式 */
.auth-footer {
  text-align: center;
  margin-top: 24px;
}

.footer-text {
  color: #666;
  font-size: 14px;
  margin-right: 8px;
}

.link-text {
  color: #667eea;
  font-size: 14px;
  text-decoration: none;
  transition: color 0.3s ease;
}

.link-text:hover {
  color: #764ba2;
  text-decoration: underline;
}

.link-primary {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-card {
    padding: 32px 24px;
    max-width: 100%;
  }

  .auth-title {
    font-size: 24px;
  }

  .code-input-wrapper {
    flex-direction: column;
  }

  .send-code-btn {
    width: 100%;
    min-width: auto;
  }
}

/* Element UI组件样式覆盖 */
.auth-form >>> .el-input__inner {
  height: 44px;
  line-height: 44px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.auth-form >>> .el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.auth-form >>> .el-input__prefix {
  display: flex;
  align-items: center;
  color: #999;
}

.auth-form >>> .el-checkbox__label {
  color: #666;
  font-size: 14px;
}

.auth-form >>> .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #667eea;
  border-color: #667eea;
}

.auth-form >>> .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #667eea;
}
</style>

