<template>
  <div class="modal-overlay" v-if="visible" @click="handleOverlayClick">
    <div class="modal-container" @click.stop>
      <!-- 左侧渐变背景区域 -->
      <div class="gradient-section">
        <!-- Logo区域 - 预留位置 -->
        <div class="logo-area">
          <div class="logo-placeholder">
            <!-- 这里放置Logo图片 -->
            <div class="logo-text"><img src="../assets/Footer_svg/Footer_logo.svg" alt=""></div>
            
          </div>
        </div>
        
        <!-- 底部标语 -->
        <div class="slogan">
          解锁智能体开发的无限可能!
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="form-section">
        <!-- 关闭按钮 -->
        <button class="close-btn" @click="handleClose">
          <img src="@/assets/icons/colse.svg" alt="关闭" class="close-icon" />
        </button>

        <!-- 标题 -->
        <h2 class="modal-title">{{ mode === 'login' ? '立即登录' : '立即注册' }}</h2>
        
        <!-- 当前登录状态显示（调试用） -->
        <div v-if="userLoggedIn" class="current-user-info">
          <p>当前用户: {{ getUserDisplayName() }}</p>
          <el-button type="text" @click="handleLogout" size="small">退出登录</el-button>
        </div>

        <!-- 方式选项卡 -->
        <div class="login-tabs" :class="{ 'tabs-two': mode === 'login', 'tabs-two': mode === 'register' }">
          <!-- 登录模式选项 -->
          <template v-if="mode === 'login'">
            <div class="tab-item" :class="{ active: activeTab === 'passwordless' }" @click="switchTab('passwordless')">
              免密登陆
            </div>
            <div class="tab-item" :class="{ active: activeTab === 'wechat' }" @click="switchTab('wechat')">
              微信登录
            </div>
          </template>
          <!-- 注册模式选项 -->
          <template v-else-if="mode === 'register'">
            <div class="tab-item" :class="{ active: activeTab === 'phone' }" @click="switchTab('phone')">
              手机注册
            </div>
            <div class="tab-item" :class="{ active: activeTab === 'wechat' }" @click="switchTab('wechat')">
              微信注册
            </div>
          </template>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
          <!-- 微信扫码登录区域 -->
          <div class="wechat-login-area" v-if="(mode === 'login' || mode === 'register') && activeTab === 'wechat'">
            <div class="qr-code-container">
              <div v-if="isWechatLoading && !wechatQrCode" class="qr-loading">
              
                <p>正在获取{{ mode === 'login' ? '登录' : '注册' }}二维码...</p>
              </div>
              <div v-else-if="wechatQrCode" class="qr-code-display">

                <img :src="wechatQrCode" alt="微信二维码" class="qr-code-img" />
                <div class="qr-code-status">
                  <div v-if="wechatLoginStatus === 'waiting'" class="status-waiting">
                   
                    <p>请使用微信扫描二维码{{ mode === 'login' ? '登录' : '注册' }}</p>
                    <p class="wechat-tip">扫码关注公众号即可{{ mode === 'login' ? '登录' : '注册' }}</p>
                  </div>
                  <div v-else-if="wechatLoginStatus === 'scanned'" class="status-scanned">
                    <p>已扫描，请在手机上确认{{ mode === 'login' ? '登录' : '注册' }}</p>
                  </div>
                  <div v-else-if="wechatLoginStatus === 'expired'" class="status-expired">
                    <p>二维码已过期</p>
                    <el-button 
                      type="primary" 
                      @click="getWechatQrCode"
                      size="small"
                    >
                      重新获取
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 手机号输入框 -->
          <div class="input-group" v-if="mode === 'login' && activeTab !== 'wechat'">
            <el-input
              v-model="formData.phone"
              type="tel"
              placeholder="请输入手机号"
              maxlength="11"
              @input="handleInput('phone')"
              size="large"
              :validate-event="true"
              :show-word-limit="false"
            />
            <div v-if="formErrors.phone" class="error-message">{{ formErrors.phone }}</div>
          </div>

          <!-- 注册模式手机号输入框 -->
          <div class="input-group" v-if="mode === 'register' && activeTab === 'phone'">
            <el-input
              v-model="formData.phone"
              type="tel"
              placeholder="请输入手机号"
              maxlength="11"
              @input="handleInput('phone')"
              size="large"
              :validate-event="true"
              :show-word-limit="false"
            />
            <div v-if="formErrors.phone" class="error-message">{{ formErrors.phone }}</div>
          </div>

          <!-- 登录模式：验证码输入框 -->
          <div class="input-group verification-group" v-if="mode === 'login' && activeTab === 'passwordless'">
            <div class="verification-input-wrapper">
              <el-input
                v-model="formData.verificationCode"
                placeholder="获取验证码"
                maxlength="6"
                @input="handleInput('verificationCode')"
                size="large"
                :validate-event="true"
                :show-word-limit="false"
              />
              <el-button 
                type="primary" 
                @click="getVerificationCode"
                size="large"
                class="verification-btn"
                :disabled="countdown > 0"
                :loading="isLoading"
              >
                {{ getVerificationButtonText() }}
              </el-button>
            </div>
            <div v-if="formErrors.verificationCode" class="error-message">{{ formErrors.verificationCode }}</div>
          </div>





          <!-- 注册模式：验证码输入框 -->
          <div class="input-group verification-group" v-if="mode === 'register' && activeTab === 'phone'">
            <div class="verification-input-wrapper">
              <el-input
                v-model="formData.verificationCode"
                placeholder="获取验证码"
                maxlength="6"
                @input="handleInput('verificationCode')"
                size="large"
                :validate-event="true"
                :show-word-limit="false"
              />
              <el-button 
                type="primary" 
                @click="getVerificationCode"
                size="large"
                class="verification-btn"
                :disabled="countdown > 0"
                :loading="isLoading"
              >
                {{ getVerificationButtonText() }}
              </el-button>
            </div>
            <div v-if="formErrors.verificationCode" class="error-message">{{ formErrors.verificationCode }}</div>
          </div>

          <!-- 注册模式：邀请码输入框 -->
          <div class="input-group" v-if="mode === 'register' && activeTab === 'phone'">
            <el-input
              v-model="formData.invitationCode"
              placeholder="填写邀请码（选填）"
              @input="handleInput('invitationCode')"
              size="large"
              :validate-event="true"
            />
          </div>

          <!-- 按钮 -->
          <el-button 
            type="primary" 
            @click="handleSubmit"
            size="large"
            class="login-btn"
            v-if="!((mode === 'login' || mode === 'register') && activeTab === 'wechat')"
          >
            {{ mode === 'login' ? '立即登录' : '立即注册' }}
          </el-button>



          <!-- 协议同意（仅手机注册模式显示） -->
          <div class="agreement" v-if="mode === 'register' && activeTab === 'phone'">
            <el-checkbox 
              v-model="formData.agreed"
              @change="handleInput('agreed')"
              class="agreement-checkbox"
            >
              <span class="agreement-text">
                同意
                <a href="#" @click="showRegistrationAgreement">《注册协议》</a>
                &
                <a href="#" @click="showPrivacyPolicy">《隐私协议》</a>
              </span>
            </el-checkbox>
            <div v-if="formErrors.agreed" class="error-message">{{ formErrors.agreed }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>



  <!-- 手机号绑定弹窗 -->
  <PhoneBindModal 
    :visible="showPhoneBindModal"
    :mandatory="true"
    @close="handlePhoneBindClose"
    @success="handlePhoneBindSuccess"
  />
  
  <!-- 人机验证弹窗 -->
  <Vcode 
    :show="showVcode" 
    @success="onVcodeSuccess" 
    @close="onVcodeClose" 
  />
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { sendSmsCode, smsLogin, register, getWechatQrCode as apiGetWechatQrCode, checkWechatLoginStatus } from '../api/auth.js'
import { getCurrentUser } from '../api/user.js'
import { login as authLogin, logout as authLogout, isLoggedIn, getUserInfo } from '../utils/auth.js'
import { useRouter } from 'vue-router'
import PhoneBindModal from './PhoneBindModal.vue'
import Vcode from 'vue3-puzzle-vcode'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'login', // 'login' 或 'register'
    validator: (value) => ['login', 'register'].includes(value)
  },
  inviteCode: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['close', 'login', 'register'])

