<template>
  <view class="page fade-in">
    <view class="hero">
      <text class="hero-title">会员中心</text>
      <text class="hero-sub" v-if="isLoggedIn">
        当前：{{ currentPlanName }}
      </text>
      <text class="hero-sub" v-else>选择套餐，解锁全部功能</text>
    </view>

    <view class="plans">
      <!-- 免费版 -->
      <view class="plan-card free" :class="{ active: isLoggedIn && plan === 'free' }">
        <view class="plan-header">
          <text class="plan-name">免费版</text>
          <view class="plan-price"><text class="price-num">免费</text></view>
        </view>
        <view class="plan-features">
          <text class="feat">✓ 每日 {{ limits.interview.dailyFreeLimit || 3 }} 次 AI 模拟面试</text>
          <text class="feat">✓ 每场最多 {{ limits.interview.maxRoundsFree || 5 }} 轮 AI 对话</text>
          <text class="feat">✓ 基础面试报告</text>
          <text class="feat">✓ 简历诊断</text>
          <text class="feat">✓ 简历优化</text>
        </view>
        <view class="plan-status" v-if="isLoggedIn && plan === 'free'">当前使用</view>
        <view class="plan-status hint" v-else-if="!isLoggedIn">注册即用</view>
      </view>

      <!-- 成长版 -->
      <view class="plan-card growth recommended" :class="{ active: plan === 'growth' && isLoggedIn }">
        <view class="plan-badge">⭐ 推荐</view>
        <view class="plan-header">
          <text class="plan-name">成长版</text>
          <text class="plan-price"><text class="price-num">{{ priceText }}</text><text class="price-unit" v-if="plan !== 'growth' || !isLoggedIn">/月</text></text>
        </view>
        <view class="plan-features">
          <text class="feat">✓ 免费版全部权益</text>
          <text class="feat">✓ 无限面试次数</text>
          <text class="feat">✓ 每场最多 {{ limits.interview.maxRoundsVip || 10 }} 轮 AI 对话</text>
          <text class="feat">✓ 详细面试报告（四维评分）</text>
          <text class="feat">✓ 进步轨迹雷达图 + 打卡</text>
          <text class="feat">✓ 参考回答思路</text>
          <text class="feat">✓ 公司真题库</text>
        </view>
        <view class="plan-action" v-if="!isLoggedIn" @click="goLogin">登录后开通</view>
        <view class="plan-action owned" v-else-if="plan === 'growth'">✅ 已开通</view>
        <view class="plan-action" v-else @click="startPay">{{ priceText }} 立即开通</view>
      </view>
    </view>

    <!-- 支付弹窗 -->
    <view class="modal-overlay" v-if="showPayModal" @click="showPayModal = false">
      <view class="modal-content" @click.stop>
        <!-- 二维码支付（H5） -->
        <template v-if="!isMp && payCodeUrl">
          <text class="modal-title">微信扫码支付</text>
          <canvas canvas-id="payQrcode" class="qr-canvas"></canvas>
          <text class="modal-hint">请用微信扫码完成支付</text>
          <text class="modal-close" @click="showPayModal = false">取消支付</text>
        </template>
        <!-- JSAPI 支付（小程序） -->
        <template v-if="isMp">
          <text class="modal-title">微信支付</text>
          <text class="modal-hint">即将调起微信支付...</text>
        </template>
        <!-- 加载中 -->
        <text class="modal-title" v-if="!payCodeUrl && !isMp">正在创建支付...</text>
      </view>
    </view>

    <!-- 成功提示 -->
    <view class="pay-success" v-if="paySuccess">
      <text class="success-icon">🎉</text>
      <text class="success-text">开通成功！成长版已生效</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { api } from '../../config'
import UQRCode from 'uqrcodejs'

const isLoggedIn = ref(false)
const isMp = ref(false)
const plan = ref('free')
const currentPlanName = ref('免费版')
const paySuccess = ref(false)
const showPayModal = ref(false)
const payCodeUrl = ref('')
const priceText = ref('¥19.9')
const limits = ref({
  interview: { dailyFreeLimit: 3, maxRoundsFree: 5, maxRoundsVip: 10 },
  diagnosis: { dailyFreeLimit: 2 },
  optimize: { dailyFreeLimit: 2 },
  price: { monthly: 1990 },
})

const token = () => uni.getStorageSync('token') || ''

onMounted(async () => {
  // #ifdef MP-WEIXIN
  isMp.value = true
  // #endif

  const t = token()
  if (!t) return
  isLoggedIn.value = true

  try {
    const [sres, lres] = await Promise.all([
      uni.request({ url: api('/member/status'), method: 'GET', header: { 'Authorization': `Bearer ${t}` } }),
      uni.request({ url: api('/member/plans'), method: 'GET' }),
    ])
    if (sres.statusCode === 200) {
      const d = sres.data
      plan.value = d.plan || 'free'
      currentPlanName.value = d.planName || '免费版'
    }
    if (lres.statusCode === 200 && lres.data) {
      const d = lres.data
      if (d.interview) limits.value.interview = d.interview
      if (d.diagnosis) limits.value.diagnosis = d.diagnosis
      if (d.optimize) limits.value.optimize = d.optimize
      if (d.price) {
        limits.value.price = d.price
        priceText.value = `¥${(d.price.monthly / 100).toFixed(1)}`
      }
    }
  } catch (e) { /* ignore */ }
})

const goLogin = () => uni.navigateTo({ url: '/pages/login/login' })

