<script setup>
/**
 * 升级代理：功能与 webview AgentUpgrade 一致（等级卡片、权益、确认开通），
 * 支付方式为微信支付（小程序内 uni.requestPayment + wxpay）。
 */
definePage({
  layout: 'PageLayout',
  style: {
    navigationBarTitleText: '升级代理',
    navigationStyle: 'default',
  },
})

import { ref, computed, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useAgentStore } from '@/stores/agentStore'
import { useUserStore } from '@/stores/userStore'
import { getLevelPrivilege, applyUpgrade } from '@/api/agent'
import { payment, paymentCheck } from '@/api/pay'
import { debugLog, debugError, showDebugInfo } from '@/utils/debug'

const agentStore = useAgentStore()
const userStore = useUserStore()
const { isAgent, level } = storeToRefs(agentStore)
const { isLoggedIn } = storeToRefs(userStore)

const goldPrice = ref(0)
const diamondPrice = ref(0)
const goldRebate = ref(0)
const diamondRebate = ref(0)
const levelPrivileges = ref([])
const loading = ref(true)
const isSubmitting = ref(false)
const selectedToLevel = ref(0)

const levelNames = { 1: '普通代理', 2: '黄金代理', 3: '钻石代理' }
const levelDescs = { 1: '基础代理特权', 2: '高级代理特权', 3: '尊享代理特权' }

const canUpgradeToGold = computed(() => level.value === 1)
const canUpgradeToDiamond = computed(() => level.value === 1 || level.value === 2)
const isMaxLevel = computed(() => (level.value || 1) >= 3)

function getLevelName(lvl) {
  return levelNames[lvl] || '普通代理'
}

function getLevelDesc(lvl) {
  return levelDescs[lvl] || '基础代理特权'
}

function getLevelBadgeClass(lvl) {
  const classes = { 1: 'badge-normal', 2: 'badge-gold', 3: 'badge-diamond' }
  return classes[lvl] || 'badge-normal'
}

function getPrivilegeInfo(targetLevel) {
  return levelPrivileges.value.find((p) => p.level === targetLevel)
}

function getUpgradeInfo(toLevel) {
  let upgradeFee = 0
  let rebateAmount = 0
  const cur = level.value || 1
  if (cur === 1) {
    if (toLevel === 2) {
      upgradeFee = goldPrice.value
      rebateAmount = goldRebate.value
    } else if (toLevel === 3) {
      upgradeFee = diamondPrice.value
      rebateAmount = diamondRebate.value
    }
  } else if (cur === 2 && toLevel === 3) {
    upgradeFee = diamondPrice.value
    rebateAmount = diamondRebate.value
  }
  return { upgradeFee, rebateAmount }
}

function formatAmount(value) {
  const num = Number(value ?? 0)
  if (Number.isNaN(num)) return '0'
  return num.toFixed(0)
}

function selectUpgrade(toLevel) {
  selectedToLevel.value = selectedToLevel.value === toLevel ? 0 : toLevel
}

async function loadPrivilegeInfo() {
  loading.value = true
  try {
    const { data, error } = await getLevelPrivilege()
    if (data.value?.code === 200 && !error.value) {
      const res = data.value.data
      levelPrivileges.value = res?.levels || []
      goldPrice.value = Number(res?.upgrade_to_gold_fee) || 0
      diamondPrice.value = Number(res?.upgrade_to_diamond_fee) || 0
      goldRebate.value = Number(res?.upgrade_to_gold_rebate) || 0
      diamondRebate.value = Number(res?.upgrade_to_diamond_rebate) || 0
    }
  } finally {
    loading.value = false
  }
}

async function pollPaymentStatus(orderNo, maxAttempts = 10) {
  for (let i = 0; i < maxAttempts; i++) {
    const { data } = await paymentCheck(orderNo)
    if (data.value?.code === 200 && data.value.data?.status === 'paid') return true
    await new Promise((r) => setTimeout(r, 1500))
  }
  return false
}

