<script setup>
definePage({
  layout: 'HomeLayout',
  style: {
    navigationBarTitleText: '我的',
    navigationStyle: 'custom',
  },
})

import { ref, computed, onBeforeMount, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useAgentStore } from '@/stores/agentStore'
import { useUserStore } from '@/stores/userStore'
import { useEnv } from '@/composables/useEnv'
import { getRevenueInfo, realNameAuth } from '@/api/agent'
import { bindMobile } from '@/api/user'
import useApiFetch from '@/composables/useApiFetch'

const agentStore = useAgentStore()
const userStore = useUserStore()
const { isAgent, level, levelName, agentCode, isRealName } = storeToRefs(agentStore)
const { userName, userAvatar, isLoggedIn, mobile } = storeToRefs(userStore)
const { isWeChat } = useEnv()
const revenueData = ref(null)
const showWithdrawQrPopup = ref(false)
const showBindMobilePopup = ref(false)
const showRealNameAuthPopup = ref(false)
const phoneNumber = ref('')
const verificationCode = ref('')
const isCountingDown = ref(false)
const countdown = ref(60)
let countdownTimer = null

// 实名认证相关
const realName = ref('')
const idCard = ref('')
const realNamePhoneNumber = ref('')
const realNameVerificationCode = ref('')
const isRealNameCountingDown = ref(false)
const realNameCountdown = ref(60)
const isAgreed = ref(false)
let realNameCountdownTimer = null

const levelNamesMap = { 1: '普通代理', 2: '黄金代理', 3: '钻石代理' }

const levelGradient = computed(() => {
  const currentLevel = level.value || 1
  const gradients = {
    1: { border: 'bg-gradient-to-r from-gray-300 to-gray-400', badge: 'bg-gradient-to-r from-gray-500 to-gray-600', text: 'text-gray-600', cardBorder: 'bg-gradient-to-r from-gray-300 to-gray-400' },
    2: { border: 'bg-gradient-to-r from-yellow-400 to-amber-500', badge: 'bg-gradient-to-r from-yellow-500 to-amber-600', text: 'text-amber-600', cardBorder: 'bg-gradient-to-r from-yellow-400 to-amber-500' },
    3: { border: 'bg-gradient-to-r from-purple-400 to-pink-400', badge: 'bg-gradient-to-r from-purple-500 to-pink-500', text: 'text-purple-600', cardBorder: 'bg-gradient-to-r from-purple-400 to-pink-400' },
  }
  return gradients[currentLevel] || gradients[1]
})

function getDefaultAvatar() {
  return '/static/me/user.png'
}


const serviceUrl = import.meta.env?.VITE_SERVICE_URL || ''
function toService() {
  if (serviceUrl) {
    // #ifdef H5
    window.location.href = serviceUrl
    // #endif
    // #ifndef H5
    uni.navigateTo({ url: '/pages/webview/index?url=' + encodeURIComponent(serviceUrl) })
    // #endif
  }
}

function toUserAgreement() {
  uni.navigateTo({ url: '/pages/userAgreement/index' })
}

function toPrivacyPolicy() {
  uni.navigateTo({ url: '/pages/privacyPolicy/index' })
}

function toAgentSystemGuide() {
  uni.navigateTo({ url: '/pages/agentSystemGuide/index' })
}

function toUpgrade() {
  uni.navigateTo({ url: '/pages/agentUpgrade/index' })
}

function toUpgradeSubordinate() {
  uni.navigateTo({ url: '/pages/upgradeSubordinate/index' })
}

function toInviteCodeManage() {
  uni.navigateTo({ url: '/pages/invitation/index' })
}

function toRealNameAuth() {
  if (!isAgent.value) {
    uni.showToast({ title: '请先成为代理', icon: 'none' })
    return
  }
  // 如果已实名认证，提示用户
  if (isRealName.value) {
    uni.showToast({ title: '您已完成实名认证', icon: 'success' })
    return
  }
  // 初始化表单数据，使用代理的手机号
  realNamePhoneNumber.value = agentStore.mobile || mobile.value || ''
  realName.value = ''
  idCard.value = ''
  realNameVerificationCode.value = ''
  isAgreed.value = false
  showRealNameAuthPopup.value = true
}