// 获取router实例
const router = useRouter()

// 响应式数据
const activeTab = ref('wechat')  // 初始默认为微信模式，会根据props.mode自动调整
const isLoading = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)

// 微信登录相关数据
const wechatQrCode = ref('')
const wechatSceneStr = ref('')
const wechatLoginStatus = ref('waiting') // waiting, scanned, expired
const isWechatLoading = ref(false)
const isWechatPolling = ref(false)
const wechatPollingTimer = ref(null)

// 手机号绑定弹窗
const showPhoneBindModal = ref(false)
const wechatUserData = ref(null)

// 人机验证相关
const showVcode = ref(false)
const vcodeSuccess = ref(false)

// 计算属性：检查是否已登录
const userLoggedIn = computed(() => isLoggedIn())
const currentUserInfo = computed(() => getUserInfo())
const formErrors = reactive({})
const formData = reactive({
  phone: '',
  verificationCode: '',
  invitationCode: '',
  agreed: true
})

// 方法
const handleClose = () => {
  cleanupWechatLogin()
  // 如果关闭弹窗时有临时token，也要清理
  if (sessionStorage.getItem('tempAuthToken')) {
    sessionStorage.removeItem('tempAuthToken')
    console.log('关闭弹窗时清理临时token')
  }
  emit('close')
}

// 切换选项卡
const switchTab = (tab) => {
  // 切换前清理微信登录状态
  if (activeTab.value === 'wechat') {
    cleanupWechatLogin()
  }
  
  activeTab.value = tab
  // 注意：不需要在这里调用 getWechatQrCode()，因为 watch activeTab 会自动处理
}

// 处理登出
const handleLogout = () => {
  try {
    // 调用auth工具函数的logout方法
    authLogout()
    
    // 清空localStorage中的其他相关数据
    localStorage.removeItem('user-store');
    
    // 清空sessionStorage中的相关数据
    sessionStorage.clear();
    
    // 清空可能存在的其他用户相关数据
    const keysToRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && (key.includes('user') || key.includes('token') || key.includes('auth'))) {
        keysToRemove.push(key);
      }
    }
    keysToRemove.forEach(key => localStorage.removeItem(key));
    
    console.log('退出登录成功，所有用户数据已清空');
    ElMessage.success('已退出登录')
    
    // 跳转到首页
    router.push('/')
    
    emit('close')
  } catch (error) {
    console.error('退出登录时发生错误:', error);
    ElMessage.error('退出登录失败，请重试');
  }
}