async function confirmUpgrade() {
  if (!selectedToLevel.value) {
    uni.showToast({ title: '请选择要升级的等级', icon: 'none' })
    return
  }
  const { upgradeFee } = getUpgradeInfo(selectedToLevel.value)
  try {
    await new Promise((resolve, reject) => {
      uni.showModal({
        title: '确认升级',
        content: `确定要升级为${getLevelName(selectedToLevel.value)}吗？\n升级费用：¥${Number(upgradeFee).toFixed(2)}`,
        success: (res) => (res.confirm ? resolve() : reject()),
      })
    })
  } catch {
    return
  }
  isSubmitting.value = true
  try {
    const { data: applyData, error: applyError } = await applyUpgrade({ to_level: selectedToLevel.value })
    if (applyData.value?.code !== 200 || applyError.value) {
      uni.showToast({ title: applyData.value?.msg || '申请升级失败', icon: 'none' })
      return
    }
    const applyRes = applyData.value.data
    const upgradeId = applyRes?.upgrade_id
    if (!upgradeId) {
      uni.showToast({ title: '提交成功', icon: 'success' })
      await agentStore.fetchAgentStatus()
      setTimeout(() => uni.navigateBack(), 1500)
      return
    }
    // 订单号由支付接口生成并返回，有 upgrade_id 即调起微信支付
    // 参考 qnc-mini 的实现：直接调用支付接口，后端会处理 openid 获取
    // 如果用户未绑定微信账号，后端会返回错误，此时再获取 code 重试
    const paymentParams = {
      id: upgradeId,
      pay_type: 'agent_upgrade',
      pay_method: 'wechat',
    }
    debugLog('支付请求参数:', paymentParams)
    
    let { data: payData, error: payError } = await payment(paymentParams)
    
    // 如果支付失败且提示需要 code，则获取 code 重试
    // #ifdef MP-WEIXIN
    if (payError.value || (payData.value?.code !== 200 && payData.value?.msg?.includes('未绑定'))) {
      debugLog('首次支付请求失败，尝试获取 code 重试:', payData.value?.msg || payError.value)
      try {
        const loginRes = await new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: resolve,
            fail: reject,
          })
        })
        if (loginRes.code) {
          paymentParams.code = loginRes.code
          debugLog('重新获取微信登录 code 并重试:', loginRes.code)
          // 重试支付请求
          const retryResult = await payment(paymentParams)
          payData = retryResult.data
          payError = retryResult.error
        }
      } catch (e) {
        debugError('获取微信登录 code 失败:', e)
        // 继续使用原始错误
      }
    }
    // #endif
    
    // 检查请求错误
    if (payError.value) {
      debugError('支付请求错误:', payError.value)
      uni.showToast({ title: payError.value || '获取支付参数失败', icon: 'none' })
      return
    }
    
    // 检查响应状态码
    if (payData.value?.code !== 200) {
      debugError('支付响应错误:', payData.value)
      const errorMsg = payData.value?.msg || '获取支付参数失败'
      debugError('错误详情:', {
        code: payData.value?.code,
        msg: errorMsg,
        fullResponse: payData.value,
      })
      uni.showToast({ title: errorMsg, icon: 'none' })
      return
    }
    
    // 检查响应数据结构
    const payRes = payData.value?.data
    debugLog('支付响应数据:', payRes)
    
    if (!payRes) {
      debugError('支付响应数据为空:', payData.value)
      uni.showToast({ title: '支付响应数据异常', icon: 'none' })
      return
    }
    
    // 获取支付参数和订单号
    // 后端返回字段：prepay_data, prepay_id, order_no
    const prepayData = payRes.prepay_data
    const prepayId = payRes.prepay_id
    const payOrderNo = payRes.order_no
    
    debugLog('支付参数解析:', { prepayData, prepayId, payOrderNo })
    
    // 验证订单号（后端必须返回）
    if (!payOrderNo) {
      debugError('支付响应缺少订单号:', payRes)
      uni.showToast({ title: '支付参数异常，缺少订单号', icon: 'none' })
      return
    }

    // 检查支付参数
    if (!prepayData) {
      debugError('支付参数为空:', {
        prepayData,
        prepayId,
        payOrderNo,
        fullResponse: payRes,
        responseMsg: payData.value?.msg,
      })
      
      // 检查错误信息，如果是 code 相关错误，提示用户
      const errorMsg = payRes?.msg || payData.value?.msg || ''
      if (errorMsg.includes('invalid code') || errorMsg.includes('code') || errorMsg.includes('OpenID')) {
        uni.showToast({
          title: '微信授权已过期，请重新打开页面',
          icon: 'none',
          duration: 3000,
        })
      } else if (prepayId) {
        // 如果返回了 prepay_id，说明可能是 APP 支付或其他支付方式
        uni.showToast({
          title: '当前环境不支持此支付方式，请使用微信小程序打开',
          icon: 'none',
        })
      } else {
        uni.showToast({
          title: errorMsg || '支付参数异常，请重试或联系客服',
          icon: 'none',
          duration: 3000,
        })
      }
      return
    }

    // 参考 qnc-mini 的实现方式，使用条件编译区分不同平台
    // prepay_data 可能是对象或直接就是支付参数
    const paymentData = prepayData.prepay_data || prepayData

    // 支付成功回调处理
    const handlePaymentSuccess = async () => {
      const paid = await pollPaymentStatus(payOrderNo)
      if (paid) {
        uni.showToast({ title: '支付成功', icon: 'success' })
        await agentStore.fetchAgentStatus()
        setTimeout(() => uni.navigateBack(), 1500)
      } else {
        uni.showToast({ title: '支付处理中，请稍后查看', icon: 'none' })
        await agentStore.fetchAgentStatus()
        uni.navigateBack()
      }
    }

    // 支付失败回调处理
    const handlePaymentFail = (err) => {
      if (err.errMsg?.includes('cancel')) {
        uni.showToast({ title: '已取消支付', icon: 'none' })
      } else {
        uni.showToast({ title: err.errMsg || '支付失败', icon: 'none' })
      }
    }

    // #ifdef MP-WEIXIN
    // 微信小程序支付：使用顶层参数
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: String(paymentData.timeStamp || paymentData.timestamp || ''),
      nonceStr: paymentData.nonceStr || paymentData.nonce_str || '',
      package: paymentData.package || '',
      signType: paymentData.signType || paymentData.sign_type || 'MD5',
      paySign: paymentData.paySign || paymentData.pay_sign || '',
      success: handlePaymentSuccess,
      fail: handlePaymentFail,
    })
    // #endif

    // #ifdef APP-PLUS
    // APP 支付：使用 orderInfo 对象
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: {
        appid: paymentData.appid,
        noncestr: paymentData.nonceStr || paymentData.nonce_str,
        package: paymentData.package,
        partnerid: paymentData.partnerid,
        prepayid: paymentData.prepayid,
        timestamp: paymentData.timeStamp || paymentData.timestamp,
        sign: paymentData.paySign || paymentData.sign,
      },
      success: handlePaymentSuccess,
      fail: handlePaymentFail,
    })
    // #endif

    // #ifdef H5
    // H5 微信支付：使用 WeixinJSBridge
    if (typeof WeixinJSBridge !== 'undefined') {
      WeixinJSBridge.invoke('getBrandWCPayRequest', paymentData, function (result) {
        if (result.err_msg === 'get_brand_wcpay_request:ok') {
          handlePaymentSuccess()
        } else {
          handlePaymentFail({ errMsg: result.err_msg || '支付失败' })
        }
      })
    } else {
      uni.showToast({ title: '当前环境不支持微信支付', icon: 'none' })
    }
    // #endif
  } catch (e) {
    console.error(e)
    uni.showToast({ title: '申请升级失败，请重试', icon: 'none' })
  } finally {
    isSubmitting.value = false
  }
}

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/service/index' })
    // #endif
  } else {
    uni.navigateTo({ url: '/pages/service/index' })
  }
}


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