function closeRealNameAuthPopup() {
  showRealNameAuthPopup.value = false
  realName.value = ''
  idCard.value = ''
  realNamePhoneNumber.value = ''
  realNameVerificationCode.value = ''
  isAgreed.value = false
  if (realNameCountdownTimer) {
    clearInterval(realNameCountdownTimer)
    realNameCountdownTimer = null
  }
  isRealNameCountingDown.value = false
  realNameCountdown.value = 60
}

function toAgentReport() {
  uni.navigateTo({ url: '/pages/agentPromotionQueryList/index' })
}

function toWithdraw() {
  showWithdrawQrPopup.value = true
}

function closeWithdrawQrPopup() {
  showWithdrawQrPopup.value = false
}

function toWithdrawDetails() {
  uni.navigateTo({ url: '/pages/withdrawDetails/index' })
}

function goToPromoteDetail() {
  uni.navigateTo({ url: '/pages/promoteDetails/index' })
}

function goToRebateDetail() {
  uni.navigateTo({ url: '/pages/rewardsDetails/index' })
}

function toRegister() {
  uni.navigateTo({ url: '/pages/register/index' })
}

function openBindMobilePopup() {
  showBindMobilePopup.value = true
  phoneNumber.value = ''
  verificationCode.value = ''
}

function closeBindMobilePopup() {
  showBindMobilePopup.value = false
  phoneNumber.value = ''
  verificationCode.value = ''
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  isCountingDown.value = false
  countdown.value = 60
}

const isPhoneNumberValid = computed(() => /^1[3-9]\d{9}$/.test(phoneNumber.value))

// 实名认证表单验证
const isRealNamePhoneValid = computed(() => /^1[3-9]\d{9}$/.test(realNamePhoneNumber.value))
const isIdCardValid = computed(() => /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idCard.value))
const isRealNameValid = computed(() => /^[\u4e00-\u9fa5]{2,}$/.test(realName.value))
const canSubmitRealName = computed(() => 
  isRealNamePhoneValid.value &&
  isIdCardValid.value &&
  isRealNameValid.value &&
  realNameVerificationCode.value.length === 6 &&
  isAgreed.value
)

async function sendVerificationCode() {
  if (isCountingDown.value || !isPhoneNumberValid.value) return
  if (!isPhoneNumberValid.value) {
    uni.showToast({ title: '请输入有效的手机号', icon: 'none' })
    return
  }

  try {
    const { data, error } = await useApiFetch('/auth/sendSms')
      .post({ mobile: phoneNumber.value, actionType: 'bindMobile' })
      .json()

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        uni.showToast({ title: '验证码已发送', icon: 'success' })
        startCountdown()
      } else {
        uni.showToast({ title: data.value.msg || '发送失败', icon: 'none' })
      }
    } else {
      uni.showToast({ title: error.value || '发送失败', icon: 'none' })
    }
  } catch (err) {
    console.error('发送验证码失败:', err)
    uni.showToast({ title: '发送失败，请重试', icon: 'none' })
  }
}

function startCountdown() {
  isCountingDown.value = true
  countdown.value = 60
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(countdownTimer)
      countdownTimer = null
      isCountingDown.value = false
    }
  }, 1000)
}

async function handleBindMobile() {
  if (!isPhoneNumberValid.value) {
    uni.showToast({ title: '请输入有效的手机号', icon: 'none' })
    return
  }
  if (verificationCode.value.length !== 6) {
    uni.showToast({ title: '请输入6位验证码', icon: 'none' })
    return
  }

  try {
    const { data, error } = await bindMobile({
      mobile: phoneNumber.value,
      code: verificationCode.value,
    })

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        // 更新 token
        uni.setStorageSync('token', data.value.data.accessToken)
        uni.setStorageSync('refreshAfter', data.value.data.refreshAfter)
        uni.setStorageSync('accessExpire', data.value.data.accessExpire)
        
        // 刷新用户信息
        await userStore.fetchUserInfo()
        
        uni.showToast({ title: '绑定成功', icon: 'success' })
        closeBindMobilePopup()
      } else {
        uni.showToast({ title: data.value.msg || '绑定失败', icon: 'none' })
      }
    } else {
      uni.showToast({ title: error.value || '绑定失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('绑定手机号失败:', err)
    uni.showToast({ title: '绑定失败，请重试', icon: 'none' })
  }
}

// 实名认证 - 发送验证码
async function sendRealNameVerificationCode() {
  if (isRealNameCountingDown.value || !isRealNamePhoneValid.value) return
  if (!isRealNamePhoneValid.value) {
    uni.showToast({ title: '请输入有效的手机号', icon: 'none' })
    return
  }

  try {
    const { data, error } = await useApiFetch('/auth/sendSms')
      .post({ mobile: realNamePhoneNumber.value, actionType: 'realName' })
      .json()

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        uni.showToast({ title: '验证码已发送', icon: 'success' })
        startRealNameCountdown()
      } else {
        uni.showToast({ title: data.value.msg || '发送失败', icon: 'none' })
      }
    } else {
      uni.showToast({ title: error.value || '发送失败', icon: 'none' })
    }
  } catch (err) {
    console.error('发送验证码失败:', err)
    uni.showToast({ title: '发送失败，请重试', icon: 'none' })
  }
}

