<template>
	<view class="container">
		<!-- 头部 -->
		<view class="header">
			<view class="header-left" @tap="goBack">
				<view class="back-button">
					<text class="wlIcon-fanhui1 text-white"></text>
				</view>
			</view>
			<view class="header-title text-white">{{$t('money.diamondRecharge')}}</view>
			<view class="header-right" @tap="goToDetail">
				<text class="text-white">{{$t('money.queryDetail')}}</text>
			</view>
		</view>
		
		<!-- 用户信息和钻石余额 -->
		<view class="user-info-card">
			<view class="user-avatar">
				<image :src="userAvatar" mode="aspectFill"></image>
			</view>
			<view class="user-info">
				<text class="user-name">{{userName}}</text>
				<text class="diamond-balance-text">{{$t('money.diamondBalance')}}: {{diamondBalance}}</text>
			</view>
		</view>
		
		<!-- 充值金额选择 -->
		<view class="recharge-section">
			<text class="section-title">{{$t('money.pleaseSelectAmount')}}</text>
			
			<!-- 快捷金额选择 -->
			<view class="quick-amount-grid" v-if="quickAmounts.length > 0">
				<view 
					class="amount-item" 
					v-for="(item, index) in quickAmounts" 
					:key="item.id || index"
					:class="{active: selectedQuickAmount && selectedQuickAmount.id === item.id}"
					@tap="selectQuickAmount(item)"
				>
					<view class="amount-item-content">
						<image class="diamond-icon-item" src="/static/imgs/icon/ic_diamond.png" mode="aspectFit"></image>
						<text class="diamond-label">{{$t('money.diamond')}}</text>
						<text class="diamond-number">{{item.number}}</text>
						<text class="amount-price">{{item.currency || ''}} {{item.money}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 汇率提示 -->
		<view class="exchange-rate-tip">
			<text>{{$t('money.exchangeRateTip')}}</text>
			<text>{{$t('money.pleaseReferToPayment')}}</text>
		</view>
		
		<!-- 支付方式列表（非 APP 平台显示） -->
		<!-- #ifndef APP-PLUS -->
		<view class="payment-methods">
			<view class="item" v-for="(item, index) in payList" :key="index">
				<text :class="'wlIcon-'+ item.type +'-pay'"></text>
				<view class="action">
					<text class="title">{{item.name}}</text>
					<view>{{item.describe}}</view>
				</view>
				<view class="radio" v-if="item.state" @tap="onSelect(index)">
					<text v-if="item.select" class="wlIcon-xuanze-danxuan text-white"></text>
					<text v-else class="wlIcon-xuanze text-gray-light"></text>
				</view>
				<view class="radio" v-else>
					<text class="wlIcon-xuanze-danxuan text-gray-light"></text>
				</view>
			</view>
		</view>
		<!-- #endif -->
		
		<!-- 充值按钮 -->
		<button class="recharge-btn" @tap="confirm()" :loading="loading" :disabled="!canRecharge">
			{{$t('money.recharge')}}
		</button>
		<!-- 充值说明协议（接口未返回 ID 时使用默认 6） -->
		<view class="recharge-instructions text-orange margin-top">
			<text @tap="onDetails(rechargeInstructionsId, $t('money.recharge-instructions'))">《{{$t('money.recharge-instructions')}}》</text>
		</view>
		<!-- 充值成功弹框 -->
		<insufficient-balance-modal
			:show="showSuccessModal"
			:title="$t('money.rechargeSuccess')"
			:subtitle="$t('money.rechargeSuccessTip', {amount: successAmount})"
			:buttonText="$t('common.confirm')"
			:maskClosable="true"
			@close="handleSuccessModalClose"
			@confirm="handleSuccessModalConfirm"
		></insufficient-balance-modal>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import InsufficientBalanceModal from '@/components/live-room/insufficient-balance-modal.vue';
import {
	getDiamondBalance,
	getDiamondList,
	getDiamondRecharge,
	notifyGooglePayPurchase,
	notifyAppleIAPPurchase,
	getAboutConfig,
	saveErrorLog
} from '@/features/mall/gateway/money.js';

export default {
	components: {
		InsufficientBalanceModal
	},
	data() {
		return {
			loading: false,
			disabled: false,
			diamondBalance: 0,
			diamondAmount: '',
			selectedQuickAmount: null, // 选中的快捷金额套餐
			quickAmounts: [], // 快捷金额选项列表（从接口获取）
			payList: [],
			googlePay: null, // Google Pay 插件实例
			isGooglePayInitialized: false, // Google Pay 是否已初始化
			iapChannel: null, // iOS IAP 支付通道（用于 finishTransaction）
			isIAPInitialized: false, // iOS IAP 是否已初始化
			showSuccessModal: false, // 是否显示充值成功弹框
			restoreFlag: false, // 是否需在 onShow 时调用恢复购买（丢单检测，文档建议）
			successAmount: 0, // 充值成功的金额
			iniData: { recharge_instructions_id: '' }, // 关于页配置（含充值说明文章ID）
			fromGift: false,
			giftLiveId: ''
		}
	},
	computed: {
		...mapState(['user']),
		canRecharge() {
			return this.selectedQuickAmount && !this.loading && !this.disabled;
		},
		userAvatar() {
			const kit = this.$appKit || this.$wanlshop;
			const avatar = this.user && this.user.avatar;
			if (kit && kit.oss && avatar) {
				return kit.oss(avatar, 100, 100, 2, 'avatar');
			}
			return avatar || '';
		},
		userName() {
			return this.user.nickname || this.user.username || this.$t('user.loginRegister');
		},
		// 充值说明文章ID，接口未返回时使用默认值 6
		rechargeInstructionsId() {
			return this.iniData.recharge_instructions_id || '6';
		}
	},
	onLoad(options) {
		this.fromGift = !!(options && (options.from === 'gift' || options.from === 'live'));
		this.giftLiveId = (options && options.liveId) ? String(options.liveId) : '';
		this.saveError('钻石充值页面加载', '页面开始加载');
		this.loadDiamondBalance();
		this.loadQuickAmounts();
		this.loadAboutData();
		this.initGooglePay();
		// 检查并处理待通知的订单（避免漏单）
		this.checkPendingOrders();
	},
	onShow() {
		// 文档：丢单检测 - 在页面 resume 时若 restoreFlag 为 true 则调用恢复购买（如用户绑卡后返回等）
		// #ifdef APP-PLUS
		const systemInfo = uni.getSystemInfoSync();
		if (systemInfo.platform && systemInfo.platform.toLowerCase() === 'ios' && this.restoreFlag && typeof plus !== 'undefined' && plus.payment) {
			plus.payment.getChannels((channels) => {
				let iap = null;
				for (let i in channels) {
					if (channels[i].id === 'appleiap') {
						iap = channels[i];
						break;
					}
				}
				if (iap) {
					iap.restoreComplateRequest({ manualFinishTransaction: true }, (results) => {
						this.restoreFlag = false;
						if (results && results.length > 0) {
							this.saveError('Apple IAP 恢复购买', `恢复 ${results.length} 笔订单`);
							results.forEach((transaction) => {
								const productId = transaction.productIdentifier || '';
								const packageItem = (this.quickAmounts || []).find(p => (p.ios_goods_id || '') === productId);
								if (packageItem) {
									this.notifyServerAppleIAPPurchase(packageItem, transaction, 0, iap);
								}
							});
						}
					});
				} else {
					this.restoreFlag = false;
				}
			});
		}
		// #endif
	},
	methods: {
		// 保存错误信息到服务器
		async saveError(title, error) {
			try {
				await saveErrorLog({
					title: title,
					error: error
				});
			} catch (err) {
				console.error('上报错误失败:', err);
			}
		},
		// 加载关于页配置（含充值说明文章ID recharge_instructions_id）
		async loadAboutData() {
			try {
				const data = await getAboutConfig();
				if (data) this.iniData = data;
			} catch (err) {
				console.error('加载关于配置失败:', err);
			}
		},
		// 加载快捷金额列表
		async loadQuickAmounts() {
			try {
				this.saveError('加载快捷金额列表', '开始加载快捷金额列表');
				let type = '';
				// #ifdef APP-PLUS
				const systemInfo = uni.getSystemInfoSync();
				const platform = systemInfo.platform.toLowerCase();
				if (platform === 'android') {
					type = 'android';
				} else if (platform === 'ios') {
					type = 'ios';
				}
				// #endif
				// #ifndef APP-PLUS
				type = 'android';
				// #endif

				const payload = await getDiamondList(type);
				let dataList = [];
				if (Array.isArray(payload)) {
					dataList = payload;
				} else if (payload && Array.isArray(payload.data)) {
					dataList = payload.data;
				}

				if (dataList.length > 0) {
					this.quickAmounts = dataList
						.filter(item => item.status === 1)
						.sort((a, b) => {
							if (a.sort !== b.sort) {
								return a.sort - b.sort;
							}
							return a.number - b.number;
						});
					this.saveError('加载快捷金额列表成功', `成功加载${this.quickAmounts.length}个套餐`);
				} else {
					console.warn('No valid data found in diamond list:', payload);
					this.saveError('加载快捷金额列表', '响应数据为空');
				}
			} catch (error) {
				console.error('Load quick amounts error:', error);
				this.saveError('加载快捷金额列表异常', JSON.stringify(error && error.message ? error.message : error));
			}
		},
		// 加载钻石余额
		async loadDiamondBalance() {
			try {
				this.saveError('加载钻石余额', '开始加载钻石余额');
				const data = await getDiamondBalance();
				if (typeof data === 'string' || typeof data === 'number') {
					this.diamondBalance = Number(data) || 0;
				} else if (data != null && typeof data === 'object') {
					if (data.diamond != null) {
						this.diamondBalance = Number(data.diamond) || 0;
					} else if (data.data != null && typeof data.data === 'object' && data.data.diamond != null) {
						this.diamondBalance = Number(data.data.diamond) || 0;
					} else {
						this.diamondBalance = Number(data) || 0;
					}
				} else {
					this.diamondBalance = 0;
				}
				this.saveError('加载钻石余额成功', `钻石余额: ${this.diamondBalance}`);
			} catch (error) {
				console.error('Load diamond balance error:', error);
				this.diamondBalance = 0;
				this.saveError('加载钻石余额异常', JSON.stringify(error && error.message ? error.message : error));
			}
		},
		// 初始化 Google Pay
		initGooglePay() {
			this.saveError('初始化支付', '开始初始化支付');
			// #ifdef APP-PLUS
			// 获取系统信息判断平台
			const systemInfo = uni.getSystemInfoSync();
			const platform = systemInfo.platform.toLowerCase();
			
			// Android 平台使用 Google Pay
			
			if (platform === 'android') {
				// 获取 Google Pay 插件实例
				this.googlePay = uni.requireNativePlugin('sn-googlepay5');
				if (!this.googlePay) {
					console.error('Google Pay 插件未找到');
					this.saveError('初始化支付失败', 'Google Pay 插件未找到');
					uni.showToast({
						title: this.$t('money.paymentPluginNotFound'),
						icon: 'none'
					});
					return;
				}
				
				// 初始化 Google Pay
				this.googlePay.init({
					autoReconnect: true,
					enableAutoServiceReconnection: true,
					enableExternalOffer: true,
					enableAlternativeBillingOnly: true
				}, (result) => {
					console.log('Google Pay init result:', result);
					if (result.code === 0) {
						this.isGooglePayInitialized = true;
						console.log('Google Pay 初始化成功');
						this.saveError('初始化支付成功', 'Google Pay 初始化成功');
					} else {
						console.error('Google Pay 初始化失败:', result.msg);
						this.saveError('初始化支付失败', result.msg || 'Google Pay 初始化失败');
						uni.showToast({
							title: result.msg || this.$t('money.paymentInitFailed'),
							icon: 'none'
						});
					}
				});
			}
			
			
			// iOS 平台使用原生 Apple IAP
			// #ifdef APP-IOS
			if (platform === 'ios') {
				this.initAppleIAP();
			}
			// #endif
			// #endif
			
			// #ifndef APP-PLUS
			// 非 APP 平台，使用其他支付方式
			this.initPaymentList();
			this.saveError('初始化支付', '非APP平台，使用其他支付方式');
			// #endif
		},
		// 初始化支付方式列表（非 Google Pay 时使用）
		initPaymentList() {
			let method = 'wap';
			// #ifdef APP-PLUS
			method = 'app';
			// #endif
			// #ifdef MP-BAIDU
			method = 'mini';
			// #endif
			// #ifdef MP-WEIXIN
			method = 'miniapp';
			// #endif
			// #ifdef MP-ALIPAY
			method = 'mini';
			// #endif
			// #ifdef MP-QQ
			method = 'mini';
			// #endif
			
			// 这里可以根据实际情况添加支付方式
			// 目前先留空，等待后续配置
			this.payList = [];
		},
		// 初始化 Apple IAP（iOS 平台）
		// 注意：iOS 支付通道在每次支付时动态获取，这里只做标记初始化完成
		initAppleIAP() {
			// #ifdef APP-PLUS-IOS
			this.saveError('初始化iOS支付', 'iOS支付将在支付时动态获取通道');
			// iOS 支付通道在每次支付时动态获取，不需要在初始化时保存
			// 直接标记为已初始化，允许进行支付
			this.isIAPInitialized = true;
			this.isGooglePayInitialized = true; // 使用相同的标志位，用于 confirm 方法检查
			console.log('Apple IAP 初始化完成（支付时动态获取通道）');
			// #endif
		},
		// 选择快捷金额
		selectQuickAmount(item) {
			this.selectedQuickAmount = item;
			this.diamondAmount = item.number.toString();
			this.saveError('选择快捷金额', `选择了套餐ID: ${item.id}, 钻石数量: ${item.number}, 价格: ${item.money}`);
		},
		// 清空输入
		emptyInput() {
			this.diamondAmount = '';
			this.selectedQuickAmount = null;
		},
		// 选择支付方式
		onSelect(key) {
			this.payList.map((value, index, array) => {
				if (index == key) {
					value.select = !value.select;
				} else {
					value.select = false;
				}
			});
		},
		// 确认充值
		confirm() {
			this.saveError('确认充值', '用户点击充值按钮');
			if (!this.canRecharge) {
				this.saveError('确认充值', '充值条件不满足，无法充值');
				return;
			}
			
			const amount = Number(this.diamondAmount);
				if (!amount || amount <= 0) {
				this.saveError('确认充值', '充值数量无效');
				uni.showToast({
					title: this.$t('money.pleaseEnterAmount'),
					icon: 'none'
				});
				return;
			}
			
			// #ifdef APP-PLUS
			// APP 平台使用 Google Play Billing / Apple IAP
			// 获取系统信息判断平台
			const systemInfo = uni.getSystemInfoSync();
			const platform = (systemInfo.platform || '').toLowerCase();
			const osName = (systemInfo.osName || '').toLowerCase();
			
			// iOS 平台直接进行支付（支付时动态获取通道）
			console.log('confirm - 平台检测:', {
				platform: platform,
				osName: osName,
				systemInfo: systemInfo
			});
			this.saveError('确认充值', `平台检测: ${platform}, osName: ${osName}, 套餐ID: ${this.selectedQuickAmount?.id || '无'}`);
			
			// 检查多种可能的 iOS 平台标识
			if (platform === 'ios' || osName === 'ios' || platform === 'iphone os' || systemInfo.platform === 'iOS') {
				console.log('confirm - 检测到iOS平台');
				if (this.selectedQuickAmount) {
					console.log('confirm - 调用payWithGooglePlay，套餐:', this.selectedQuickAmount);
					this.saveError('确认充值', `iOS平台，开始支付，套餐ID: ${this.selectedQuickAmount.id}`);
					this.payWithGooglePlay(this.selectedQuickAmount);
				} else {
					this.saveError('确认充值', '未选择充值套餐');
					uni.showToast({
						title: this.$t('money.pleaseSelectPackage'),
						icon: 'none'
					});
				}
				return;
			} else {
				// Android 平台检查 Google Pay 初始化
				if (!this.isGooglePayInitialized) {
					// 等待初始化完成（最多等待3秒）
					let waitCount = 0;
					const maxWait = 30; // 30次，每次100ms，总共3秒
					const checkInit = setInterval(() => {
						waitCount++;
						if (this.isGooglePayInitialized || waitCount >= maxWait) {
							clearInterval(checkInit);
							if (this.isGooglePayInitialized && this.selectedQuickAmount) {
								this.saveError('确认充值', `Android平台，支付初始化完成，套餐ID: ${this.selectedQuickAmount.id}`);
								this.payWithGooglePlay(this.selectedQuickAmount);
							} else {
								this.saveError('确认充值', '支付未初始化');
								uni.showToast({
									title: this.$t('money.paymentNotInitialized'),
									icon: 'none'
								});
							}
						}
					}, 100);
					return;
				}
			}
			
			// 已初始化，继续支付流程
			if (this.selectedQuickAmount) {
				this.saveError('确认充值', `APP平台，使用支付，套餐ID: ${this.selectedQuickAmount.id}`);
				this.payWithGooglePlay(this.selectedQuickAmount);
			} else {
				this.saveError('确认充值', '未选择充值套餐');
				uni.showToast({
					title: this.$t('money.pleaseSelectPackage'),
					icon: 'none'
				});
			}
			// #endif
			
			// #ifndef APP-PLUS
			// 非 APP 平台，使用其他支付方式
			let data = null;
			this.payList.map((value) => {
				if (value.select) {
					data = value;
				}
			});
			
			if (!data) {
				this.saveError('确认充值', '未选择支付方式，默认googleBilling支付');
				uni.showModal({
					content: this.$t('money.pleaseSelectPayMethod'),
					showCancel: false
				});
				return;
			}
			
			this.disabled = true;
			this.loading = true;
			
			// 如果选择了快捷金额套餐，使用套餐ID；否则使用手动输入的金额
			const packageId = this.selectedQuickAmount ? this.selectedQuickAmount.id : null;
			this.saveError('确认充值', `非APP平台，支付方式: ${data.type}, 金额: ${amount}, 套餐ID: ${packageId || '无'}`);
			this.wanlPay(data, amount, packageId);
			// #endif
		},
		// 发起支付
		async wanlPay(data, amount, packageId = null) {
			try {
				this.saveError('发起支付', `支付类型: ${data.type}, 金额: ${amount}, 套餐ID: ${packageId || '无'}`);
				// 获取小程序code
				// #ifdef MP
				uni.login({
					success: (e) => {
						this.saveError('发起支付', `获取小程序code成功: ${e.code}`);
						this.doPay(data, amount, packageId, e.code);
					},
					fail: (e) => {
						this.loading = false;
						this.disabled = false;
						this.saveError('发起支付失败', `无法获取微信code: ${e.errMsg}`);
						uni.showModal({
							content: this.$t('money.cannotGetWechatCode') + ': ' + e.errMsg,
							showCancel: false
						});
					}
				});
				// #endif
				// #ifndef MP
				this.doPay(data, amount, packageId);
				// #endif
			} catch (error) {
				this.loading = false;
				this.disabled = false;
				this.saveError('发起支付异常', JSON.stringify(error));
				uni.showToast({
					title: this.$t('money.paymentFailed'),
					icon: 'none'
				});
			}
		},
		// 执行支付
		async doPay(data, amount, packageId = null, code = null) {
			this.saveError('执行支付', `开始执行支付，类型: ${data.type}, 方法: ${data.method}, 金额: ${amount}`);
			
			// 判断支付平台类型（google=>谷歌支付,apple=>苹果支付）
			let payType = '';
			// #ifdef APP-PLUS
			const systemInfo = uni.getSystemInfoSync();
			const platform = systemInfo.platform.toLowerCase();
			if (platform === 'android') {
				payType = 'google';
			} else if (platform === 'ios') {
				payType = 'apple';
			}
			// #endif
			// #ifndef APP-PLUS
			// 非APP平台，使用原有支付类型
			payType = data.type;
			// #endif
			
			const requestData = {
				type: payType, // google=>谷歌支付,apple=>苹果支付
				order_type: 2, // 充值类型,1=>余额类型,2=>钻石充值
				method: data.method,
				code: code,
				diamond: amount
			};
			
			// 如果选择了套餐，传递套餐ID
			if (packageId) {
				requestData.package_id = packageId;
			}
			
			// await uni.request({
			// 	url: '/wanlshop/pay/recharge', // 钻石充值接口
			// 	method: 'POST',
			// 	data: requestData,
			// 	success: res => {
			// 		this.saveError('执行支付', `支付请求成功，类型: ${data.type}`);
			// 		// 处理支付结果
			// 		switch (data.type) {
			// 			case 'wechat':
			// 				if (data.method == 'wap') {
			// 					this.loading = false;
			// 					this.saveError('执行支付', '微信支付，跳转支付页面');
			// 					uni.showModal({
			// 						title: this.$t('money.wechatPay') || '微信支付',
			// 						content: this.$t('money.isPaymentCompleted') || '是否已完成支付？',
			// 						success: (res) => {
			// 							if (res.confirm) {
			// 								this.paySuccess(amount);
			// 							}
			// 						}
			// 					});
			// 					window.location.href = res.data;
			// 				}
			// 				break;
			// 			case 'alipay':
			// 				if (data.method == 'wap') {
			// 					this.loading = false;
			// 					this.disabled = false;
			// 					this.saveError('执行支付', '支付宝支付，跳转支付页面');
			// 					document.write(res.data);
			// 				}
			// 				break;
			// 			case 'balance':
			// 				// 余额支付
			// 				this.saveError('执行支付', '余额支付成功');
			// 				this.paySuccess(amount);
			// 				break;
			// 		}
			// 	},
			// 	fail: err => {
			// 		this.loading = false;
			// 		this.disabled = false;
			// 		this.saveError('执行支付失败', JSON.stringify(err));
			// 		uni.showToast({
			// 			title: err.errMsg || '支付失败，请重试',
			// 			icon: 'none'
			// 		});
			// 	}
			// });
		},
		// 使用 Google Play Billing 支付（Android）或 Apple IAP（iOS）
		payWithGooglePlay(packageItem) {
			// #ifdef APP-PLUS
			// 获取系统信息判断平台
			const systemInfo = uni.getSystemInfoSync();
			const platform = (systemInfo.platform || '').toLowerCase();
			const osName = (systemInfo.osName || '').toLowerCase();
			
			console.log('payWithGooglePlay - 平台信息:', {
				platform: platform,
				osName: osName,
				systemInfo: systemInfo
			});
			this.saveError('payWithGooglePlay', `平台: ${platform}, osName: ${osName}, 套餐ID: ${packageItem.id}`);
			
			// iOS 平台使用 Apple IAP（检查多种可能的平台标识）
			if (platform === 'ios' || osName === 'ios' || platform === 'iphone os' || systemInfo.platform === 'iOS') {
				console.log('检测到iOS平台，调用payWithAppleIAP');
				this.saveError('payWithGooglePlay', '检测到iOS平台，调用payWithAppleIAP');
				this.payWithAppleIAP(packageItem);
				return;
			}
			
			// Android 平台使用 Google Play Billing
			if (!this.googlePay || !this.isGooglePayInitialized) {
				this.saveError('Google Play支付失败', '支付未初始化');
				uni.showToast({
					title: this.$t('money.paymentNotInitializedShort'),
					icon: 'none'
				});
				return;
			}
			
			// 根据平台获取对应的商品ID（android_goods_id 是谷歌商品ID，ios_goods_id 是iOS商品ID）
			let productId = '';
			if (platform === 'android') {
				console.log('Android 平台使用 android_goods_id（谷歌商品ID）', packageItem.android_goods_id);
				// Android 平台使用 android_goods_id（谷歌商品ID）
				productId = packageItem.android_goods_id;
				
			} else {
				// 其他平台，优先使用 android_goods_id
				productId = packageItem.android_goods_id || packageItem.ios_goods_id;
			}
			
			// 判断商品ID是否非空且非空字符串
			if (!productId || (typeof productId === 'string' && productId.trim() === '')) {
				this.saveError('Google Play支付失败', `商品ID不存在，平台: ${platform}, 套餐ID: ${packageItem.id}`);
				uni.showToast({
					title: this.$t('money.productIdNotExists'),
					icon: 'none'
				});
				return;
			}
			
			this.loading = true;
			this.disabled = true;
			
			console.log('开始支付，商品ID:', productId, '平台:', platform);
			this.saveError('Google Play支付', `开始支付，商品ID: ${productId}, 平台: ${platform}, 套餐ID: ${packageItem.id}`);
			
			// 先调用 getPayInfo 获取支付信息
			this.getPayInfoAndPay(productId, packageItem);
			// #endif
			
			// #ifndef APP-PLUS
			this.saveError('Google Play支付', '仅支持 APP 平台');
			uni.showToast({
				title: this.$t('money.onlyAppPlatform'),
				icon: 'none'
			});
			// #endif
		},
		// 使用 Apple IAP 支付（iOS 平台）
		payWithAppleIAP(packageItem) {
			console.log('payWithAppleIAP 方法被调用，套餐信息:', JSON.stringify(packageItem));
			this.saveError('payWithAppleIAP', `方法被调用，套餐ID: ${packageItem.id}`);
			
			// 获取 iOS 商品ID
			const productId = packageItem.ios_goods_id;
			if (!productId || (typeof productId === 'string' && productId.trim() === '')) {
				this.saveError('Apple IAP支付失败', `商品ID不存在，套餐ID: ${packageItem.id}`);
				uni.showToast({
					title: this.$t('money.productIdNotExists'),
					icon: 'none'
				});
				return;
			}
			
			this.loading = true;
			this.disabled = true;
			
			console.log('开始iOS支付，商品ID:', productId, '套餐ID:', packageItem.id);
			this.saveError('Apple IAP支付', `开始支付，商品ID: ${productId}, 套餐ID: ${packageItem.id}`);
			
			// 获取用户ID（用于支付凭证）
			const userId = this.user.id || this.user.user_id || '1001';
			
			// 每次支付时动态获取支付通道（更可靠）
			let iap = null; // 保存应用内支付对象
			plus.payment.getChannels((channels) => {
				// 查找 appleiap 通道
				for (let i in channels) {
					const channel = channels[i];
					// 获取 id 为 'appleiap' 的 channel
					if (channel.id === 'appleiap') {
						iap = channel;
						break;
					}
				}
				
				if (!iap) {
					// 未找到 IAP 通道
					this.loading = false;
					this.disabled = false;
					console.error('Apple IAP 通道未找到');
					this.saveError('Apple IAP支付失败', 'Apple IAP 通道未找到');
					uni.showToast({
						title: this.$t('money.paymentChannelNotFound'),
						icon: 'none'
					});
					return;
				}
				
				// ids 数组中的项为 App Store Connect 配置的内购买项目产品ID（productId）
				const ids = [productId];
				
				// iap 为应用内支付对象，获取订单信息
				iap.requestOrder(ids, (e) => {
					// 获取订单信息成功回调方法
					console.log('requestOrder success:', JSON.stringify(e));
					this.saveError('Apple IAP支付', `获取订单信息成功: ${JSON.stringify(e)}`);
					
					// 发起支付（文档建议 manualFinishTransaction: true，服务器二次验证后再调用 finishTransaction 关闭订单）
					this.restoreFlag = true;
					this.iapChannel = iap;
					plus.payment.request(iap, {
						productid: productId,
						username: userId.toString(),
						manualFinishTransaction: true
					}, (result) => {
						// 支付成功，result 为 IAP商品交易信息对象 IAPTransaction
						// 需将返回的支付凭证传给后端进行二次认证，验证通过后调用 finishTransaction 关闭订单
						console.log('支付成功:', JSON.stringify(result));
						this.saveError('Apple IAP支付成功', `支付成功: ${JSON.stringify(result)}`);
						// 通知服务器支付成功（服务器验证通过后在此方法内调用 finishTransaction）
						this.notifyServerAppleIAPPurchase(packageItem, result, 0, iap);
					}, (e) => {
						this.restoreFlag = false;
						this.iapChannel = null;
						console.error('支付失败:', JSON.stringify(e));
						this.loading = false;
						this.disabled = false;
						this.saveError('Apple IAP支付失败', `支付失败: ${JSON.stringify(e)}`);
						if (e.code === 2) {
							uni.showToast({
								title: this.$t('money.paymentCancelled'),
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: e.message || this.$t('money.paymentFailed'),
								icon: 'none'
							});
						}
					});
				}, (e) => {
					// 获取订单信息失败回调方法
					console.error('requestOrder failed:', JSON.stringify(e));
					this.loading = false;
					this.disabled = false;
					this.saveError('Apple IAP支付失败', `获取订单信息失败: ${JSON.stringify(e)}`);
					uni.showToast({
						title: e.message || this.$t('money.getOrderInfoFailed'),
						icon: 'none'
					});
				});
			}, (e) => {
				// 获取 IAP 支付通道失败
				console.error('获取iap支付通道失败:', e.message);
				this.loading = false;
				this.disabled = false;
				this.saveError('Apple IAP支付失败', `获取iap支付通道失败: ${e.message}`);
				uni.showToast({
					title: this.$t('money.getPaymentChannelFailed'),
					icon: 'none'
				});
			});
		
			
			
		},
		// 获取支付信息并支付
		async getPayInfoAndPay(productId, packageItem) {
			try {
				this.saveError('获取支付信息', `开始获取支付信息，套餐ID: ${packageItem.id}, 钻石数量: ${packageItem.number}`);

				let payType = '';
				// #ifdef APP-PLUS
				const systemInfo = uni.getSystemInfoSync();
				const platform = systemInfo.platform.toLowerCase();
				if (platform === 'android') {
					payType = 'google';
				} else if (platform === 'ios') {
					payType = 'apple';
				}
				// #endif
				// #ifndef APP-PLUS
				payType = 'google';
				// #endif
				console.log('获取支付信息开始' + packageItem.number + '----' + packageItem.id);

				const payInfo = await getDiamondRecharge({
					type: payType,
					order_type: 2
				}) || {};

				this.saveError('获取支付信息成功', `accountId: ${payInfo.externalTransactionId}, is_switch_acknowledge: ${payInfo.is_switch_acknowledge}`);
				this.queryProductAndPay(productId, packageItem, payInfo.externalTransactionId || '', payInfo.is_switch_acknowledge || 0);
			} catch (error) {
				this.loading = false;
				this.disabled = false;
				console.log('获取支付信息失败：' + JSON.stringify(error && error.message ? error.message : error));
				this.saveError('获取支付信息异常', `异常: ${JSON.stringify(error && error.message ? error.message : error)}`);
				uni.showToast({
					title: '获取支付信息失败',
					icon: 'none'
				});
			}
		},
		// 查询商品并支付
		queryProductAndPay(productId, packageItem, accountId = '', isSwitchAcknowledge = 0) {
			// #ifdef APP-PLUS
				if (!this.googlePay || !this.isGooglePayInitialized) {
				this.loading = false;
				this.disabled = false;
				this.saveError('查询商品失败', 'Google Pay未初始化');
				uni.showToast({
					title: this.$t('money.paymentNotInitializedShort'),
					icon: 'none'
				});
				return;
			}
			console.log("获取支付信息："+`accountId: ${accountId}`);
			this.saveError('查询商品', `开始查询商品信息，商品ID: ${productId}`);
			
			// 查询商品信息（一次性商品使用 inapp）
			const queryParams = {
				inapp: [productId]
			};
			
			this.googlePay.querySku(queryParams, (queryResult) => {
				console.log('querySku result:', queryResult);
				this.saveError('查询商品', `查询结果: ${JSON.stringify(queryResult)}`);
				
				if (queryResult.code === 0) {
					// 查询成功，获取商品信息
					const products = queryResult.list || [];
					if (products.length === 0) {
						this.loading = false;
						this.disabled = false;
						this.saveError('查询商品失败', '未找到商品信息');
						uni.showToast({
							title: this.$t('money.productNotExists'),
							icon: 'none'
						});
						return;
					}
					
					const product = products[0];
					this.saveError('查询商品成功', `商品信息: ${JSON.stringify(product)}`);
					
					// 调用支付
					this.doGooglePay(product, productId, packageItem, accountId, isSwitchAcknowledge);
				} else {
					// 查询失败，仍然尝试支付（可能商品已存在但查询失败）
					this.saveError('查询商品失败', `查询失败但仍尝试支付: ${queryResult.msg || '未知错误'}`);
					this.doGooglePay(null, productId, packageItem, accountId, isSwitchAcknowledge);
				}
			});
			// #endif
		},
		// 执行 Google Play 支付
		doGooglePay(product, productId, packageItem, accountId = '', isSwitchAcknowledge = 0) {
			// #ifdef APP-PLUS
			// 构建支付参数
			const payParams = {
				productId: productId,
				accountId: accountId || ""
			};
			
			// 如果是订阅商品，需要添加 offerToken（当前是钻石充值，应该是一次性商品，但保留此逻辑）
			if (product && product.subscriptionOfferDetails && product.subscriptionOfferDetails.length > 0) {
				payParams.offerToken = product.subscriptionOfferDetails[0].offerToken;
				this.saveError('Google Play支付', `订阅商品，使用 offerToken: ${payParams.offerToken}`);
			}
			
				this.googlePay.payAll(payParams, (result) => {
			// 调用 Google Play 支付（参考测试文件的实现）
			// this.googlePay.pay(payParams, (result) => {
				console.log('Google Pay result:', result);
				
				if (result.code === 0) {
					var resultJson = JSON.stringify(result)
					// 支付成功
					this.saveError('Google Play支付成功', `支付成功，resultJson: ${resultJson}`);
					if (result.data && result.data.length > 0) {
						const purchaseData = result.data[0];
						console.log('购买数据:', JSON.stringify(purchaseData));
						
						// 一次性商品需要消耗（参考测试文件的逻辑）
						if (purchaseData.original && purchaseData.original.purchaseToken) {
							// 判断 is_switch_acknowledge，如果是 0 则不消费直接通知服务器
							if (isSwitchAcknowledge === 0) {
								this.saveError('Google Play支付', 'is_switch_acknowledge为0，不消费直接通知服务器');
								this.notifyServerPurchase(packageItem, purchaseData);
							} else {
								// 先消耗购买，然后通知服务器
								this.saveError('Google Play支付', '有purchaseToken，开始消耗购买');
								this.consumeAndNotifyServer(purchaseData, packageItem);
							}
						} else {
							// 如果没有 purchaseToken，直接通知服务器
							this.saveError('Google Play支付', '无purchaseToken，直接通知服务器');
							this.notifyServerPurchase(packageItem, purchaseData);
						}
					} else {
						// 没有购买数据，直接通知服务器
						console.warn('支付成功但没有购买数据');
						this.saveError('Google Play支付', '支付成功但没有购买数据');
						this.notifyServerPurchase(packageItem, null);
					}
				} else if (result.code === 1) {
					// 用户取消
					this.loading = false;
					this.disabled = false;
					this.saveError('Google Play支付', '用户取消支付');
					uni.showToast({
						title: this.$t('money.paymentCancelled'),
						icon: 'none'
					});
				} else {
					// 支付失败
					this.loading = false;
					this.disabled = false;
					this.saveError('Google Play支付失败', result.msg || '支付失败');
					uni.showToast({
						title: result.msg || this.$t('money.paymentFailed'),
						icon: 'none'
					});
				}
			});
			// #endif
			
			// #ifndef APP-PLUS
			this.saveError('Google Play支付', '仅支持 APP 平台');
			uni.showToast({
				title: this.$t('money.onlyAppPlatform'),
				icon: 'none'
			});
			// #endif
		},
		// 消耗购买并通知服务器
		consumeAndNotifyServer(purchaseData, packageItem) {
			var purchaseJson = JSON.stringify(purchaseData);
			var packageItemJson = JSON.stringify(packageItem);
			// #ifdef APP-PLUS
			this.saveError('消耗购买', `开始消耗购买，套餐ID: ${packageItemJson}, purchase: ${purchaseJson || '无'}`);
			if (!this.googlePay) {
				this.saveError('消耗购买', 'Google Pay插件不存在，直接通知服务器');
				this.notifyServerPurchase(packageItem, purchaseData);
				return;
			}
			
			// 消耗购买
			this.googlePay.consume({
				purchaseToken: purchaseData.original.purchaseToken
			}, (consumeResult) => {
				console.log('Consume result:', consumeResult);
				
				if (consumeResult.code === 0) {
					// 消耗成功，通知服务器
					this.saveError('消耗购买成功', `消耗成功，套餐ID: ${packageItem.id}`);
					this.notifyServerPurchase(packageItem, purchaseData);
				} else {
					// 消耗失败，仍然通知服务器（可能已经消耗过了）
					console.warn('Consume failed, but still notify server:', consumeResult.msg);
					this.saveError('消耗购买', `消耗失败但仍通知服务器: ${consumeResult.msg}`);
					this.notifyServerPurchase(packageItem, purchaseData);
				}
			});
			// #endif
		},
		// 保存待通知订单到本地存储（避免漏单）
		// platform: 'google' | 'apple'
		savePendingOrder(packageItem, purchaseData, retryCount = 0, platform = 'google') {
			try {
				const orderKey = `pending_order_${platform}_${packageItem.id}_${Date.now()}`;
				const orderData = {
					package_id: packageItem.id,
					diamond: packageItem.number,
					platform: platform,
					purchase_data: purchaseData ? JSON.stringify(purchaseData) : null,
					retry_count: retryCount,
					timestamp: Date.now(),
					package_item: JSON.stringify(packageItem)
				};
				uni.setStorageSync(orderKey, orderData);
				this.saveError('保存待通知订单', `订单已保存到本地，key: ${orderKey}, platform: ${platform}, 重试次数: ${retryCount}`);
			} catch (error) {
				console.error('保存待通知订单失败:', error);
				this.saveError('保存待通知订单失败', JSON.stringify(error));
			}
		},
		// 清除待通知订单
		clearPendingOrder(orderKey) {
			try {
				uni.removeStorageSync(orderKey);
				this.saveError('清除待通知订单', `订单已清除: ${orderKey}`);
			} catch (error) {
				console.error('清除待通知订单失败:', error);
			}
		},
		// 获取所有待通知订单
		getPendingOrders() {
			try {
				const allKeys = uni.getStorageInfoSync().keys || [];
				const pendingOrders = [];
				allKeys.forEach(key => {
					if (key.startsWith('pending_order_')) {
						const orderData = uni.getStorageSync(key);
						if (orderData) {
							pendingOrders.push({
								key: key,
								data: orderData
							});
						}
					}
				});
				return pendingOrders;
			} catch (error) {
				console.error('获取待通知订单失败:', error);
				return [];
			}
		},
		// 检查并处理待通知的订单
		async checkPendingOrders() {
			try {
				const pendingOrders = this.getPendingOrders();
				if (pendingOrders.length === 0) {
					return;
				}
				
				this.saveError('检查待通知订单', `发现 ${pendingOrders.length} 个待通知订单，开始处理`);
				
				// 延迟处理，等待初始化完成
				setTimeout(async () => {
					for (const order of pendingOrders) {
						// 检查订单是否过期（超过24小时则不再重试）
						const orderAge = Date.now() - order.data.timestamp;
						if (orderAge > 24 * 60 * 60 * 1000) {
							this.saveError('待通知订单过期', `订单已过期，清除: ${order.key}`);
							this.clearPendingOrder(order.key);
							continue;
						}
						
						// 如果重试次数超过5次，不再重试
						if (order.data.retry_count >= 5) {
							this.saveError('待通知订单重试次数超限', `订单重试次数已达上限，清除: ${order.key}`);
							this.clearPendingOrder(order.key);
							continue;
						}
						
						// 重新通知服务器（按平台区分 Google / Apple）
						try {
							const packageItem = JSON.parse(order.data.package_item);
							const purchaseData = order.data.purchase_data ? JSON.parse(order.data.purchase_data) : null;
							if (order.data.platform === 'apple') {
								await this.retryNotifyServerAppleIAPPurchase(packageItem, purchaseData, order.data.retry_count + 1, order.key);
							} else {
								await this.retryNotifyServer(packageItem, purchaseData, order.data.retry_count + 1, order.key);
							}
						} catch (error) {
							console.error('处理待通知订单失败:', error);
							this.saveError('处理待通知订单失败', JSON.stringify(error));
						}
					}
				}, 2000); // 延迟2秒，确保初始化完成
			} catch (error) {
				console.error('检查待通知订单失败:', error);
				this.saveError('检查待通知订单异常', JSON.stringify(error));
			}
		},
		// 重试通知服务器
		async retryNotifyServer(packageItem, purchaseData, retryCount, orderKey) {
			try {
				this.saveError('重试通知服务器', `第 ${retryCount} 次重试，套餐ID: ${packageItem.id}`);
				
				// 确保 purchase_data 是纯 JSON 字符串，避免双重编码
				let purchaseDataString = '';
				if (purchaseData) {
					// 如果是对象，直接序列化
					purchaseDataString = JSON.stringify(purchaseData);
				}
				
				// 验证 JSON 字符串格式
				try {
					if (purchaseDataString) {
						JSON.parse(purchaseDataString);
						this.saveError('重试通知服务器', `purchase_data 格式验证通过，长度: ${purchaseDataString.length}`);
					}
				} catch (e) {
					this.saveError('重试通知服务器警告', `purchase_data 格式验证失败: ${e.message}`);
				}
				
				// 检查 purchaseData 是否有必要的字段
				if (!purchaseData || !purchaseData.original) {
					this.saveError('重试通知服务器失败', `购买数据不完整，无法重试`);
					this.savePendingOrder(packageItem, purchaseData, retryCount);
					return;
				}
				
				await uni.request({
					url: '/wanlshop/callback/ingoogalpay',
					method: 'POST',
					header: {
						'Content-Type': 'application/json;charset=UTF-8'
					},
					dataType: 'json',
					data: {
						purchaseToken: purchaseData.original.purchaseToken,
						packageName: purchaseData.original.packageName,
						productId: purchaseData.original.productId,
						purchase_data: purchaseDataString
					},
					success: (res) => {
						if (res && res.res && res.res.code === 1) {
							// 通知成功，清除本地存储
							this.saveError('重试通知服务器成功', `第 ${retryCount} 次重试成功，套餐ID: ${packageItem.id}, 钻石数量: ${packageItem.number}`);
							this.clearPendingOrder(orderKey);
							// 调用支付成功方法，统一处理提示和余额刷新
							this.paySuccess(packageItem.number);
						} else {
							// 服务器验证失败，更新重试次数
							const errorMsg = (res && res.data && res.data.msg) || (res && res.res && res.res.msg) || '未知错误';
							this.saveError('重试通知服务器验证失败', `第 ${retryCount} 次重试验证失败: ${errorMsg}`);
							this.savePendingOrder(packageItem, purchaseData, retryCount);
						}
					},
					fail: (err) => {
						console.error('重试通知服务器失败:', err);
						// 请求失败，更新重试次数并继续保存
						this.saveError('重试通知服务器失败', `第 ${retryCount} 次重试失败: ${JSON.stringify(err)}`);
						this.savePendingOrder(packageItem, purchaseData, retryCount);
					}
				});
			} catch (error) {
				console.error('重试通知服务器异常:', error);
				this.saveError('重试通知服务器异常', `发生异常: ${JSON.stringify(error)}`);
				this.savePendingOrder(packageItem, purchaseData, retryCount);
			}
		},
		// 重试通知服务器 Apple IAP（待通知订单重试，需先获取 iap 通道再验证并 finishTransaction）
		async retryNotifyServerAppleIAPPurchase(packageItem, iapResult, retryCount, orderKey) {
			// #ifdef APP-PLUS
			if (typeof plus === 'undefined' || !plus.payment) {
				this.savePendingOrder(packageItem, iapResult, retryCount, 'apple');
				return;
			}
			let iap = null;
			plus.payment.getChannels((channels) => {
				for (let i in channels) {
					if (channels[i].id === 'appleiap') {
						iap = channels[i];
						break;
					}
				}
				if (!iap) {
					this.saveError('重试Apple IAP失败', '未找到 appleiap 通道');
					this.savePendingOrder(packageItem, iapResult, retryCount, 'apple');
					return;
				}
				const receiptData = iapResult.transactionReceipt || iapResult.receipt || '';
				const transactionIdentifier = iapResult.transactionIdentifier || '';
				const productIdentifier = iapResult.productIdentifier || packageItem.ios_goods_id;
				uni.request({
					url: '/wanlshop/callback/iniospay',
					method: 'POST',
					header: { 'Content-Type': 'application/json;charset=UTF-8' },
					dataType: 'json',
					data: {
						package_id: packageItem.id,
						diamond: packageItem.number,
						platform: 'apple',
						receipt_data: receiptData,
						transaction_identifier: transactionIdentifier,
						product_identifier: productIdentifier,
						iap_data: JSON.stringify(iapResult)
					},
					success: (res) => {
						if (res && res.res && res.res.code === 1) {
							this.restoreFlag = false;
							if (iap && typeof iap.finishTransaction === 'function') {
								iap.finishTransaction(iapResult, () => {}, () => {});
							}
							this.clearPendingOrder(orderKey);
							this.paySuccess(packageItem.number);
						} else {
							this.savePendingOrder(packageItem, iapResult, retryCount, 'apple');
						}
					},
					fail: () => {
						this.savePendingOrder(packageItem, iapResult, retryCount, 'apple');
					}
				});
			}, () => {
				this.savePendingOrder(packageItem, iapResult, retryCount, 'apple');
			});
			// #endif
		},
		// 通知服务器 Apple IAP 购买成功（iOS 平台）
		async notifyServerAppleIAPPurchase(packageItem, iapResult, retryCount = 0, iapChannel = null) {
			try {
				this.saveError('通知服务器Apple IAP购买', `开始通知服务器，iapResult:${JSON.stringify(iapResult)},套餐ID: ${packageItem.id}, 钻石数量: ${packageItem.number}, 重试次数: ${retryCount}`);
				const iap = iapChannel || this.iapChannel;
				this.savePendingOrder(packageItem, iapResult, retryCount, 'apple');

				const transactionIdentifier = iapResult.transactionIdentifier || '';
				const productIdentifier = iapResult.productIdentifier || packageItem.ios_goods_id;

				await notifyAppleIAPPurchase({
					package_id: packageItem.id,
					diamond: packageItem.number,
					platform: 'apple',
					receipt_data: iapResult.transactionReceipt,
					transaction_identifier: transactionIdentifier,
					product_identifier: productIdentifier,
					iap_data: JSON.stringify(iapResult)
				});

				this.restoreFlag = false;
				if (iap && typeof iap.finishTransaction === 'function') {
					iap.finishTransaction(iapResult, () => {
						this.saveError('Apple IAP关闭订单', 'finishTransaction 成功');
					}, (err) => {
						this.saveError('Apple IAP关闭订单失败', JSON.stringify(err));
					});
				}
				const pendingOrders = this.getPendingOrders();
				pendingOrders.forEach(order => {
					if (order.data.package_id === packageItem.id && order.data.platform === 'apple') {
						this.clearPendingOrder(order.key);
					}
				});
				this.saveError('通知服务器Apple IAP购买成功', `服务器验证成功，套餐ID: ${packageItem.id}, 钻石数量: ${packageItem.number}`);
				this.paySuccess(packageItem.number);
			} catch (error) {
				console.error('Notify server error:', error);
				this.saveError('通知服务器Apple IAP购买异常', `发生异常，已保存到本地等待重试: ${JSON.stringify(error && error.message ? error.message : error)}`);
				this.loading = false;
				this.disabled = false;
				uni.showToast({
					title: this.$t('money.paymentVerifying') || '支付验证中，请稍后',
					icon: 'none',
					duration: 3000
				});
			}
		},
		// 通知服务器购买成功（Google Play）
		async notifyServerPurchase(packageItem, purchaseData, retryCount = 0) {
			try {
				this.saveError('通知服务器购买', `开始通知服务器，套餐ID: ${packageItem.id}, 钻石数量: ${packageItem.number}, 重试次数: ${retryCount}`);
				this.savePendingOrder(packageItem, purchaseData, retryCount);

				let purchaseDataString = '';
				if (purchaseData) {
					purchaseDataString = JSON.stringify(purchaseData);
				}
				try {
					JSON.parse(purchaseDataString);
					this.saveError('通知服务器购买', `purchase_data 格式验证通过，长度: ${purchaseDataString.length}`);
				} catch (e) {
					this.saveError('通知服务器购买警告', `purchase_data 格式验证失败: ${e.message}`);
				}

				await notifyGooglePayPurchase({
					purchaseToken: purchaseData.original.purchaseToken,
					packageName: purchaseData.original.packageName,
					productId: purchaseData.original.productId,
					purchase_data: purchaseDataString
				});

				const pendingOrders = this.getPendingOrders();
				pendingOrders.forEach(order => {
					if (order.data.package_id === packageItem.id) {
						this.clearPendingOrder(order.key);
					}
				});
				this.saveError('通知服务器购买成功', `服务器验证成功，套餐ID: ${packageItem.id}, 钻石数量: ${packageItem.number}`);
				this.paySuccess(packageItem.number);
			} catch (error) {
				console.error('Notify server error:', error);
				this.saveError('通知服务器购买异常', `发生异常，已保存到本地等待重试: ${JSON.stringify(error && error.message ? error.message : error)}`);
				this.loading = false;
				this.disabled = false;
				uni.showToast({
					title: this.$t('money.paymentVerifying') || '支付验证中，请稍后',
					icon: 'none',
					duration: 3000
				});
			}
		},
		// 支付成功
		paySuccess(amount) {
			this.saveError('支付成功', `充值成功，钻石数量: ${amount}`);
			this.loading = false;
			this.disabled = false;

			// 刷新钻石余额
			this.loadDiamondBalance();

			// 从礼物面板跳来：保留 pending_gift，标记回房刷新，确认后 navigateBack
			uni.setStorageSync('from_recharge_page', '1');

			// 显示成功弹框提示
			this.successAmount = amount;
			this.showSuccessModal = true;
		},
		// 处理充值成功弹框关闭
		handleSuccessModalClose() {
			this.showSuccessModal = false;
			if (this.fromGift) {
				uni.navigateBack({ fail: () => {} });
			}
		},
		// 处理充值成功弹框确认
		handleSuccessModalConfirm() {
			this.showSuccessModal = false;
			this.selectedQuickAmount = null;
			this.diamondAmount = '';
			if (this.fromGift) {
				uni.navigateBack({ fail: () => {} });
			}
		},
		// 返回上一页
		goBack() {
			uni.navigateBack({ fail: () => {} });
		},
		// 跳转到充值明细
		goToDetail() {
			if (this.$appKit && this.$appKit.to) {
				this.$appKit.to('/pages/user/money/diamond-log');
			} else {
				uni.navigateTo({ url: '/pages/user/money/diamond-log' });
			}
		}
	}
}
</script>

<style>
/* 全局样式 */
page {
	background: linear-gradient(180deg, #2F1464 0%, #000000 100%);
	min-height: 100vh;
}

/* 容器 */
.container {
	width: 100%;
	min-height: 100vh;
	padding-bottom: 40rpx;
}

/* 头部 */
.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	padding-top: calc(var(--status-bar-height) + 20rpx);
	margin-bottom: 30rpx;
}

.header-left, .header-right {
	width: 100rpx;
}

.header-left {
	text-align: left;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}

.back-button {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.2);
	backdrop-filter: blur(10rpx);
}

