<template>
  <div class="phone-bind-overlay" v-if="visible" @click="handleOverlayClick">
    <div class="phone-bind-modal" @click.stop>
      <!-- 模态框头部 -->
      <div class="modal-header">
        <button v-if="!mandatory" class="close-button" @click="handleClose">
          X
        </button>
      </div>

      <!-- 表单内容 -->
      <div class="modal-content">
        <!-- 标题 -->
        <h2 class="modal-title">绑定手机</h2>
        
        <!-- 手机号输入区域 -->
        <div class="form-section">
          <input
            id="phone-number-input"
            v-model="phoneNumber"
            type="tel"
            placeholder="请输入绑定手机号"
            maxlength="11"
            @input="handlePhoneInput"
            :class="['input-field', {
              'error': phoneError
            }]"
          />
          <div v-if="phoneError" class="error-message">
            {{ phoneError }}
          </div>
        </div>

        <!-- 验证码输入区域 -->
        <div class="form-section">
          <div class="verification-input-group">
            <input
              id="verification-code"
              v-model="verificationCode"
              type="text"
              placeholder="获取验证码"
              maxlength="6"
              @input="handleCodeInput"
              :class="['input-field', 'verification-input', {
                'error': codeError
              }]"
            />
            <button 
              @click="sendVerificationCode"
              :disabled="countdown > 0 || !isValidPhone || sendingCode"
              :class="['send-code-button', {
                'disabled': countdown > 0 || !isValidPhone
              }]"
            >
              {{ getCodeButtonText() }}
            </button>
          </div>
          <div v-if="codeError" class="error-message">
            {{ codeError }}
          </div>
        </div>
        
        <!-- 确认绑定按钮 -->
        <button 
          @click="handleConfirm"
          :disabled="!canSubmit || submitting"
          :class="['confirm-button', {
            'disabled': !canSubmit
          }]"
        >
          {{ submitting ? '确认中...' : '确认绑定' }}
        </button>
      </div>
    </div>
  </div>
  
  <!-- 人机验证弹窗 -->
  <Vcode 
    :show="showVcode" 
    @success="onVcodeSuccess" 
    @close="onVcodeClose" 
  />
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { sendSmsCode, updateUserPhone } from '../api/auth.js'
import Vcode from 'vue3-puzzle-vcode'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mandatory: {
    type: Boolean,
    default: false
  }
})

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

// 响应式数据
const phoneNumber = ref('')
const verificationCode = ref('')
const phoneError = ref('')
const codeError = ref('')
const countdown = ref(0)
const sendingCode = ref(false)
const submitting = ref(false)

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

// 计算属性
const isValidPhone = computed(() => {
  return /^1[3-9]\d{9}$/.test(phoneNumber.value)
})

const canSubmit = computed(() => {
  return isValidPhone.value && 
         verificationCode.value.length === 6 && 
         !submitting.value
})

const getCodeButtonText = () => {
  if (countdown.value > 0) {
    return `${countdown.value}s后重发`
  }
  return sendingCode.value ? '发送中...' : '获取验证码'
}



// 方法
const handleClose = () => {
  // 如果是强制模式，不允许关闭
  if (props.mandatory) {
    ElMessage.warning('请先完成手机号绑定')
    return
  }
  emit('close')
  resetForm()
}

const handleOverlayClick = () => {
  // 如果是强制模式，不允许通过点击遮罩关闭
  if (props.mandatory) {
    ElMessage.warning('请先完成手机号绑定')
    return
  }
  handleClose()
}

const resetForm = () => {
  phoneNumber.value = ''
  verificationCode.value = ''
  phoneError.value = ''
  codeError.value = ''
  countdown.value = 0
  sendingCode.value = false
  submitting.value = false
}

// 手机号输入处理
const handlePhoneInput = (event) => {
  const value = event.target.value
  // 只允许数字
  const numericValue = value.replace(/\D/g, '')
  phoneNumber.value = numericValue
  
  phoneError.value = ''
  if (numericValue && !isValidPhone.value) {
    phoneError.value = '请输入正确的手机号格式'
  }
}