function startRealNameCountdown() {
  isRealNameCountingDown.value = true
  realNameCountdown.value = 60
  realNameCountdownTimer = setInterval(() => {
    if (realNameCountdown.value > 0) {
      realNameCountdown.value--
    } else {
      clearInterval(realNameCountdownTimer)
      realNameCountdownTimer = null
      isRealNameCountingDown.value = false
    }
  }, 1000)
}

// 实名认证 - 提交
async function handleRealNameAuth() {
  if (!isRealNameValid.value) {
    uni.showToast({ title: '请输入有效的姓名', icon: 'none' })
    return
  }
  if (!isIdCardValid.value) {
    uni.showToast({ title: '请输入有效的身份证号', icon: 'none' })
    return
  }
  if (!isRealNamePhoneValid.value) {
    uni.showToast({ title: '请输入有效的手机号', icon: 'none' })
    return
  }
  if (realNameVerificationCode.value.length !== 6) {
    uni.showToast({ title: '请输入6位验证码', icon: 'none' })
    return
  }
  if (!isAgreed.value) {
    uni.showToast({ title: '请先同意用户协议', icon: 'none' })
    return
  }

  try {
    const { data, error } = await realNameAuth({
      name: realName.value,
      id_card: idCard.value,
      mobile: realNamePhoneNumber.value,
      code: realNameVerificationCode.value,
    })

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        uni.showToast({ title: '认证成功', icon: 'success' })
        // 刷新代理状态信息
        await agentStore.fetchAgentStatus()
        closeRealNameAuthPopup()
      } else {
        uni.showToast({ title: data.value.msg || '认证失败', icon: 'none' })
      }
    } else {
      uni.showToast({ title: error.value || '认证失败，请重试', icon: 'none' })
    }
  } catch (err) {
    console.error('实名认证失败:', err)
    uni.showToast({ title: '认证失败，请重试', icon: 'none' })
  }
}

async function getRevenueData() {
  if (!isAgent.value) return
  try {
    const { data, error } = await getRevenueInfo()
    if (data.value?.code === 200 && !error.value) revenueData.value = data.value.data
  } catch (e) {
    console.error(e)
  }
}

onBeforeMount(async () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) userStore.updateUserInfo(typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo)
    const agentInfo = uni.getStorageSync('agentInfo')
    if (agentInfo) agentStore.updateAgentInfo(typeof agentInfo === 'string' ? JSON.parse(agentInfo) : agentInfo)
    const token = uni.getStorageSync('token')
    if (token && isLoggedIn.value) await agentStore.fetchAgentStatus()
  } catch (e) {
    console.error(e)
  }
})

onMounted(() => {
  if (isAgent.value) getRevenueData()
})

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  if (realNameCountdownTimer) {
    clearInterval(realNameCountdownTimer)
    realNameCountdownTimer = null
  }
})
</script>