.back-button text {
	font-size: 36rpx;
}

.header-right {
	text-align: right;
}

.header-title {
	flex: 1;
	text-align: center;
	font-size: 32rpx;
	font-weight: bold;
}

/* 用户信息卡片 */
.user-info-card {
	background-image: url('/static/imgs/icon/bg_d_top.png');
	height:320rpx;
	background-size: cover;
	background-position: center;
	background-repeat: no-repeat;
	margin: 120rpx 30rpx 40rpx 30rpx;
	padding: 40rpx;
	border-radius: 24rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.user-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	overflow: hidden;
	margin-right: 24rpx;
	border: 4rpx solid #ffffff;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.user-avatar image {
	width: 100%;
	height: 100%;
}

.user-info {
	flex: 1;
}

.user-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 8rpx;
	display: block;
}

.diamond-balance-text {
	font-size: 24rpx;
	color: #666666;
}

/* 充值部分 */
.recharge-section {
	padding: 0 30rpx;
	margin-bottom: 40rpx;
}

.section-title {
	text-align: center;
	font-size: 28rpx;
	color: #ffffff;
	margin-bottom: 30rpx;
}

/* 快捷金额网格 */
.quick-amount-grid {
	margin-top: 20rpx;
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
}

.amount-item {
	background: rgba(139, 69, 199, 0.3);
	border-radius: 16rpx;
	padding: 24rpx 16rpx;
	text-align: left;
	border: 2rpx solid transparent;
	backdrop-filter: blur(10rpx);
	transition: all 0.3s ease;
	position: relative;
}