// 刷新用户信息
const refreshUserInfo = () => {
  const userInfo = getUserInfo()
  if (userInfo) {
    ElMessage.success('用户信息已刷新')
  }
}

// 获取用户显示名称
const getUserDisplayName = () => {
  const userInfo = getUserInfo()
  if (!userInfo) return '未知用户';
  
  // 根据接口返回的数据结构，按优先级获取用户名称：username > phone
  return userInfo.username || 
         userInfo.phone || 
         '未知用户';
}

const handleOverlayClick = () => {
  handleClose()
}

const handleSubmit = async () => {
  // 微信模式不需要手动提交
  if (activeTab.value === 'wechat' || !validateForm() || isLoading.value) {
    return
  }
  
  isLoading.value = true
  
  try {
    let response
    
    // 登录模式
    if (props.mode === 'login') {
      if (activeTab.value === 'passwordless') {
        response = await smsLogin({
          phone: formData.phone,
          code: formData.verificationCode
        })
      }
    }
    
    // 注册模式（手机注册）
    if (props.mode === 'register' && activeTab.value === 'phone') {
      const registerData = {
        phone: formData.phone,
        code: formData.verificationCode
      }
      
      // 只在有邀请码时才添加邀请码字段
      if (formData.invitationCode) {
        registerData.inviteCode = formData.invitationCode
      }
      
      response = await register(registerData)
    }
    
    // 处理响应
    if (response?.code === 200) {
      authLogin(response.data.userInfo, response.data.token)
      const successMessage = props.mode === 'login' ? '登录成功' : '注册成功'
      ElMessage.success(successMessage)
      emit(props.mode, response.data)
      emit('close')
    } else {
      const errorMessage = props.mode === 'login' ? '登录失败' : '注册失败'
      ElMessage.error(response?.message || errorMessage)
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  } finally {
    isLoading.value = false
  }
}



const getVerificationCode = async () => {
  const phone = formData.phone
  
  // 使用严格的手机号验证
  const phoneError = validatePhone(phone)
  if (phoneError) {
    ElMessage.error(phoneError)
    return
  }
  
  if (isLoading.value || countdown.value > 0) return
  
  // 触发人机验证
  showVcode.value = true
  
  // 动态修复人机验证弹窗层级问题（特别针对生产环境）
  fixVcodeZIndex()
}

// 人机验证成功后发送短信
const sendSmsAfterVerification = async () => {
  const phone = formData.phone
  
  isLoading.value = true
  
  try {
    const response = await sendSmsCode(phone)
    // 检查业务状态码
    if (response.code === 200) {
      ElMessage.success('验证码已发送')
      // 开始倒计时
      startCountdown()
    } else {
      // 业务错误（如验证码已存在）
      ElMessage.error(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    isLoading.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value)
      countdownTimer.value = null
    }
  }, 1000)
}

// 获取验证码按钮文本
const getVerificationButtonText = () => {
  if (countdown.value > 0) {
    return `${countdown.value}s后重发`
  }
  return '获取验证码'
}

// 组件挂载和卸载

onMounted(() => {
  // 如果用户已登录，自动关闭登录弹窗
  if (userLoggedIn.value) {
    
    emit('close')
    return
  }
  
  // 如果有传入的邀请码，自动填入
  if (props.inviteCode) {
    formData.invitationCode = props.inviteCode
  }
  
  // 如果弹窗可见且当前是微信tab，获取二维码
  if (props.visible && activeTab.value === 'wechat') {
    setTimeout(() => {
      getWechatQrCode()
    }, 100)
  }
})

// 监听邀请码变化
watch(() => props.inviteCode, (newCode) => {
  if (newCode) {
    formData.invitationCode = newCode
  }
})

// 监听模式变化，设置对应的默认tab
watch(() => props.mode, (newMode, oldMode) => {
  if (newMode === 'login') {
    activeTab.value = 'wechat'  // 登录默认为微信模式
  } else if (newMode === 'register') {
    // 有邀请码时注册默认为微信模式，否则为手机模式
    activeTab.value = props.inviteCode ? 'wechat' : 'phone'
  }
  
  // 如果模式发生变化且当前是微信tab，并且弹窗可见，重新获取二维码
  if (oldMode && oldMode !== newMode && activeTab.value === 'wechat' && props.visible) {
    // 延迟重新获取二维码，确保状态更新完成
    setTimeout(() => {
      getWechatQrCode()
    }, 100)
  }
}, { immediate: true })

// 监听邀请码变化，如果是注册模式且有邀请码，切换到微信模式
watch(() => props.inviteCode, (newInviteCode) => {
  if (props.mode === 'register' && newInviteCode) {
    activeTab.value = 'wechat'
  }
})

// 监听弹窗显示状态，当弹窗显示且当前是微信tab时自动获取二维码
watch(() => props.visible, (newVisible) => {
  if (newVisible && activeTab.value === 'wechat') {
    // 延迟一点获取二维码，确保DOM已渲染
    setTimeout(() => {
      getWechatQrCode()
    }, 100)
  } else if (!newVisible) {
    // 弹窗关闭时清理微信登录状态
    cleanupWechatLogin()
  }
})