<template>
  <view class="box-border min-h-screen">
    <view class="flex flex-col p-4 space-y-6">
      <view
        class="profile-section rounded-xl p-0.5"
        :class="isAgent ? levelGradient.cardBorder : 'bg-gray-200'"
      >
        <view class="rounded-xl bg-white p-6">
          <view class="flex items-center gap-4 mb-4">
            <view class="relative">
              <view class="overflow-hidden rounded-full p-0.5" :class="levelGradient.border">
                <image
                  :src="userAvatar || getDefaultAvatar()"
                  class="h-20 w-20 rounded-full border-4 border-white block"
                  mode="aspectFill"
                />
              </view>
              <view v-if="isAgent" class="absolute -bottom-2 -right-2">
                <view
                  class="flex items-center justify-center rounded-full px-3 py-1 text-xs font-bold text-white shadow-sm"
                  :class="levelGradient.badge"
                >
                  {{ levelNamesMap[level] || levelNamesMap[1] }}
                </view>
              </view>
            </view>
            <view class="flex-1 space-y-1">
              <view class="text-2xl font-bold text-gray-800">
                {{ !isLoggedIn ? '点击登录' : mobile ? mobile : isWeChat ? '微信用户' : '未绑定手机号' }}
              </view>
              <view v-if="isLoggedIn && !mobile && isWeChat" class="text-sm text-blue-500" @click.stop="openBindMobilePopup">
                绑定手机号
              </view>
              <view v-if="isLoggedIn && mobile && !isAgent" class="text-sm text-blue-500" @click.stop="toRegister">
                点击申请成为代理
              </view>
              <view v-if="isAgent" class="font-bold" :class="levelGradient.text">ID: {{ agentCode }}</view>
            </view>
            <view v-if="isAgent" class="text-right">
              <view class="text-sm mb-1 text-gray-500">余额</view>
              <view class="text-2xl font-bold text-blue-500">¥ {{ (revenueData?.balance || 0).toFixed(2) }}</view>
            </view>
          </view>
          <template v-if="isAgent">
            <view class="grid grid-cols-3 gap-3 mb-4 pt-4 border-t border-gray-200">
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">累计收益</view>
                <view class="text-base font-semibold text-gray-800">¥ {{ (revenueData?.total_earnings || 0).toFixed(2) }}</view>
              </view>
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">风险保障金</view>
                <view class="text-base font-semibold text-gray-800">¥ {{ (revenueData?.frozen_balance || 0).toFixed(2) }}</view>
              </view>
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">累计提现</view>
                <view class="text-base font-semibold text-gray-800">¥ {{ (revenueData?.withdrawn_amount || 0).toFixed(2) }}</view>
              </view>
            </view>
            <view class="grid grid-cols-2 gap-3">
              <button
                class="text-white rounded-full py-1.5 px-4 shadow-md flex items-center justify-center text-base bg-blue-500"
                @click.stop="toWithdraw"
              >
                <wd-icon name="gold-coin" class="mr-1" />
                提现
              </button>
              <button
                class="bg-white border border-gray-200 rounded-full py-1.5 px-4 shadow-sm flex items-center justify-center text-base text-gray-500"
                @click.stop="toWithdrawDetails"
              >
                <wd-icon name="notes" class="mr-1" />
                提现记录
              </button>
            </view>
          </template>
        </view>
      </view>

      <view v-if="isAgent" class="rounded-xl shadow-lg bg-white p-5">
        <view class="grid grid-cols-2 gap-4">
          <view class="pr-4 border-r border-gray-200">
            <view class="flex items-center mb-3">
              <wd-icon name="balance-list" class="text-lg mr-2" color="#e6a23c" />
              <text class="text-base font-bold text-gray-800">我的推广收益</text>
            </view>
            <view class="text-center mb-3">
              <view class="text-xl font-bold text-amber-500">¥ {{ (revenueData?.commission_total || 0).toFixed(2) }}</view>
              <view class="text-sm mt-0.5 text-gray-500">累计总收益</view>
            </view>
            <view class="grid grid-cols-2 gap-2 mb-3">
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">今日</view>
                <view class="text-base font-semibold text-amber-500">¥ {{ (revenueData?.commission_today || 0).toFixed(2) }}</view>
              </view>
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">本月</view>
                <view class="text-base font-semibold text-amber-500">¥ {{ (revenueData?.commission_month || 0).toFixed(2) }}</view>
              </view>
            </view>
            <view class="flex items-center justify-center text-sm font-semibold text-amber-500" @click="goToPromoteDetail">
              <text>查看明细</text>
              <text class="ml-1 text-base">→</text>
            </view>
          </view>
          <view class="pl-4">
            <view class="flex items-center mb-3">
              <wd-icon name="gift" class="text-lg mr-2" color="#07c160" />
              <text class="text-base font-bold text-gray-800">下级推广收益</text>
            </view>
            <view class="text-center mb-3">
              <view class="text-xl font-bold text-green-500">¥ {{ (revenueData?.rebate_total || 0).toFixed(2) }}</view>
              <view class="text-sm mt-0.5 text-gray-500">累计总收益</view>
            </view>
            <view class="grid grid-cols-2 gap-2 mb-3">
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">今日</view>
                <view class="text-base font-semibold text-green-500">¥ {{ (revenueData?.rebate_today || 0).toFixed(2) }}</view>
              </view>
              <view class="text-center">
                <view class="text-sm mb-1 text-gray-500">本月</view>
                <view class="text-base font-semibold text-green-500">¥ {{ (revenueData?.rebate_month || 0).toFixed(2) }}</view>
              </view>
            </view>
            <view class="flex items-center justify-center text-sm font-semibold text-green-500" @click="goToRebateDetail">
              <text>查看明细</text>
              <text class="ml-1 text-base">→</text>
            </view>
          </view>
        </view>
      </view>

      <view class="bg-white rounded-xl shadow-sm p-4">
        <view class="grid grid-cols-4 gap-4">
          <view v-if="isAgent && level !== 3" class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toUpgrade">
            <image src="/static/me/sjdl.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">升级代理</text>
          </view>
          <view v-if="isAgent && level === 3" class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toUpgradeSubordinate">
            <image src="/static/me/sjxj.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">调整级别</text>
          </view>
          <view v-if="isAgent" class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toInviteCodeManage">
            <image src="/static/me/yqmgl.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">邀请码管理</text>
          </view>
          <view v-if="isAgent" class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toRealNameAuth">
            <image src="/static/me/smrz.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">实名认证</text>
            <text v-if="isRealName" class="text-xs text-green-500">已认证</text>
          </view>
          <view v-if="isAgent" class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toAgentReport">
            <image src="/static/me/tgcxjl.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">推广查询记录</text>
          </view>
          <view class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toUserAgreement">
            <image src="/static/me/yhxy.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">用户协议</text>
          </view>
          <view class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toPrivacyPolicy">
            <image src="/static/me/yszc.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">隐私政策</text>
          </view>
          <!-- 小程序内使用原生客服按钮；其他端跳转客服页 -->
          <!-- #ifdef MP-WEIXIN -->
          <button
            open-type="contact"
            class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg w-full min-h-0 leading-none border-0 bg-transparent p-0 m-0 after:border-0"
          >
            <image src="/static/me/lxkf.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">联系客服</text>
          </button>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <view class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toService">
            <image src="/static/me/lxkf.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">联系客服</text>
          </view>
          <!-- #endif -->
          <view class="flex flex-col items-center justify-center gap-2 py-4 rounded-lg" @click="toAgentSystemGuide">
            <image src="/static/me/yhxy.svg" class="w-8 h-8" mode="aspectFit" />
            <text class="text-xs text-gray-700 font-medium text-center">代理系统指南</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 提现 - 公众号二维码弹窗 -->
    <view v-if="showWithdrawQrPopup" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click.self="closeWithdrawQrPopup">
      <view class="mx-4 rounded-2xl bg-white p-6 shadow-xl" @click.stop>
        <view class="text-center text-lg font-bold text-gray-800 mb-2">提现须知</view>
        <view class="text-center text-sm text-gray-500 mb-4">请长按识别下方公众号二维码，联系客服办理提现</view>
        <image
          src="/static/me/official_qrcode.jpg"
          class="w-56 h-56 mx-auto block rounded-lg bg-gray-100"
          mode="aspectFit"
          show-menu-by-longpress
        />
        <button
          class="mt-4 w-full rounded-full py-2.5 text-base font-medium text-white bg-blue-500"
          @click="closeWithdrawQrPopup"
        >
          关闭
        </button>
      </view>
    </view>

    <!-- 绑定手机号弹窗 -->
    <view v-if="showBindMobilePopup" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click.self="closeBindMobilePopup">
      <view class="mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl" @click.stop>
        <view class="text-center text-lg font-bold text-gray-800 mb-4">绑定手机号</view>
        
        <view class="mb-4">
          <view class="text-sm text-gray-600 mb-2">手机号</view>
          <input
            v-model="phoneNumber"
            type="number"
            placeholder="请输入手机号"
            maxlength="11"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg text-base focus:border-blue-500 focus:outline-none"
          />
        </view>

        <view class="mb-4">
          <view class="text-sm text-gray-600 mb-2">验证码</view>
          <view class="flex gap-2">
            <input
              v-model="verificationCode"
              type="number"
              placeholder="请输入验证码"
              maxlength="6"
              class="flex-1 px-4 py-3 border border-gray-300 rounded-lg text-base focus:border-blue-500 focus:outline-none"
            />
            <button
              :disabled="isCountingDown || !isPhoneNumberValid"
              :class="[
                'px-4 py-3 rounded-lg text-sm font-medium whitespace-nowrap',
                isCountingDown || !isPhoneNumberValid
                  ? 'bg-gray-200 text-gray-400'
                  : 'bg-blue-500 text-white'
              ]"
              @click="sendVerificationCode"
            >
              {{ isCountingDown ? `${countdown}秒` : '获取验证码' }}
            </button>
          </view>
        </view>

        <view class="flex gap-3">
          <button
            class="flex-1 rounded-lg py-3 text-base font-medium text-gray-700 bg-gray-100"
            @click="closeBindMobilePopup"
          >
            取消
          </button>
          <button
            class="flex-1 rounded-lg py-3 text-base font-medium text-white bg-blue-500"
            @click="handleBindMobile"
          >
            确定
          </button>
        </view>
      </view>
    </view>

    <!-- 实名认证弹窗 -->
    <view v-if="showRealNameAuthPopup" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click.self="closeRealNameAuthPopup">
      <view class="mx-4 w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl max-h-[90vh] overflow-y-auto" @click.stop>
        <view class="text-center text-lg font-bold text-gray-800 mb-4">实名认证</view>
        
        <view class="mb-4">
          <view class="text-sm text-gray-600 mb-2">姓名</view>
          <input
            v-model="realName"
            type="text"
            placeholder="请输入真实姓名"
            maxlength="20"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg text-base focus:border-blue-500 focus:outline-none"
          />
        </view>

        <view class="mb-4">
          <view class="text-sm text-gray-600 mb-2">身份证号</view>
          <input
            v-model="idCard"
            type="text"
            placeholder="请输入身份证号"
            maxlength="18"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg text-base focus:border-blue-500 focus:outline-none"
          />
        </view>

        <view class="mb-4">
          <view class="text-sm text-gray-600 mb-2">手机号</view>
          <input
            v-model="realNamePhoneNumber"
            type="number"
            placeholder="请输入手机号"
            maxlength="11"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg text-base focus:border-blue-500 focus:outline-none"
          />
        </view>

        <view class="mb-4">
          <view class="text-sm text-gray-600 mb-2">验证码</view>
          <view class="flex gap-2">
            <input
              v-model="realNameVerificationCode"
              type="number"
              placeholder="请输入验证码"
              maxlength="6"
              class="flex-1 px-4 py-3 border border-gray-300 rounded-lg text-base focus:border-blue-500 focus:outline-none"
            />
            <button
              :disabled="isRealNameCountingDown || !isRealNamePhoneValid"
              :class="[
                'px-4 py-3 rounded-lg text-sm font-medium whitespace-nowrap',
                isRealNameCountingDown || !isRealNamePhoneValid
                  ? 'bg-gray-200 text-gray-400'
                  : 'bg-blue-500 text-white'
              ]"
              @click="sendRealNameVerificationCode"
            >
              {{ isRealNameCountingDown ? `${realNameCountdown}秒` : '获取验证码' }}
            </button>
          </view>
        </view>

        <view class="mb-4">
          <view class="flex items-start gap-2">
            <wd-checkbox v-model="isAgreed" />
            <view class="text-xs text-gray-600 flex-1">
              我已阅读并同意
              <text class="text-blue-500" @click.stop="toUserAgreement">《用户协议》</text>
              和
              <text class="text-blue-500" @click.stop="toPrivacyPolicy">《隐私政策》</text>
            </view>
          </view>
        </view>

        <view class="flex gap-3">
          <button
            class="flex-1 rounded-lg py-3 text-base font-medium text-gray-700 bg-gray-100"
            @click="closeRealNameAuthPopup"
          >
            取消
          </button>
          <button
            class="flex-1 rounded-lg py-3 text-base font-medium text-white bg-blue-500"
            :class="{ 'opacity-50': !canSubmitRealName }"
            :disabled="!canSubmitRealName"
            @click="handleRealNameAuth"
          >
            提交认证
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped>
/* 小程序客服按钮：去除默认边框与背景，与菜单项一致 */
/* #ifdef MP-WEIXIN */
button[open-type='contact']::after {
  border: none;
}
/* #endif */
</style>