.amount-item.active {
	border-color: #ffffff;
	background: rgba(139, 69, 199, 0.5);
	/* #ifndef APP-NVUE */
	transform: translateY(-2rpx);
	box-shadow: 0 4rpx 16rpx rgba(255, 255, 255, 0.3);
	/* #endif */
	/* #ifdef APP-NVUE */
	/* nvue中transform可能不支持，使用其他方式 */
	/* #endif */
}

.amount-item-content {
	display: flex;
	flex-direction: column;
	position: relative;
}

.diamond-icon-item {
	width: 40rpx;
	height: 40rpx;
	position: absolute;
	top: 0;
	left: 0;
}

.diamond-label {
	font-size: 22rpx;
	color: #87ceeb;
	font-weight: 500;
	margin-bottom: 12rpx;
	margin-top: 4rpx;
	padding-left: 48rpx;
}

.diamond-number {
	font-size: 40rpx;
	font-weight: bold;
	color: #87ceeb;
	margin-bottom: 12rpx;
	line-height: 1.2;
}

.amount-price {
	font-size: 22rpx;
	color: #ffffff;
	font-weight: 500;
}

/* 汇率提示 */
.exchange-rate-tip {
	padding: 0 30rpx;
	margin-bottom: 40rpx;
	text-align: center;
}