// 监听activeTab变化，当切换到微信tab且弹窗可见时自动获取二维码
watch(() => activeTab.value, (newTab) => {
  if (newTab === 'wechat' && props.visible) {
    getWechatQrCode()
  }
})

// 监听人机验证弹窗显示状态变化，确保层级正确
watch(() => showVcode.value, (newShowVcode) => {
  if (newShowVcode) {
    console.log('[VCODE] 人机验证弹窗即将显示，准备修复层级')
    // 多次尝试修复，确保在各种环境下都能正常工作
    fixVcodeZIndex()
    setTimeout(fixVcodeZIndex, 200)
    setTimeout(fixVcodeZIndex, 500)
    setTimeout(fixVcodeZIndex, 1000)
  }
})


onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  cleanupWechatLogin()
})

const showRegistrationAgreement = () => {
  // 在新标签页中打开用户协议
  window.open('/doc/用户协议.html', '_blank')
}

const showPrivacyPolicy = () => {
  // 在新标签页中打开隐私政策
  window.open('/doc/隐私政策.html', '_blank')
}

// 实时验证函数
const clearError = (field) => {
  if (formErrors[field]) {
    delete formErrors[field]
  }
}

// 过滤手机号输入，只允许数字
const filterPhoneInput = (value) => {
  return value.replace(/[^\d]/g, '')
}

// 监听输入变化，清除对应错误
const handleInput = (field) => {
  // 如果是手机号字段，先过滤非数字字符
  if (field === 'phone') {
    formData.phone = filterPhoneInput(formData.phone)
  }
  clearError(field)
  // 实时验证
  validateField(field)
}





// 实时验证单个字段
const validateField = (field) => {
  const value = formData[field]
  let error = ''
  
  switch (field) {
    case 'phone':
      error = validatePhone(value)
      break
    case 'verificationCode':
      if ((props.mode === 'login' && activeTab.value === 'passwordless') || props.mode === 'register') {
        error = validateVerificationCode(value)
      }
      break
  }
  
  if (error) {
    formErrors[field] = error
  } else {
    delete formErrors[field]
  }
}

// 验证函数
const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phone) return '请输入手机号'
  if (!phoneRegex.test(phone)) return '请输入正确的手机号'
  return ''
}

const validatePassword = (password) => {
  if (!password) return '请输入密码'
  if (password.length < 6) return '密码长度至少6位'
  if (password.length > 20) return '密码长度不能超过20位'
  return ''
}

const validateRegisterPassword = (password) => {
  if (!password) return '请设置密码'
  if (password.length < 6) return '密码长度至少6位'
  if (password.length > 20) return '密码长度不能超过20位'
  // 密码强度验证
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasNumber = /\d/.test(password)
  if (!hasLetter || !hasNumber) return '密码必须包含字母和数字'
  return ''
}

const validateConfirmPassword = (confirmPassword, password) => {
  if (!confirmPassword) return '请确认密码'
  if (confirmPassword !== password) return '两次输入的密码不一致'
  return ''
}

const validateVerificationCode = (code) => {
  if (!code) return '请输入验证码'
  if (code.length !== 6) return '验证码为6位数字'
  if (!/^\d{6}$/.test(code)) return '验证码只能包含数字'
  return ''
}

const validateForm = () => {
  const errors = {}
  
  // 微信模式跳过验证
  if (activeTab.value === 'wechat') {
    return true
  }
  
  // 手机号验证（所有非微信模式都需要）
  const phoneError = validatePhone(formData.phone)
  if (phoneError) errors.phone = phoneError
  
  // 登录模式验证
  if (props.mode === 'login') {
    if (activeTab.value === 'passwordless') {
      const codeError = validateVerificationCode(formData.verificationCode)
      if (codeError) errors.verificationCode = codeError
    }
  }
  
  // 注册模式验证（手机注册）
  if (props.mode === 'register' && activeTab.value === 'phone') {
    const codeError = validateVerificationCode(formData.verificationCode)
    if (codeError) errors.verificationCode = codeError
    
    if (!formData.agreed) {
      errors.agreed = '请先同意注册协议和隐私协议'
    }
  }
  
  Object.assign(formErrors, errors)
  return Object.keys(errors).length === 0
}



// 微信登录相关方法
const getWechatQrCode = async () => {
  if (isWechatLoading.value) return
  
  // 清理之前的状态
  wechatQrCode.value = ''
  wechatSceneStr.value = ''
  wechatLoginStatus.value = 'waiting'
  
  isWechatLoading.value = true
  
  try {
    // 准备请求参数
    const params = {
      isRegister: props.mode === 'register',
      inviteCode: props.mode === 'register' ? props.inviteCode : ''
    }
    
    const response = await apiGetWechatQrCode(params)
    
    if (response.code === 200) {
      wechatQrCode.value = response.data.qrCodeUrl
      wechatSceneStr.value = response.data.sceneStr
      wechatLoginStatus.value = 'waiting'
      
      // 开始轮询检查登录状态
      startWechatPolling()
      
    } else {
      ElMessage.error(response.message || '获取二维码失败')
      // 确保在失败时清理状态
      wechatQrCode.value = ''
      wechatSceneStr.value = ''
    }
  } catch (error) {
    console.error('获取微信二维码失败:', error)
    ElMessage.error(error.response?.data?.message || '获取二维码失败')
    // 确保在异常时清理状态
    wechatQrCode.value = ''
    wechatSceneStr.value = ''
  } finally {
    isWechatLoading.value = false
  }
}

