<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="page-title">{{ isWechatPay ? '微信扫码支付' : '支付宝扫码支付' }}</text>
      </view>
    </view>

    <!-- 支付内容 -->
    <view class="content">
      <!-- 订单信息 -->
      <view class="order-card">
        <text class="order-title">订单信息</text>
        <view class="order-info">
          <text class="info-label">商品</text>
          <text class="info-value">{{ orderInfo.planName || '-' }}</text>
        </view>
        <view class="order-info">
          <text class="info-label">订单号</text>
          <text class="info-value">{{ orderInfo.orderNo || '-' }}</text>
        </view>
        <view class="order-info highlight">
          <text class="info-label">应付金额</text>
          <text class="info-value price">¥{{ orderInfo.amount || 0 }}</text>
        </view>
      </view>

      <!-- 二维码 -->
      <view class="qrcode-section" v-if="qrcodeUrl">
        <text class="qrcode-hint">{{ isWechatPay ? '请使用微信扫码支付' : '请使用支付宝扫码支付' }}</text>
        <view class="qrcode-container">
          <image class="qrcode" :src="qrcodeImageUrl" mode="aspectFit" show-menu-by-longpress />
        </view>
        <text class="qrcode-tip">支付成功后页面将自动更新</text>
      </view>

      <!-- 加载中 -->
      <view class="loading-section" v-else-if="loading">
        <text class="loading-text">正在生成支付二维码...</text>
      </view>

      <!-- 错误 -->
      <view class="error-section" v-else-if="error">
        <text class="error-icon">!</text>
        <text class="error-text">{{ error }}</text>
        <button class="retry-btn" @click="generateQrcode">重新生成</button>
      </view>

      <!-- 操作按钮 -->
      <view class="actions">
        <button class="btn-secondary" @click="goBack">取消支付</button>
        <button class="btn-primary" @click="checkPaymentStatus">我已支付</button>
      </view>

      <!-- 提示 -->
      <view class="tips">
        <text class="tips-title">温馨提示</text>
        <text class="tips-text">• 请在24小时内完成支付</text>
        <text class="tips-text">• 支付成功后权益将自动到账</text>
        <text class="tips-text">• 如支付遇到问题，请联系客服</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { post, get } from '../../utils/request';

const orderInfo = ref<{
  orderNo: string;
  amount: number;
  planName: string;
}>({
  orderNo: '',
  amount: 0,
  planName: ''
});

const qrcodeUrl = ref('');
const isWechatPay = ref(false);
const loading = ref(false);
const error = ref('');
let checkTimer: ReturnType<typeof setInterval> | null = null;

// 生成二维码图片URL（使用在线二维码生成服务）
const qrcodeImageUrl = computed(() => {
  if (!qrcodeUrl.value) return '';
  // 使用 API 转换为图片
  return `https://api.powered.by/qrcode?text=${encodeURIComponent(qrcodeUrl.value)}&size=200`;
});

onMounted(async () => {
  // 获取 URL 参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  // #ifdef APP-PLUS
  const options = currentPage?.$page?.options || {};
  // #endif
  // #ifndef APP-PLUS
  const options = currentPage?.options || {};
  // #endif

  // 检测支付方式
  isWechatPay.value = options.qrcode && (options.qrcode.includes('weixin') || options.qrcode.includes('wxpay'));

  if (options.orderNo) {
    orderInfo.value.orderNo = options.orderNo;
    orderInfo.value.amount = parseFloat(options.amount) || 0;
    orderInfo.value.planName = decodeURIComponent(options.planName || '会员订阅');
    qrcodeUrl.value = decodeURIComponent(options.qrcode || '');
  } else if (options.planId) {
    // 需要先创建订单
    await generateOrderAndQrcode(parseInt(options.planId), options.method === 'wechat' ? 'wechat' : 'alipay');
  }

  // 开始轮询支付状态
  if (qrcodeUrl.value) {
    startPaymentCheck();
  }
});

async function generateOrderAndQrcode(planId: number, method: 'alipay' | 'wechat' = 'alipay') {
  loading.value = true;
  error.value = '';
  isWechatPay.value = method === 'wechat';

  try {
    const result = await post<{
      orderNo: string;
      amount: number;
      planName: string;
      qrcode: string;
    }>('/payment/create', {
      planId,
      paymentMethod: method
    });

    orderInfo.value = {
      orderNo: result.orderNo,
      amount: result.amount,
      planName: result.planName
    };
    qrcodeUrl.value = result.qrcode || '';

    // 开始轮询
    if (qrcodeUrl.value) {
      startPaymentCheck();
    }
  } catch (e: any) {
    error.value = e.message || '生成支付二维码失败';
  } finally {
    loading.value = false;
  }
}