onMounted(() => {
  if (!isLoggedIn.value) return
  if (!isAgent.value) return
  loadPrivilegeInfo()
  if (level.value === 1) selectedToLevel.value = 2
  else if (level.value === 2) selectedToLevel.value = 3
})
</script>

<template>
  <view class="page-wrap">
    <!-- 未登录 / 非代理 -->
    <view v-if="!isLoggedIn" class="rounded-xl shadow-lg bg-white p-6 text-center mx-4 mt-4">
      <view class="text-gray-600">正在登录中，请稍候...</view>
    </view>
    <view v-else-if="!isAgent" class="rounded-xl shadow-lg bg-white p-6 text-center mx-4 mt-4">
      <view class="text-gray-600 mb-4">请先注册成为代理</view>
      <wd-button type="primary" block @click="toRegister">注册成为代理</wd-button>
    </view>

    <template v-else>
      <view v-if="loading" class="p-4">
        <view class="rounded-xl shadow-lg bg-white p-6">
          <wd-skeleton :row="4" />
        </view>
      </view>

      <template v-else>
        <!-- 当前等级卡片 -->
        <view class="px-4 pt-4">
          <view class="rounded-xl shadow-lg bg-white p-6">
            <view class="flex items-center gap-4">
              <view class="level-badge" :class="getLevelBadgeClass(level)">
                {{ getLevelName(level) }}
              </view>
              <view class="flex-1">
                <view class="flex justify-between items-start gap-2">
                  <view>
                    <view class="text-lg font-bold text-gray-800">当前等级</view>
                    <view class="text-sm mt-1 text-gray-500">{{ getLevelDesc(level) }}</view>
                  </view>
                  <view v-if="getPrivilegeInfo(level)" class="space-y-1 text-sm text-right text-gray-700">
                    <view class="flex items-center gap-1 justify-end">
                      <text>设置查询价最高{{ getPrivilegeInfo(level).max_set_price }}元</text>
                      <wd-icon name="check" size="14" color="#f59e0b" />
                    </view>
                    <view class="flex items-center gap-1 justify-end">
                      <text>邀请黄金代理，奖励{{ getPrivilegeInfo(level).invite_gold_reward }}元</text>
                      <wd-icon name="check" size="14" color="#f59e0b" />
                    </view>
                    <view class="flex items-center gap-1 justify-end">
                      <text>邀请钻石代理，奖励{{ getPrivilegeInfo(level).invite_diamond_reward }}元</text>
                      <wd-icon name="check" size="14" color="#f59e0b" />
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 升级选项 -->
        <view class="px-4 mt-4 mb-32">
          <view class="text-lg font-bold mb-4 text-amber-800">选择升级等级</view>

          <!-- 黄金代理选项 -->
          <view
            v-if="canUpgradeToGold"
            class="rounded-xl shadow-lg mb-4 bg-white p-6 border-2"
            :class="selectedToLevel === 2 ? 'border-amber-400' : 'border-transparent'"
            @click="selectUpgrade(2)"
          >
            <view class="flex justify-between items-center mb-4">
              <view class="flex items-center gap-2">
                <wd-icon name="medal" size="20" color="#f59e0b" />
                <text class="text-lg font-bold text-gray-800">黄金代理</text>
                <wd-icon v-if="selectedToLevel === 2" name="check" size="20" color="#f59e0b" />
              </view>
              <view class="text-right">
                <view class="text-xs mb-1 text-gray-500">升级费用</view>
                <view class="text-2xl font-bold text-amber-500">¥{{ goldPrice }}</view>
              </view>
            </view>
            <view v-if="getPrivilegeInfo(2)" class="space-y-2">
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>设置查询价最高{{ getPrivilegeInfo(2).max_set_price }}元</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>查询底价降低{{ formatAmount(getPrivilegeInfo(2).price_reduction) }}元每单</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>下级代理查询奖励最高{{ getPrivilegeInfo(2).subordinate_reward_max }}元每单</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>邀请黄金代理奖励{{ getPrivilegeInfo(2).invite_gold_reward }}元</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>邀请钻石代理奖励{{ getPrivilegeInfo(2).invite_diamond_reward }}元</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>更多权益敬请期待</text>
              </view>
            </view>
          </view>

          <!-- 钻石代理选项 -->
          <view
            v-if="canUpgradeToDiamond"
            class="rounded-xl shadow-lg mb-4 bg-white p-6 border-2"
            :class="selectedToLevel === 3 ? 'border-amber-400' : 'border-transparent'"
            @click="selectUpgrade(3)"
          >
            <view class="flex justify-between items-center mb-4">
              <view class="flex items-center gap-2">
                <wd-icon name="medal" size="20" color="#f59e0b" />
                <text class="text-lg font-bold text-gray-800">钻石代理</text>
                <wd-icon v-if="selectedToLevel === 3" name="check" size="20" color="#f59e0b" />
              </view>
              <view class="text-right">
                <view class="text-xs mb-1 text-gray-500">升级费用</view>
                <view class="text-2xl font-bold text-amber-500">¥{{ diamondPrice }}</view>
              </view>
            </view>
            <view v-if="getPrivilegeInfo(3)" class="space-y-2">
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>升级费用¥{{ formatAmount(getUpgradeInfo(3).upgradeFee) }}</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>设置查询价最高{{ getPrivilegeInfo(3).max_set_price }}元</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>查询底价降低{{ formatAmount(getPrivilegeInfo(3).price_reduction) }}元每单</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>下级代理查询奖励最高{{ getPrivilegeInfo(3).subordinate_reward_max }}元每单</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>邀请黄金代理奖励{{ getPrivilegeInfo(3).invite_gold_reward }}元</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>邀请钻石代理奖励{{ getPrivilegeInfo(3).invite_diamond_reward }}元</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>调整下级代理级别权限</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>系统内白名单权限</text>
              </view>
              <view class="flex items-center gap-2 text-sm text-gray-700">
                <wd-icon name="check" size="14" color="#f59e0b" />
                <text>更多权益敬请期待</text>
              </view>
            </view>
          </view>

          <!-- 已是最高等级 -->
          <view
            v-if="isMaxLevel"
            class="rounded-xl shadow-lg bg-white p-8 text-center"
          >
            <wd-icon name="medal" size="48" color="#f59e0b" />
            <view class="text-lg font-bold mt-4 text-gray-800">您已是最高等级</view>
            <view class="text-sm mt-2 text-gray-500">钻石代理享有最高权益</view>
          </view>
        </view>

        <!-- 底部固定按钮 -->
        <view
          v-if="!isMaxLevel && !loading"
          class="fixed bottom-0 left-0 right-0 bg-white border-t border-amber-100 p-4 safe-area-bottom"
        >
          <view class="flex items-center gap-3">
            <wd-button
              v-if="serviceUrl"
              size="small"
              custom-class="flex-shrink-0"
              custom-style="background-color: #fef3c7; color: #92400e; border: 1px solid #fde68a;"
              @click="toService"
            >
              <wd-icon name="service" class="mr-1" />
              联系客服
            </wd-button>
            <wd-button
              type="primary"
              block
              :disabled="!selectedToLevel"
              :loading="isSubmitting"
              custom-style="background: linear-gradient(135deg, #f59e0b, #d97706); border: none;"
              @click="confirmUpgrade"
            >
              确认开通
            </wd-button>
          </view>
        </view>
      </template>
    </template>
  </view>
</template>

<style scoped>
.page-wrap {
  min-height: 100vh;
  background: linear-gradient(to bottom, #fef3c7, #fef9e7);
  padding-bottom: env(safe-area-inset-bottom);
}

.level-badge {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  color: white;
  flex-shrink: 0;
}

.badge-normal {
  background-color: #6b7280;
}

.badge-gold {
  background-color: #f59e0b;
}

.badge-diamond {
  background-color: #f59e0b;
}

.space-y-1 > view + view,
.space-y-2 > view + view {
  margin-top: 4px;
}

.space-y-2 > view + view {
  margin-top: 8px;
}

.safe-area-bottom {
  padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
}
</style>