// 开始轮询检查微信登录状态
const startWechatPolling = () => {
  // 清除之前的轮询
  if (wechatPollingTimer.value) {
    clearInterval(wechatPollingTimer.value)
  }
  
  // 设置轮询状态
  isWechatPolling.value = true
  
  // 开始新的轮询，每2秒检查一次
  wechatPollingTimer.value = setInterval(async () => {
    try {
      const response = await checkWechatLoginStatus(wechatSceneStr.value)
      
      if (response.code === 200) {
        // 登录成功
        clearInterval(wechatPollingTimer.value)
        wechatPollingTimer.value = null
        isWechatPolling.value = false
        
        if (props.mode === 'login') {
          // 登录模式：检查是否需要绑定手机号
          const userInfo = response.data.userInfo
          const hasPhone = userInfo.phone && userInfo.phone.trim() !== ''
          
          if (hasPhone) {
            // 已有手机号，保存登录信息并完成登录
            authLogin(response.data.userInfo, response.data.token)
            ElMessage.success('微信登录成功')
            emit('login', response.data)
            emit('close')
          } else {
            // 没有手机号，临时保存token到sessionStorage供绑定API使用
            console.log('临时保存token到sessionStorage，供绑定手机号API使用')
            sessionStorage.setItem('tempAuthToken', response.data.token)
            ElMessage.success('微信登录成功，请绑定手机号后完成登录')
            wechatUserData.value = response.data
            showPhoneBindModal.value = true
            // 注意：不保存到localStorage，等手机号绑定完成后再正式保存
          }
        } else {
          // 注册模式：检查是否需要绑定手机号
          const userInfo = response.data.userInfo
          const hasPhone = userInfo.phone && userInfo.phone.trim() !== ''
          
          if (hasPhone) {
            // 已有手机号，保存登录信息并完成注册
            authLogin(response.data.userInfo, response.data.token)
            ElMessage.success('微信注册成功')
            emit('register', response.data)
            emit('close')
          } else {
            // 没有手机号，临时保存token到sessionStorage供绑定API使用
            console.log('临时保存token到sessionStorage，供绑定手机号API使用')
            sessionStorage.setItem('tempAuthToken', response.data.token)
            ElMessage.success('微信注册成功，请绑定手机号后完成注册')
            wechatUserData.value = response.data
            showPhoneBindModal.value = true
            // 注意：不保存到localStorage，等手机号绑定完成后再正式保存
          }
        }
      } else if (response.code === 500) {
        // 用户尚未扫码，继续轮询
        console.log('用户尚未扫码，继续等待...')
      }
    } catch (error) {
      console.error('检查微信登录状态失败:', error)
      
      // 如果是网络错误或其他错误，可能需要停止轮询
      if (error.response?.status !== 500) {
        clearInterval(wechatPollingTimer.value)
        wechatPollingTimer.value = null
        isWechatPolling.value = false
        wechatLoginStatus.value = 'expired'
        ElMessage.error('登录检查失败，请重新获取二维码')
      }
    }
  }, 2000)
  
  // 设置二维码过期时间（5分钟）
  setTimeout(() => {
    if (wechatPollingTimer.value) {
      clearInterval(wechatPollingTimer.value)
      wechatPollingTimer.value = null
      isWechatPolling.value = false
      wechatLoginStatus.value = 'expired'
      ElMessage.warning('二维码已过期，请重新获取')
    }
  }, 5 * 60 * 1000) // 5分钟
}

// 清理微信登录相关资源
const cleanupWechatLogin = () => {
  if (wechatPollingTimer.value) {
    clearInterval(wechatPollingTimer.value)
    wechatPollingTimer.value = null
  }
  wechatQrCode.value = ''
  wechatSceneStr.value = ''
  wechatLoginStatus.value = 'waiting'
  isWechatPolling.value = false
  isWechatLoading.value = false
  // 注意：不清空wechatUserData，因为手机号绑定过程中可能需要用到
  console.log('cleanupWechatLogin: 清理微信登录状态，但保留用户数据')
}

// 人机验证处理函数
const onVcodeSuccess = () => {
  vcodeSuccess.value = true
  showVcode.value = false
  ElMessage.success('人机验证成功')
  // 验证成功后发送短信
  sendSmsAfterVerification()
}

const onVcodeClose = () => {
  showVcode.value = false
  vcodeSuccess.value = false
  ElMessage.warning('验证已取消')
}