async function generateQrcode() {
  if (orderInfo.value.orderNo) {
    // 已有订单号，重新获取二维码
    await generateOrderAndQrcode(0);
  }
}

function startPaymentCheck() {
  if (checkTimer) return;

  checkTimer = setInterval(async () => {
    try {
      const result = await get<{ status: string }>(`/payment/orders/${orderInfo.value.orderNo}`);
      if (result.status === 'paid') {
        clearInterval(checkTimer!);
        uni.showModal({
          title: '支付成功',
          content: '恭喜您，订阅已生效！',
          showCancel: false,
          success: () => {
            uni.switchTab({ url: '/pages/mine/index' });
          }
        });
      }
    } catch (e) {
      // 忽略错误，继续轮询
    }
  }, 3000);
}

function stopPaymentCheck() {
  if (checkTimer) {
    clearInterval(checkTimer);
    checkTimer = null;
  }
}

async function checkPaymentStatus() {
  try {
    const result = await get<{ status: string }>(`/payment/orders/${orderInfo.value.orderNo}`);
    if (result.status === 'paid') {
      uni.showModal({
        title: '支付成功',
        content: '恭喜您，订阅已生效！',
        showCancel: false,
        success: () => {
          stopPaymentCheck();
          uni.switchTab({ url: '/pages/mine/index' });
        }
      });
    } else {
      uni.showToast({ title: '暂未收到支付结果，请稍后', icon: 'none' });
    }
  } catch (e) {
    uni.showToast({ title: '查询失败，请稍后重试', icon: 'none' });
  }
}

function goBack() {
  stopPaymentCheck();
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/member/index' });
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  padding-top: env(safe-area-inset-top);
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  z-index: 100;
}

.nav-content {
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
}

.nav-left {
  width: 80rpx;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.page-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-right: 80rpx;
}

.content {
  padding-top: calc(120rpx + env(safe-area-inset-top));
  padding-left: 32rpx;
  padding-right: 32rpx;
}

.order-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.order-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24rpx;
  display: block;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1px solid #f3f4f6;
}

.order-info:last-child {
  border-bottom: none;
}

.order-info.highlight {
  margin-top: 16rpx;
  padding-top: 24rpx;
  border-top: 2rpx dashed #e5e7eb;
  border-bottom: none;
}

.info-label {
  font-size: 26rpx;
  color: #9ca3af;
}

.info-value {
  font-size: 26rpx;
  color: #1f2937;
}

.info-value.price {
  font-size: 36rpx;
  font-weight: 700;
  color: #ef4444;
}

.qrcode-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx;
  text-align: center;
  margin-bottom: 32rpx;
}

.qrcode-hint {
  font-size: 28rpx;
  color: #1f2937;
  margin-bottom: 32rpx;
  display: block;
}

.qrcode-container {
  width: 400rpx;
  height: 400rpx;
  margin: 0 auto 32rpx;
  background: #f9fafb;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qrcode {
  width: 360rpx;
  height: 360rpx;
}

.qrcode-tip {
  font-size: 24rpx;
  color: #9ca3af;
}

.loading-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 80rpx 40rpx;
  text-align: center;
  margin-bottom: 32rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #6b7280;
}

.error-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 80rpx 40rpx;
  text-align: center;
  margin-bottom: 32rpx;
}

.error-icon {
  width: 80rpx;
  height: 80rpx;
  background: #fef2f2;
  color: #ef4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  font-weight: bold;
  margin: 0 auto 24rpx;
}

.error-text {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 32rpx;
}

.retry-btn {
  padding: 16rpx 48rpx;
  background: #4f46e5;
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.actions {
  display: flex;
  gap: 24rpx;
  margin-bottom: 32rpx;
}

.btn-primary,
.btn-secondary {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  border: none;
}

.btn-primary {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: #ffffff;
}

.btn-secondary {
  background: #ffffff;
  color: #6b7280;
  border: 2rpx solid #e5e7eb;
}

.tips {
  background: #fef3c7;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 48rpx;
}

.tips-title {
  font-size: 24rpx;
  font-weight: 600;
  color: #92400e;
  display: block;
  margin-bottom: 12rpx;
}

.tips-text {
  font-size: 22rpx;
  color: #78350f;
  display: block;
  margin-bottom: 6rpx;
}
</style>
