<template>
  <!-- 会员弹窗 — 通过 Teleport 挂载到 body -->
  <Teleport to="body">
    <!-- 遮罩层 — 点击关闭弹窗 -->
    <div v-if="modelValue" class="member-dialog-overlay" @click="$emit('update:modelValue', false)">
      <!-- 弹窗主体 — 阻止点击冒泡 -->
      <div class="member-dialog" @click.stop>

        <!-- 顶部标题行 -->
        <div class="member-dialog__header">
          <div class="member-dialog__header-left">
            <h2 class="member-dialog__title">会员中心</h2>
            <p class="member-dialog__subtitle">解锁更多求职功能，让投递更高效</p>
          </div>
          <div class="member-dialog__header-right">
            <!-- 联系客服（hover显示二维码） -->
            <span class="member-dialog__contact-wrap">
              <span class="member-dialog__contact">联系客服</span>
              <div class="member-dialog__contact-qr">
                <img src="@/assets/images/nav/kg-qcCode.png" alt="客服二维码" />
                <div class="member-dialog__contact-qr-arrow"></div>
              </div>
            </span>
            <span class="member-dialog__close" @click="$emit('update:modelValue', false)">✕</span>
          </div>
        </div>

        <!-- 套餐选择区域 -->
        <div class="member-dialog__plans">
          <div
            v-for="plan in plans"
            :key="plan.key"
            class="member-dialog__plan-card"
            :class="{ 'member-dialog__plan-card--active': selectedPlan === plan.key }"
            @click="selectedPlan = plan.key"
          >
            <!-- 推荐标签 -->
            <div v-if="plan.recommend" class="member-dialog__plan-recommend"><svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
              <g clip-path="url(#clip0_180_2594)">
                <path d="M0.872709 4.61946C0.867714 4.56192 0.874732 4.50398 0.893317 4.44931C0.911903 4.39464 0.94165 4.34442 0.980672 4.30186C1.01969 4.25929 1.06714 4.2253 1.11999 4.20204C1.17285 4.17878 1.22996 4.16676 1.28771 4.16675H2.08333C2.19384 4.16675 2.29982 4.21065 2.37796 4.28879C2.4561 4.36693 2.5 4.47291 2.5 4.58341V8.54175C2.5 8.65225 2.4561 8.75823 2.37796 8.83637C2.29982 8.91451 2.19384 8.95841 2.08333 8.95841H1.63208C1.5278 8.95844 1.42729 8.91936 1.35042 8.84889C1.27355 8.77842 1.2259 8.68168 1.21688 8.57779L0.872709 4.61946ZM3.75 4.45321C3.75 4.27904 3.85833 4.1232 4.01563 4.04904C4.35917 3.88696 4.94438 3.56133 5.20833 3.12112C5.54854 2.55362 5.61271 1.52841 5.62313 1.29362C5.62458 1.26071 5.62375 1.22779 5.62813 1.19529C5.68458 0.788414 6.46979 1.26362 6.77083 1.76612C6.93438 2.03862 6.95521 2.39675 6.93813 2.67654C6.91958 2.97571 6.83188 3.26466 6.74583 3.55175L6.5625 4.16362H8.82438C8.88875 4.16362 8.95225 4.17853 9.0099 4.20719C9.06754 4.23585 9.11776 4.27748 9.15662 4.32881C9.19547 4.38014 9.22191 4.43977 9.23384 4.50303C9.24578 4.56629 9.2429 4.63145 9.22542 4.69341L8.10667 8.65508C8.08197 8.74245 8.02941 8.81937 7.95698 8.87413C7.88455 8.92888 7.79622 8.95848 7.70542 8.95841H4.16667C4.05616 8.95841 3.95018 8.91451 3.87204 8.83637C3.7939 8.75823 3.75 8.65225 3.75 8.54175V4.45321Z" fill="white" stroke="white" stroke-width="0.833333" stroke-linecap="round" stroke-linejoin="round"/>
              </g>
              <defs>
                <clipPath id="clip0_180_2594">
                  <rect width="10" height="10" fill="white"/>
                </clipPath>
              </defs>
            </svg>
              推荐</div>
            <!-- 套餐名称 -->
            <div class="member-dialog__plan-name">{{ plan.name }}</div>
            <!-- 价格行 -->
            <div class="member-dialog__plan-price">
              <span class="member-dialog__plan-price-symbol">¥</span>
              <span class="member-dialog__plan-price-num">{{ plan.priceInt }}</span>
              <span v-if="plan.originalPrice" class="member-dialog__plan-original-price">{{ plan.originalPrice }}</span>
            </div>
            <!-- 标签描述（接口tag字段） -->
            <div class="member-dialog__plan-daily mt4">{{ plan.tag }}</div>
          </div>
        </div>

        <!-- 会员权益区域 -->
        <div class="member-dialog__benefits">
          <h3 class="member-dialog__benefits-title">会员权益</h3>
          <div class="member-dialog__benefits-cards">
            <div class="member-dialog__benefit-card">
              <div class="member-dialog__benefit-icon">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <rect width="24" height="24" rx="12" fill="#EDF9FA"/>
                  <path d="M7 8h7v2H7V8zm0 3h10v2H7v-2zm0 3h5v2H7v-2z" fill="#52CAD1"/>
                </svg>
              </div>
              <div class="member-dialog__benefit-info">
                <span class="member-dialog__benefit-name">AI优化简历</span>
                <span class="member-dialog__benefit-desc">享受无限次数</span>
              </div>
            </div>
            <div class="member-dialog__benefit-card">
              <div class="member-dialog__benefit-icon">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <rect width="24" height="24" rx="12" fill="#EDF9FA"/>
                  <path d="M12 7l1.5 3 3.5.5-2.5 2.5.5 3.5L12 15l-3 1.5.5-3.5L7 10.5l3.5-.5L12 7z" fill="#52CAD1"/>
                </svg>
              </div>
              <div class="member-dialog__benefit-info">
                <span class="member-dialog__benefit-name">AI+投递助手</span>
                <span class="member-dialog__benefit-desc">会员专享</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付方式选择 -->
        <div class="member-dialog__payment">
          <span class="member-dialog__payment-label">选择支付方式</span>
          <div class="member-dialog__payment-methods">
            <div
              class="member-dialog__payment-item"
              :class="{ 'member-dialog__payment-item--wechat-active': selectedPayment === 'wechat' }"
              @click="selectedPayment = 'wechat'"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M14 8c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6 6 2.7 6 6z" fill="#07C160"/>
                <path d="M5.5 6.5c.5-.3 1.2-.1 1.5.4l.5 1 1.5-2c.3-.5 1-.6 1.5-.3.5.3.6 1 .3 1.5l-2.5 3.5c-.2.3-.5.4-.8.4-.3 0-.6-.1-.8-.4L5.2 8c-.3-.5-.2-1.2.3-1.5z" fill="white"/>
              </svg>
              <span class="member-dialog__payment-text member-dialog__payment-text--wechat">微信支付</span>
            </div>
            <div
              class="member-dialog__payment-item"
              :class="{ 'member-dialog__payment-item--alipay-active': selectedPayment === 'alipay' }"
              @click="selectedPayment = 'alipay'"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <rect width="16" height="16" rx="3" fill="#1677FF"/>
                <text x="4" y="12" fill="white" font-size="10" font-weight="bold">支</text>
              </svg>
              <span class="member-dialog__payment-text member-dialog__payment-text--alipay">支付宝支付</span>
            </div>
          </div>
        </div>

        <!-- 购买按钮 -->
        <button
          class="member-dialog__buy-btn"
          :class="{ 'member-dialog__buy-btn--active': selectedPayment }"
          @click="handleBuy"
        >购买会员</button>

      </div>
    </div>

    <!-- ==================== 扫码支付弹窗 ==================== -->
    <div v-if="showQrCode" class="member-dialog-overlay member-dialog-overlay--qrcode" @click="handleCloseQrCode">
      <div class="member-dialog member-dialog--qrcode" @click.stop>

        <!-- 顶部标题行 -->
        <div class="member-dialog__header">
          <div class="member-dialog__header-left">
            <h2 class="member-dialog__title">扫码支付</h2>
          </div>
          <div class="member-dialog__header-right">
            <span class="member-dialog__close" @click="handleCloseQrCode">✕</span>
          </div>
        </div>

        <!-- 二维码区域 -->
        <div class="member-dialog__qrcode-content">
          <!-- 支付宝：iframe 渲染支付表单 -->
          <div v-if="selectedPayment === 'alipay' && paymentFormHtml" class="member-dialog__qrcode-image">
            <iframe
              :srcdoc="paymentFormHtml"
              frameborder="0"
              class="member-dialog__payment-iframe"
              scrolling="auto"
            ></iframe>
          </div>
          <!-- 微信：使用 qrcode.js 渲染二维码 -->
          <div v-if="selectedPayment === 'wechat' && wechatCodeUrl" class="member-dialog__qrcode-image">
            <iframe
              :srcdoc="wechatQrHtml"
              frameborder="0"
              class="member-dialog__wechat-qr-iframe"
              scrolling="no"
            ></iframe>
          </div>

          <!-- 金额和提示 -->
          <div class="member-dialog__qrcode-price-row">
            <span class="member-dialog__qrcode-price">¥{{ currentPlan.priceInt }}</span>
            <span class="member-dialog__qrcode-tip">扫码完成支付</span>
          </div>

          <!-- 协议提示 -->
          <p class="member-dialog__qrcode-agreement">
            开通即代表同意 <a href="javascript:;" @click.prevent="openMemberAgreement">《会员服务协议》</a>
          </p>
        </div>

        <!-- 已支付成功按钮 -->
        <button class="member-dialog__paid-btn" @click="handleConfirmPaid">已支付成功</button>
      </div>
    </div>

    <!-- 协议预览弹窗 -->
    <AgreementPreviewDialog v-model="showAgreementDialog" code="ae8065i3" />
  </Teleport>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { fetchMemberProductList, createMemberOrder, fetchOrderDetail, type MemberProduct } from '@/api/member'