// 动态修复人机验证弹窗层级问题
const fixVcodeZIndex = () => {
  setTimeout(() => {
    // 查找所有可能的人机验证相关元素
    const vcodeElements = [
      document.querySelector('.vcodeImg-box'),
      document.querySelector('.vcodeImg'),
      document.querySelector('.vcodeImg-Wrap'),
      ...document.querySelectorAll('[class*="vcode"]')
    ].filter(el => el) // 过滤掉null元素
    
    vcodeElements.forEach(el => {
      if (el) {
        el.style.zIndex = '10006'
        el.style.position = 'fixed'
        console.log('[VCODE FIX] 动态修复验证码层级:', el.className)
      }
    })
    
    // 特别处理遮罩层
    const maskElement = document.querySelector('.vcodeImg-mask')
    if (maskElement) {
      maskElement.style.zIndex = '10005'
      maskElement.style.position = 'fixed'
      maskElement.style.top = '0'
      maskElement.style.left = '0'
      maskElement.style.width = '100vw'
      maskElement.style.height = '100vh'
      console.log('[VCODE FIX] 动态修复验证码遮罩层级')
    }
  }, 100) // 延迟100ms执行，确保DOM已渲染
}

// 手机号绑定弹窗处理
const handlePhoneBindClose = () => {
  // 在强制绑定模式下，这个函数实际上不会被调用，因为PhoneBindModal会阻止关闭
  showPhoneBindModal.value = false
  ElMessage.warning('您必须绑定手机号才能完成登录')
  // 不清空 wechatUserData，保持绑定弹窗状态
}

const handlePhoneBindSuccess = async (phoneNumber) => {
  console.log('=== 手机号绑定成功回调开始 ===')
  console.log('绑定的手机号:', phoneNumber)
  console.log('当前wechatUserData:', wechatUserData.value)
  console.log('当前模式:', props.mode)
  
  showPhoneBindModal.value = false
  ElMessage.success(`手机号 ${phoneNumber} 绑定成功`)
  
  // 更新用户信息并完成登录/注册流程
  if (wechatUserData.value) {
    try {
      // 首先保存基础的登录信息到本地存储
      console.log('开始保存登录信息...')
      authLogin(wechatUserData.value.userInfo, wechatUserData.value.token)
      
      console.log('基础登录信息保存完成，检查登录状态:', isLoggedIn())
      console.log('基础用户信息:', getUserInfo())
      
      // 尝试从服务器获取最新的用户信息（包含已绑定的手机号）
      try {
        console.log('尝试获取服务器最新用户信息...')
        const userInfoResponse = await getCurrentUser()
        
        if (userInfoResponse.code === 200) {
          console.log('获取到最新用户信息:', userInfoResponse.data)
          // 使用最新的用户信息更新本地存储
          const finalUserData = {
            userInfo: userInfoResponse.data,
            token: wechatUserData.value.token
          }
          authLogin(finalUserData.userInfo, finalUserData.token)
          console.log('最新用户信息已保存')
          
          // 发出相应的事件
          if (props.mode === 'login') {
            emit('login', finalUserData)
          } else {
            emit('register', finalUserData)
          }
        } else {
          console.warn('获取最新用户信息失败，使用手动更新的数据')
          // 回退到手动更新的数据
          const updatedUserInfo = {
            ...wechatUserData.value.userInfo,
            phone: phoneNumber
          }
          const updatedData = {
            ...wechatUserData.value,
            userInfo: updatedUserInfo
          }
          authLogin(updatedData.userInfo, updatedData.token)
          
          if (props.mode === 'login') {
            emit('login', updatedData)
          } else {
            emit('register', updatedData)
          }
        }
      } catch (error) {
        console.error('获取最新用户信息失败:', error)
        // 回退到手动更新的数据
        const updatedUserInfo = {
          ...wechatUserData.value.userInfo,
          phone: phoneNumber
        }
        const updatedData = {
          ...wechatUserData.value,
          userInfo: updatedUserInfo
        }
        authLogin(updatedData.userInfo, updatedData.token)
        
        if (props.mode === 'login') {
          emit('login', updatedData)
        } else {
          emit('register', updatedData)
        }
      }
      
      // 延迟关闭弹窗，确保所有操作完成
      setTimeout(() => {
        console.log('最终检查登录状态:', isLoggedIn())
        console.log('最终用户信息:', getUserInfo())
        emit('close')
        console.log('=== 手机号绑定成功回调完成 ===')
      }, 200)
      
    } catch (error) {
      console.error('保存登录信息失败:', error)
      ElMessage.error('保存登录信息失败，请重新登录')
    } finally {
      // 清空临时数据
      wechatUserData.value = null
      // 清理临时token
      sessionStorage.removeItem('tempAuthToken')
      console.log('已清理临时token')
    }
  } else {
    console.error('错误：wechatUserData为空，无法完成登录流程')
    ElMessage.error('登录数据丢失，请重新登录')
  }
}
</script>

<style scoped>
/* 左侧渐变背景区域 */
.gradient-section {
  width: 300px;
  min-width: 250px;
  flex: 0 0 auto;
  background: linear-gradient(135deg, #000000 0%, #000000 20%, #1e3a8a 35%, #3b82f6 50%, #8b5cf6 65%, #8b5cf6 100%);
  display: flex;
  flex-direction: column;
  padding: 40px 30px;
  position: relative;
  overflow: hidden;
}

/* Logo区域 */
.logo-area {
  flex: 0 0 auto;
  margin-bottom: 60px;
}



.logo-placeholder {
  color: white;
}

.logo-text {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.logo-text img {
  height: 40px;
  width: auto;
  display: block;
  animation: logoGlow 2s ease-in-out infinite alternate;
}

@keyframes logoGlow {
  0% {
    filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.3));
  }
  100% {
    filter: drop-shadow(0 0 15px rgba(255, 255, 255, 0.6));
  }
}

