<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">确认支付</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="payment-section">
        <text class="section-title">选择支付方式</text>
        <view class="payment-methods">
          <view
            class="payment-method"
            :class="{ active: paymentMethod === 'alipay' }"
            @click="paymentMethod = 'alipay'"
          >
            <view class="method-radio">
              <view class="radio-inner" v-if="paymentMethod === 'alipay'"></view>
            </view>
            <text class="method-icon">💙</text>
            <text class="method-name">支付宝</text>
          </view>
          <view
            class="payment-method"
            :class="{ active: paymentMethod === 'wechat' }"
            @click="paymentMethod = 'wechat'"
          >
            <view class="method-radio">
              <view class="radio-inner" v-if="paymentMethod === 'wechat'"></view>
            </view>
            <text class="method-icon">🟢</text>
            <text class="method-name">微信支付</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="actions">
        <button class="btn-secondary" @click="goBack">取消</button>
        <button class="btn-primary" @click="handlePay">确认支付</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 } from 'vue';
import { post, get } from '../../utils/request';

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

const planId = ref<number>(0);
const paymentMethod = ref<'alipay' | 'wechat'>('alipay');
let checkTimer: ReturnType<typeof setInterval> | null = null;

onMounted(() => {
  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

  if (options.planId) {
    planId.value = parseInt(options.planId);
    orderInfo.value.planName = decodeURIComponent(options.planName || '会员订阅');
    orderInfo.value.amount = parseFloat(options.amount) || 0;
  }
});

async function handlePay() {
  if (!planId.value) {
    uni.showToast({ title: '参数错误', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '创建订单...' });

    // #ifdef H5
    const returnUrl = `${window.location.origin}/#/pages/payment-result/index`;
    // #endif
    // #ifndef H5
    // App 端使用相对路径
    const returnUrl = `/#/pages/payment-result/index`;
    // #endif

    const orderResult = await post<{
      orderNo: string;
      amount: number;
      paymentUrl?: string;
      qrcode?: string;
      planName?: string;
    }>('/payment/create', {
      planId: planId.value,
      paymentMethod: paymentMethod.value,
      returnUrl
    });

    uni.hideLoading();

    orderInfo.value.orderNo = orderResult.orderNo;

    // 微信支付 - 显示二维码
    if (paymentMethod.value === 'wechat' && orderResult.qrcode) {
      uni.navigateTo({
        url: `/pages/alipay-qrcode/index?orderNo=${orderResult.orderNo}&amount=${orderResult.amount}&planName=${encodeURIComponent(orderResult.planName || orderInfo.value.planName)}&qrcode=${encodeURIComponent(orderResult.qrcode)}&method=wechat`
      });
      return;
    }

    // 支付宝 H5 跳转
    // #ifdef H5
    if (orderResult.paymentUrl) {
      uni.showToast({ title: '即将跳转支付宝...', icon: 'none' });
      setTimeout(() => {
        window.location.href = orderResult.paymentUrl!;
      }, 1000);
    }
    // #endif

    // 开发环境模拟
    // #ifndef H5
    uni.showModal({
      title: '模拟支付',
      content: `确认支付 ¥${orderResult.amount}？\n（开发环境模拟）`,
      success: async (res) => {
        if (res.confirm) {
          await mockPay(orderResult.orderNo);
        }
      },
    });
    // #endif
  } catch (error: any) {
    uni.hideLoading();
    console.error('创建订单失败:', error);
    uni.showToast({ title: error.message || '创建订单失败', icon: 'none' });
  }
}

async function mockPay(orderNo: string) {
  try {
    uni.showLoading({ title: '支付中...' });
    await post('/payment/mock', { orderNo });
    uni.hideLoading();
    uni.showModal({
      title: '支付成功',
      content: '恭喜您订阅成功！',
      showCancel: false,
      success: () => {
        uni.switchTab({ url: '/pages/mine/index' });
      }
    });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({ title: '支付失败', icon: 'none' });
  }
}

function goBack() {
  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;
}

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

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

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background: #f9fafb;
  border: 3rpx solid #e5e7eb;
  border-radius: 12rpx;
  transition: all 0.3s;
}

.payment-method.active {
  border-color: #667eea;
  background: #f0f2ff;
}

.method-radio {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #d1d5db;
  border-radius: 50%;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-method.active .method-radio {
  border-color: #667eea;
}

.radio-inner {
  width: 24rpx;
  height: 24rpx;
  background: #667eea;
  border-radius: 50%;
}

.method-icon {
  font-size: 36rpx;
  margin-right: 12rpx;
}

.method-name {
  font-size: 28rpx;
  color: #1f2937;
  flex: 1;
}

.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>