import AgreementPreviewDialog from '@/components/tools/AgreementPreviewDialog.vue'

/** 组件 Props — 控制弹窗显示/隐藏 */
const props = defineProps<{ modelValue: boolean }>()

/** 组件 Emits — 通知父组件更新 modelValue */
const emit = defineEmits<{ (e: 'update:modelValue', value: boolean): void }>()

const store = useStore()

// ==================== 类型定义 ====================

/** 套餐项类型（包含后端完整数据 + 前端展示字段） */
interface PlanItem {
  key: string
  name: string
  /** 整数价格（元），用于显示 */
  priceInt: string
  /** 划线价（元） */
  originalPrice: string
  /** 标签描述（接口tag字段，如"轻量体验"、"低至¥0.56/天"） */
  tag: string
  /** 是否推荐 */
  recommend?: boolean
  /** 后端原始数据，下单时使用 */
  raw: MemberProduct
}

// ==================== 状态 ====================

/** 当前选中的套餐 key */
const selectedPlan = ref('')

/** 当前选中的支付方式（wechat / alipay），默认不选 */
const selectedPayment = ref('')

/** 是否显示扫码支付弹窗 */
const showQrCode = ref(false)

/** 支付宝表单 HTML（用于 iframe 渲染） */
const paymentFormHtml = ref('')