.logo-text sup {
  font-size: 16px;
  vertical-align: super;
}

.studio-text {
  font-size: 18px;
  opacity: 0.9;
}

/* 标语 */
.slogan {
  color: white;
  font-size: 16px;
  text-align: center;
  line-height: 1.5;
  flex: 1;
  display: flex;
  align-items: flex-end;
  padding-bottom: 20px;
  position: relative;
  z-index: 2;
}



/* 模态框容器 */
.modal-container {
  width: 90vw;
  max-width: 816px;
  min-width: 320px;
  height: 90vh;
  max-height: 600px;
  min-height: 500px;
  background: white;
  border-radius: 12px;
  display: flex;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  position: relative;
}



/* 遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}



/* 右侧表单区域 */
.form-section {
  flex: 1;
  padding: 40px;
  position: relative;
  background: white;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}



/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  background: none;
  border: none;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  outline: none;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
  transform: scale(1.1);
}

.close-btn:hover .close-icon {
  filter: brightness(0.8);
}

.close-btn:focus {
  outline: none;
}

.close-btn .close-icon {
  width: 17px;
  height: 17px;
  display: block;
  transition: filter 0.2s ease;
}

/* 标题 */
.modal-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
  width: 100%;
  max-width: 298px;
}





/* 选项卡容器 */
.login-tabs {
  display: flex;
  margin-bottom: 30px;
  border-radius: 8px;
  background: #f5f5f5;
  padding: 4px;
  width: 100%;
  max-width: 298px;
  min-height: 41px;
  position: relative;
  overflow: hidden;
}



/* 基础tab项样式 */
.tab-item {
  flex: 1;
  padding: 8px 12px;
  text-align: center;
  cursor: pointer;
  border-radius: 6px;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 33px;
  position: relative;
  z-index: 1;
  white-space: nowrap;
  min-width: 0;
}

.tab-item.active {
  background: #333;
  color: white;
  z-index: 2;
}

.tab-item:hover:not(.active) {
  background: #e5e5e5;
}



/* 两个选项卡优化 */
.tabs-two .tab-item {
  font-size: 14px;
  padding: 8px 16px;
}

/* 表单内容 */
.form-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  align-items: center;
  width: 100%;
}



/* 输入框组 */
.input-group {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 298px;
}



/* Element Plus 输入框样式覆盖 - 保持原样式 */
.input-group .el-input {
  width: 100%;
  max-width: 298px;
}

.input-group .el-input__wrapper {
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 2px solid #e5e5e5;
  padding: 16px 20px;
  font-size: 16px;
  box-sizing: border-box;
  height: 41px;
}

.input-group .el-input__wrapper:hover {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.input-group .el-input__wrapper.is-focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  transform: translateY(-2px);
}

.input-group .el-input__inner {
  padding: 0;
  font-size: 16px;
}

.input-group .el-input__inner::placeholder {
  color: #999;
}

/* 错误提示样式 */
.error-message {
  color: #ef4444;
  font-size: 12px;
  animation: errorSlideIn 0.3s ease-out;
  align-self: flex-start;
  margin: 0;
}