/** 创建支付订单 */
const startPay = async () => {
  const t = token()
  if (!t) { uni.showToast({ title: '请先登录', icon: 'none' }); return }
  showPayModal.value = true

  try {
    if (isMp.value) {
      // 小程序：JSAPI 支付
      const res = await uni.request({
        url: api('/payment/jsapi'), method: 'POST',
        header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
      })
      if (res.statusCode === 200 && res.data?.payParams) {
        const pp = res.data.payParams
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: pp.timeStamp,
          nonceStr: pp.nonceStr,
          package: pp.package,
          signType: pp.signType,
          paySign: pp.paySign,
          success: () => checkPayResult(),
          fail: () => { showPayModal.value = false; uni.showToast({ title: '支付取消', icon: 'none' }) },
        })
      } else {
        showPayModal.value = false
        uni.showToast({ title: '创建订单失败', icon: 'none' })
      }
    } else {
      // H5：Native 二维码支付
      const res = await uni.request({
        url: api('/payment/create'), method: 'POST',
        header: { 'Authorization': `Bearer ${t}`, 'Content-Type': 'application/json' },
      })
      if (res.statusCode === 200 && res.data?.codeUrl) {
        payCodeUrl.value = res.data.codeUrl
        nextTick(() => {
          try {
            const ctx = uni.createCanvasContext('payQrcode')
            const uqrcode = new UQRCode()
            uqrcode.data = res.data.codeUrl
            uqrcode.size = 400
            uqrcode.margin = 20
            uqrcode.backgroundColor = '#FFFFFF'
            uqrcode.foregroundColor = '#000000'
            uqrcode.make()
            uqrcode.drawCanvas(ctx)
          } catch(e) { console.error('二维码生成失败', e) }
        })
      } else {
        showPayModal.value = false
        uni.showToast({ title: '支付服务暂不可用', icon: 'none' })
      }
    }
  } catch (e) {
    showPayModal.value = false
    uni.showToast({ title: '支付服务暂不可用', icon: 'none' })
  }
}

/** 支付成功后查询并更新状态 */
const checkPayResult = async () => {
  uni.showLoading({ title: '查询支付结果...' })
  try {
    await new Promise(r => setTimeout(r, 2000))
    const res = await uni.request({ url: api('/member/pay'), method: 'POST', header: { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' } })
    if (res.statusCode === 200 && res.data?.success) {
      paySuccess.value = true
      showPayModal.value = false
      plan.value = 'growth'
      currentPlanName.value = '成长版'
      uni.hideLoading()
      uni.showToast({ title: '🎉 开通成功！', icon: 'success' })
    } else {
      uni.hideLoading()
      uni.showToast({ title: '支付未完成，请稍后重试', icon: 'none' })
    }
  } catch { uni.hideLoading(); uni.showToast({ title: '查询失败', icon: 'none' }) }
}
</script>

<style scoped>
.page { min-height: 100vh; background: var(--color-bg); }
.hero { background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid), var(--color-gradient-end)); padding: 48rpx 32rpx 72rpx; border-radius: 0 0 48rpx 48rpx; }
.hero-title { font-size: 40rpx; font-weight: 700; color: #FFFFFF; }
.hero-sub { font-size: 22rpx; color: rgba(255,255,255,0.7); margin-top: 8rpx; display: block; }
.plans { padding: 0 32rpx; margin-top: -40rpx; display: flex; flex-direction: column; gap: 24rpx; }
.plan-card { background: #FFFFFF; border-radius: var(--radius-xl); padding: 32rpx; box-shadow: var(--shadow-sm); position: relative; }
.plan-card.growth { border: 2rpx solid var(--color-primary); }
.plan-card.active { border-color: var(--color-primary); }
.plan-badge { position: absolute; top: -12rpx; right: 24rpx; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #FFF; font-size: 20rpx; padding: 4rpx 20rpx; border-radius: var(--radius-round); font-weight: 600; }
.plan-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 20rpx; }
.plan-name { font-size: 30rpx; font-weight: 700; color: var(--color-text); }
.price-num { font-size: 44rpx; font-weight: 800; color: var(--color-primary); }
.price-unit { font-size: 22rpx; color: var(--color-text-tertiary); }
.plan-features { display: flex; flex-direction: column; gap: 10rpx; margin-bottom: 24rpx; }
.feat { font-size: 24rpx; color: var(--color-text-secondary); }
.plan-status { text-align: center; background: #F3F4F6; padding: 14rpx; border-radius: var(--radius-sm); font-size: 24rpx; color: var(--color-text-secondary); }
.plan-status.hint { background: transparent; color: var(--color-text-tertiary); }
.plan-action { text-align: center; background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-mid)); color: #FFF; padding: 20rpx; border-radius: var(--radius-md); font-size: 28rpx; font-weight: 600; }
.plan-action.owned { background: #ECFDF5; color: var(--color-success); }
.pay-success { margin: 24rpx 32rpx; background: #ECFDF5; border-radius: var(--radius-lg); padding: 32rpx; text-align: center; }
.success-icon { font-size: 48rpx; display: block; margin-bottom: 8rpx; }
.success-text { font-size: 28rpx; font-weight: 600; color: var(--color-success); }

/* 弹窗 */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 100; }
.modal-content { background: #FFF; border-radius: var(--radius-xl); padding: 40rpx; width: 70%; display: flex; flex-direction: column; align-items: center; gap: 20rpx; }
.modal-title { font-size: 28rpx; font-weight: 600; color: var(--color-text); }
.qr-canvas { width: 400rpx; height: 400rpx; background: #FFF; border-radius: var(--radius-md); }
.modal-hint { font-size: 22rpx; color: var(--color-text-tertiary); }
.modal-close { font-size: 22rpx; color: var(--color-text-tertiary); padding: 8rpx; }
</style>