/** 微信支付 code_url（用于生成二维码） */
const wechatCodeUrl = ref('')

/** 微信二维码 iframe 的 srcdoc HTML */
const wechatQrHtml = computed(() => {
  if (!wechatCodeUrl.value) return ''
  return `<!DOCTYPE html><html><head><meta charset="UTF-8"><script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"><\/script><style>body{display:flex;align-items:center;justify-content:center;margin:0;height:100%;}</style></head><body><div id="qrcode"></div><script>new QRCode(document.getElementById("qrcode"),{text:"${wechatCodeUrl.value}",width:210,height:210,colorDark:"#000000",colorLight:"#ffffff",correctLevel:QRCode.CorrectLevel.H});<\/script></body></html>`
})

/** 当前订单ID */
const orderId = ref('')

/** 是否正在创建订单 */
const creatingOrder = ref(false)

/** 协议预览弹窗显示状态 */
const showAgreementDialog = ref(false)

// ==================== 监听 ====================

/** 监听弹窗开关 — 打开时锁定背景滚动，关闭时恢复并重置状态 */
watch(() => props.modelValue, (val) => {
  document.body.style.overflow = val ? 'hidden' : ''
  if (!val) {
    showQrCode.value = false
    selectedPayment.value = ''
    paymentFormHtml.value = ''
    wechatCodeUrl.value = ''
    orderId.value = ''
  }
})

// ==================== 计算属性 ====================

/** 当前选中的套餐对象 */
const currentPlan = computed(() => {
  return plans.value.find(p => p.key === selectedPlan.value) || plans.value[0] || { priceInt: '0', name: '', key: '', originalPrice: '', tag: '', raw: {} as MemberProduct }
})

// ==================== 数据 ====================

/** 套餐列表（从接口获取） */
const plans = ref<PlanItem[]>([])

/** 将后端商品数据转换为前端套餐项 */
function mapProductToPlan(product: MemberProduct): PlanItem {
  // 分转元，直接除以100不四舍五入
  const priceYuan = product.price / 100
  const originalPriceYuan = product.originalPrice ? product.originalPrice / 100 : 0
  // 直接使用接口返回的 productName 作为套餐名称
  const name = product.productName

  // 价格显示：如果是整数就不显示小数，否则保留实际小数
  const priceDisplay = Number.isInteger(priceYuan) ? String(priceYuan) : priceYuan.toFixed(2)
  const originalDisplay = originalPriceYuan > priceYuan
    ? `¥${Number.isInteger(originalPriceYuan) ? originalPriceYuan : originalPriceYuan.toFixed(2)}`
    : ''

  return {
    key: String(product.id),
    name,
    priceInt: priceDisplay,
    originalPrice: originalDisplay,
    tag: product.tag || '',
    recommend: product.isFeatured === 1,
    raw: product,
  }
}