.exchange-rate-tip text {
	display: block;
	font-size: 20rpx;
	color: #ffffff;
	opacity: 0.8;
	margin-bottom: 4rpx;
}

/* 支付方式 */
.payment-methods {
	margin: 0 30rpx;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 16rpx;
	padding: 20rpx;
	backdrop-filter: blur(10rpx);
	margin-bottom: 40rpx;
}

.payment-methods .item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.payment-methods .item:last-child {
	border-bottom: none;
}

.payment-methods .item text[class*="wlIcon-"] {
	font-size: 48rpx;
	color: #ffffff;
	margin-right: 24rpx;
}

.payment-methods .item .action {
	flex: 1;
}

.payment-methods .item .action .title {
	font-size: 28rpx;
	color: #ffffff;
	margin-bottom: 4rpx;
	display: block;
}

.payment-methods .item .action view {
	font-size: 20rpx;
	color: rgba(255, 255, 255, 0.8);
}

.payment-methods .item .radio {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 充值按钮 */
.recharge-btn {
	width: calc(100% - 60rpx);
	height: 90rpx;
	background: linear-gradient(90deg, #ff6b6b, #ee5a6f);
	border-radius: 45rpx;
	font-size: 32rpx;
	color: #ffffff;
	font-weight: bold;
	margin: 0 30rpx;
	margin-top: 20rpx;
	border: none;
}

.recharge-btn::after {
	border: none;
}

.recharge-instructions {
	margin-top: 24rpx;
	text-align: center;
	font-size: 26rpx;
}

/* 辅助类 */
.text-white {
	color: #ffffff;
}

.text-gray-light {
	color: rgba(255, 255, 255, 0.6);
}

/* 响应式调整 */
@media screen and (max-width: 375px) {
	.quick-amount-grid {
		gap: 16rpx;
	}
	
	.amount-item {
		padding: 20rpx 16rpx;
	}
	
	.diamond-number {
		font-size: 32rpx;
	}
}
</style>