// 验证码输入处理
const handleCodeInput = (event) => {
  const value = event.target.value
  // 只允许数字，最多6位
  const numericValue = value.replace(/\D/g, '').slice(0, 6)
  verificationCode.value = numericValue
  codeError.value = ''
}



// 发送验证码
const sendVerificationCode = async () => {
  if (!isValidPhone.value) {
    phoneError.value = '请输入正确的手机号格式'
    return
  }
  
  // 触发人机验证
  showVcode.value = true
}

// 人机验证成功后发送短信
const sendSmsAfterVerification = async () => {
  sendingCode.value = true
  
  try {
    const response = await sendSmsCode(phoneNumber.value)
    // 检查业务状态码
    if (response.code === 200) {
      ElMessage.success('验证码已发送')
      startCountdown()
      
      // 自动聚焦到验证码输入框
      nextTick(() => {
        document.getElementById('verification-code')?.focus()
      })
    } else {
      // 业务错误（如验证码已存在）
      ElMessage.error(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

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

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

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

// 确认绑定
const handleConfirm = async () => {
  // 完整的输入验证
  if (!phoneNumber.value) {
    phoneError.value = '请输入手机号'
    ElMessage.warning('请输入手机号')
    return
  }
  
  if (!isValidPhone.value) {
    phoneError.value = '请输入正确的手机号格式'
    ElMessage.warning('请输入正确的手机号格式')
    return
  }
  
  if (!verificationCode.value) {
    codeError.value = '请输入验证码'
    ElMessage.warning('请输入验证码')
    return
  }
  
  if (verificationCode.value.length !== 6) {
    codeError.value = '请输入完整的6位验证码'
    ElMessage.warning('请输入完整的6位验证码')
    return
  }
  
  if (!canSubmit.value) return
  
  submitting.value = true
  
  try {
    console.log('=== 开始绑定手机号 ===')
    console.log('绑定手机号:', phoneNumber.value)
    console.log('验证码:', verificationCode.value)
    
    const response = await updateUserPhone({
      newPhone: phoneNumber.value,
      code: verificationCode.value
    })
    
    console.log('手机号绑定API响应:', response)
    
    if (response.code === 200) {
      console.log('手机号绑定API成功，触发success事件')
      ElMessage.success('手机号绑定成功')
      emit('success', phoneNumber.value)
      // 不管是否强制模式，绑定成功后都要重置表单，但由父组件决定是否关闭弹窗
      resetForm()
    } else {
      console.error('手机号绑定API失败:', response)
      ElMessage.error(response.message || '绑定失败')
      codeError.value = '验证码错误，请重新输入'
    }
  } catch (error) {
    console.error('绑定手机号失败:', error)
    const errorMessage = error.response?.data?.message || error.response?.data?.msg || error.message || '绑定失败，请重试'
    console.error('错误详情:', error)
    ElMessage.error(errorMessage)
    if (errorMessage.includes('验证码')) {
      codeError.value = '验证码错误，请重新输入'
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
/* 基础重置 */
* {
  box-sizing: border-box;
}

/* 主遮罩层 */
.phone-bind-overlay {
  position: fixed;
  inset: 0;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

/* 主弹窗容器 */
.phone-bind-modal {
  background: #ffffff;
  border-radius: 12px;
  width: 540px;
  height: 390px;
  overflow: hidden;

  display: flex;
  flex-direction: column;
}

/* 头部区域 */
.modal-header {
  padding: 20px 20px 0 0;
  background: #ffffff;
  display: flex;
  justify-content: flex-end;
}

.modal-title {
  margin: 0 0 24px 0;
  font-size: 24px;
  font-weight: 400;
  color: #111827;
  text-align: center;
}

.close-button {
  width: 36px;
  height: 36px;
  background: #f8f9fa;
  
  border-radius: 6px;
  color: #374151;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-button svg {
  width: 20px;
  height: 20px;
}

.close-button:hover {
  background: #e5e7eb;
  color: #111827;
  border-color: #d1d5db;
}

/* 内容区域 */
.modal-content {

  flex: 1;
  background: #ffffff;
  width: 298px;
  height: 248px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 表单区块 */
.form-section {
  margin-bottom: 24px;
}

.form-section:last-child {
  margin-bottom: 24px;
}

/* 输入框样式 */
.input-field {
  width: 100%;
  height: 48px;
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 16px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: #333333 !important; /* 强制设置文字颜色 */
  background-color: #f5f5f5 !important; /* 强制设置背景色 */
  background: #f5f5f5 !important; /* 兼容性背景设置 */
  transition: border-color 0.2s ease;
  outline: none;
  -webkit-appearance: none; /* 移除浏览器默认样式 */
  -moz-appearance: none;
  appearance: none;
  box-sizing: border-box; /* 确保盒模型一致 */
  -webkit-text-fill-color: #333333 !important; /* WebKit浏览器文字颜色 */
  -webkit-background-clip: padding-box !important; /* WebKit背景裁剪 */
}

.input-field:focus {
  border-color: #333333;
}

.input-field.error {
  border-color: #ef4444;
}

.input-field::placeholder {
  color: #666666 !important;
  opacity: 1 !important; /* 确保 Firefox 中占位符透明度一致 */
}

.input-field::-webkit-input-placeholder {
  color: #666666 !important;
  opacity: 1 !important;
}

.input-field::-moz-placeholder {
  color: #666666 !important;
  opacity: 1 !important;
}

.input-field:-ms-input-placeholder {
  color: #666666 !important;
}

/* 验证码输入框占位符样式 */
.verification-input::placeholder {
  color: #666666 !important;
  opacity: 1 !important;
}

.verification-input::-webkit-input-placeholder {
  color: #666666 !important;
  opacity: 1 !important;
}

.verification-input::-moz-placeholder {
  color: #666666 !important;
  opacity: 1 !important;
}

.verification-input:-ms-input-placeholder {
  color: #666666 !important;
}

/* 验证码输入组 */
.verification-input-group {
  display: flex;
  gap: 0;
  align-items: stretch;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.verification-input {
  flex: 1;
  border: none;
  border-radius: 0;
  background: #f5f5f5 !important; /* 强制设置背景色，与主输入框一致 */
  background-color: #f5f5f5 !important; /* 兼容性背景设置 */
  color: #333333 !important; /* 强制设置文字颜色 */
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  -webkit-appearance: none; /* 移除浏览器默认样式 */
  -moz-appearance: none;
  appearance: none;
  -webkit-text-fill-color: #333333 !important; /* WebKit浏览器文字颜色 */
  -webkit-background-clip: padding-box !important; /* WebKit背景裁剪 */
}

.verification-input:focus {
  border: none;
  outline: none;
}

.verification-input-group:focus-within {
  border-color: #333333;
}

.send-code-button {
  height: 48px;
  padding: 0 20px;
  background: #333333;
  border: none;
  border-left: 1px solid #d1d5db;
  border-radius: 0;
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  min-width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-code-button:hover:not(.disabled) {
  background: #555555;
}

.send-code-button.disabled {
  background: #cccccc;
  color: #888888;
  cursor: not-allowed;
}







/* 错误消息 */
.error-message {
  margin-top: 8px;
  color: #ef4444;
  font-size: 14px;
}

/* 确认按钮样式 */
.confirm-button {
  width: 100%;
  height: 48px;
  background: rgba(0, 0, 0, 1);
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-top: 8px;
}

/* 流光特效 */
.confirm-button:not(.disabled):hover::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: shimmer 0.8s ease-in-out;
}

@keyframes shimmer {
  0% {
    left: -100%;
  }
  100% {
    left: 100%;
  }
}

.confirm-button:hover:not(.disabled) {
  background: #333333;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transform: translateY(-1px);
}

.confirm-button.disabled {
  background: #cccccc;
  color: #888888;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .phone-bind-overlay {
    padding: 16px;
  }
  
  .phone-bind-modal {
    width: 100%;
    border-radius: 12px;
  }
  
  .modal-header {
    padding: 16px 16px 0 0;
  }
  
  .modal-content {
    padding: 24px;
    width: 100%;
    height: auto;
  }
  

  
  .verification-input-group {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .send-code-button {
    width: 100%;
    min-width: unset;
  }
}

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