/** 加载会员商品列表 */
async function loadMemberProducts() {
  try {
    const res = await fetchMemberProductList()
    if (res.data && res.data.length) {
      const sorted = [...res.data].sort((a, b) => a.sortOrder - b.sortOrder)
      plans.value = sorted.map(mapProductToPlan)
      // 默认选中推荐套餐（季卡），若无则选第一个
      const featured = plans.value.find(p => p.recommend)
      selectedPlan.value = featured ? featured.key : plans.value[0].key
    }
  } catch (e) {
    console.error('加载会员商品列表失败', e)
  }
}

/** 组件挂载时加载商品列表 */
onMounted(() => {
  loadMemberProducts()
})

// ==================== 事件处理 ====================

/** 点击购买会员按钮 */
async function handleBuy() {
  if (!selectedPayment.value) {
    ElMessage.warning('请选择付款方式')
    return
  }
  if (creatingOrder.value) return
  const plan = currentPlan.value
  if (!plan || !plan.raw) return

  creatingOrder.value = true
  try {
    const payChannel = selectedPayment.value === 'alipay' ? 2 : 1
    const res = await createMemberOrder({
      productId: plan.key,
      payChannel,
    })
    if (res.data) {
      orderId.value = String(res.data.orderId)
      if (selectedPayment.value === 'wechat') {
        wechatCodeUrl.value = res.data.payData
        paymentFormHtml.value = ''
      } else {
        paymentFormHtml.value = res.data.payData
        wechatCodeUrl.value = ''
      }
      showQrCode.value = true
      // 【注释掉自动轮询，后续如需恢复取消注释即可】
      // confirmPaymentPolling()
    }
  } catch (e) {
    console.error('创建订单失败', e)
  } finally {
    creatingOrder.value = false
  }
}

// /** 轮询计时器 */
// let pollTimer: ReturnType<typeof setInterval> | null = null

// /**
//  * 自动轮询查询订单支付状态（已关闭，保留逻辑防止后续要用）
//  * 支付成功后自动关闭弹窗并刷新会员状态
//  */
// async function confirmPaymentPolling() {
//   const startTime = Date.now()
//   const timeout = 5 * 60 * 1000 // 5分钟超时
//   const interval = 500
//
//   if (pollTimer) {
//     clearInterval(pollTimer)
//     pollTimer = null
//   }
//
//   pollTimer = setInterval(async () => {
//     try {
//       const res = await fetchOrderDetail(orderId.value)
//       const status = res.data?.status
//
//       if (status === 1) {
//         clearInterval(pollTimer!)
//         pollTimer = null
//         showQrCode.value = false
//         ElMessage.success('开通成功')
//         emit('update:modelValue', false)
//         store.dispatch('loadMemberStatus')
//       } else if (status === 2 || status === 3) {
//         clearInterval(pollTimer!)
//         pollTimer = null
//         showQrCode.value = false
//         ElMessage.error('支付未成功，请重新下单')
//       } else if (Date.now() - startTime >= timeout) {
//         clearInterval(pollTimer!)
//         pollTimer = null
//         showQrCode.value = false
//         ElMessage.error('支付超时，请重新下单')
//       }
//     } catch (e) {
//       console.error('查询订单状态失败', e)
//     }
//   }, interval)
// }

/** 点击"已支付成功"按钮 — 手动查询一次订单状态 */
async function handleConfirmPaid() {
  if (!orderId.value) return
  try {
    const res = await fetchOrderDetail(orderId.value)
    const status = res.data?.status
    if (status === 1) {
      // 支付成功 — 关闭弹窗，刷新会员状态
      showQrCode.value = false
      ElMessage.success('开通成功')
      emit('update:modelValue', false)
      // 刷新 vuex 中的会员状态
      store.dispatch('loadMemberStatus')
    } else {
      // 未支付成功
      ElMessage.warning('未查询到支付订单，请再次确认')
    }
  } catch (e) {
    console.error('查询订单状态失败', e)
    ElMessage.error('查询失败，请稍后重试')
  }
}

/** 关闭扫码支付弹窗 */
function handleCloseQrCode() {
  showQrCode.value = false
}

/** 打开会员服务协议 */
function openMemberAgreement() {
  showAgreementDialog.value = true
}
</script>