@keyframes errorSlideIn {
  0% {
    opacity: 0;
    transform: translateY(-5px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}



/* 验证码输入框组 */
.verification-group {
  display: flex;
  flex-direction: column;
  gap: 30px;
  width: 100%;
  max-width: 298px;
}

.verification-input-wrapper {
  display: flex;
  gap: 12px;
  width: 100%;
  max-width: 298px;
}

.verification-group .el-input {
  flex: 1;
  width: 180px;
}

.verification-btn {
  white-space: nowrap;
  transition: all 0.3s ease;
  padding: 16px 20px;
  background: #333;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  height: 41px;
  width: 106px;
}

.verification-btn:hover {
  background: #555;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.verification-btn:disabled {
  background: #ccc !important;
  color: #999 !important;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

.verification-btn:disabled:hover {
  background: #ccc !important;
  transform: none !important;
  box-shadow: none !important;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  max-width: 298px;
  height: 41px;
  position: relative;
  overflow: hidden;
  padding: 16px;
  background: #333;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-btn:hover::before {
  left: 100%;
}

.login-btn:hover {
  background: #555;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}



/* 忘记密码 */
.forgot-password {
  text-align: center;
  width: 100%;
  max-width: 298px;
  display: flex;
  justify-content: center;
}

.forgot-password a {
  color: #3b82f6;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password a:hover {
  text-decoration: underline;
}

/* 当前用户信息显示 */
.current-user-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  width: 100%;
  max-width: 298px;
  text-align: center;
}

.current-user-info p {
  margin: 0 0 8px 0;
  color: #495057;
  font-size: 14px;
}

.current-user-info .el-button {
  color: #dc3545;
  font-size: 12px;
}

.current-user-info .el-button:hover {
  color: #c82333;
}

/* 协议同意 */
.agreement {
  margin-top: 10px;
  width: 100%;
  max-width: 298px;
  display: flex;
  justify-content: center;
}

.agreement-checkbox {
  font-size: 14px;
  color: #666;
}

.agreement-text {
  line-height: 1.4;
}

.agreement-text a {
  color: #3b82f6;
  text-decoration: none;
}

.agreement-text a:hover {
  text-decoration: underline;
}



/* 人机验证组件层级调整已在全局 vcode-fix.css 中处理，这里移除重复设置避免冲突 */

/* 微信登录相关样式 */
.wechat-login-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 298px;
}



.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.qr-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 40px 20px;
}

.qr-code-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.qr-code-img {
  width: 200px;
  height: 200px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  object-fit: contain;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}



.qr-code-status {
  text-align: center;
  width: 100%;
}

.status-waiting,
.status-scanned,
.status-expired {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.status-waiting p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.wechat-tip {
  color: #07c160 !important;
  font-size: 13px !important;
  margin: 8px 0 0 0 !important;
  font-weight: 500;
  opacity: 0.9;
}

.status-scanned p {
  color: #52c41a;
  font-size: 14px;
  margin: 0;
  font-weight: 500;
}

.status-expired p {
  color: #ff4d4f;
  font-size: 14px;
  margin: 0;
  margin-bottom: 10px;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f0f0f0;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}







/* 响应式设计 */
@media (max-width: 900px) {
  .modal-overlay {
    padding: 15px;
    box-sizing: border-box;
  }

  .modal-container {
    width: 95vw;
    max-width: 816px;
    height: auto;
    max-height: calc(100% - 30px);
    min-height: 500px;
    flex-direction: column;
    margin: 0;
    box-sizing: border-box;
  }

  .gradient-section {
    width: 100%;
    height: 180px;
    min-width: auto;
    padding: 20px;
    justify-content: space-between;
    flex-shrink: 0;
  }

  .form-section {
    padding: 25px 20px;
    flex: 1;
    overflow-y: auto;
    min-height: 320px;
  }

  /* 900px以下：调整表单元素宽度 */
  .login-tabs,
  .input-group,
  .login-btn,
  .forgot-password,
  .agreement,
  .current-user-info,
  .wechat-login-area,
  .modal-title {
    max-width: calc(100vw - 70px);
  }

  .qr-code-img {
    width: 180px;
    height: 180px;
  }

  .wechat-login-area {
    width: 100%;
  }


}

@media (max-width: 600px) {
  .modal-overlay {
    padding: 10px;
    box-sizing: border-box;
  }

  .modal-container {
    width: calc(100% - 20px);
    max-width: 95vw;
    height: auto;
    max-height: calc(100% - 20px);
    min-height: 450px;
    margin: 0;
    box-sizing: border-box;
  }

  .gradient-section {
    height: 140px;
    padding: 15px;
    justify-content: space-between;
    flex-shrink: 0;
  }

  .logo-area {
    margin-bottom: 15px;
  }
  
  .logo-text {
    font-size: 22px;
  }

  .studio-text {
    font-size: 15px;
  }

  .slogan {
    font-size: 13px;
  }

  .form-section {
    padding: 20px 15px;
    flex: 1;
    overflow-y: auto;
    min-height: 310px;
  }

  .modal-title {
    font-size: 20px;
    margin-bottom: 15px;
  }

  /* 600px以下：进一步调整表单元素宽度 */
  .login-tabs,
  .input-group,
  .login-btn,
  .forgot-password,
  .agreement,
  .current-user-info,
  .wechat-login-area,
  .modal-title {
    max-width: calc(100vw - 50px);
  }



  /* 两个按钮保持横向排列 */
  .tabs-two .tab-item {
    padding: 10px 12px;
    font-size: 13px;
    min-height: 37px;
  }

  .form-content {
    gap: 15px;
  }

  .login-btn {
    padding: 14px;
    font-size: 15px;
  }

  .qr-code-img {
    width: 160px;
    height: 160px;
  }




}

@media (max-width: 480px) {
  .modal-overlay {
    padding: 8px;
    box-sizing: border-box;
  }

  .modal-container {
    width: calc(100% - 16px);
    max-width: 100%;
    height: auto;
    max-height: calc(100% - 16px);
    min-height: 400px;
    margin: 0;
    box-sizing: border-box;
  }

  .gradient-section {
    height: 100px;
    padding: 10px;
    justify-content: space-between;
    flex-shrink: 0;
  }

  .logo-area {
    margin-bottom: 10px;
  }
  
  .logo-text {
    font-size: 18px;
  }

  .studio-text {
    font-size: 13px;
  }

  .slogan {
    font-size: 11px;
  }

  .form-section {
    padding: 15px 10px;
    flex: 1;
    overflow-y: auto;
    min-height: 300px;
  }

  .modal-title {
    font-size: 18px;
    margin-bottom: 15px;
  }

  /* 480px以下：最大化可用宽度 */
  .login-tabs,
  .input-group,
  .login-btn,
  .forgot-password,
  .agreement,
  .current-user-info,
  .wechat-login-area,
  .modal-title {
    max-width: calc(100% - 20px);
  }

  /* 480px以下：保持两个按钮横向排列 */
  .login-tabs {
    gap: 4px;
    margin-bottom: 15px;
    padding: 6px;
  }

  .tab-item {
    width: 100%;
    flex: none;
    padding: 10px 16px;
    font-size: 13px;
    min-height: 36px;
  }

  .qr-code-img {
    width: 140px;
    height: 140px;
  }




}
</style> 