<template>
	<scroll-view scroll-y class="vip-page">
		<!-- 顶部背景 -->
		<view class="header-bg">
			<!-- 返回按钮 -->
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			
			<text class="crown-icon">👑</text>
			<text class="title">VIP会员特权</text>
			<text class="subtitle">开通会员，享受专属服务</text>
		</view>

		<!-- 特权列表 -->
		<view class="privileges-section">
			<view class="privilege-item" v-for="(item, index) in privileges" :key="index">
				<view class="privilege-icon">{{ item.icon }}</view>
				<view class="privilege-content">
					<text class="privilege-title">{{ item.title }}</text>
					<text class="privilege-desc">{{ item.desc }}</text>
				</view>
			</view>
		</view>

		<!-- VIP套餐 -->
		<view class="packages-section">
			<view class="section-title">选择套餐</view>
			<view class="packages-list">
				<view 
					class="package-card" 
					v-for="(pkg, index) in packages" 
					:key="index"
					:class="{ 'active': selectedPackage === index }"
					@click="selectPackage(index)"
				>
					<text class="package-name">{{ pkg.name }}</text>
					<view class="package-price">
						<text class="price-symbol">¥</text>
						<text class="price-value">{{ pkg.price }}</text>
						<text class="price-unit">/{{ pkg.duration }}</text>
					</view>
					<text class="package-original" v-if="pkg.originalPrice">原价 ¥{{ pkg.originalPrice }}</text>
					<view class="package-benefits">
						<text class="benefit-item" v-for="(benefit, idx) in pkg.benefits" :key="idx">
							{{ benefit }}
						</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部占位 -->
		<view class="bottom-placeholder"></view>

		<!-- 底部购买按钮 -->
		<view class="bottom-bar">
			<view class="total-info">
				<text class="total-label">合计：</text>
				<text class="total-price" v-if="selectedPackagePrice > 0">¥{{ selectedPackagePrice }}</text>
				<text class="total-price-hint" v-else>请选择套餐</text>
			</view>
			<button class="buy-btn" @click="handlePurchase">立即开通</button>
		</view>
	</scroll-view>
</template>

<script>
	import userAuth from '@/utils/userAuth.js'
	
	export default {
		data() {
			return {
				gatewayURL: 'https://api.zhongruanke.cn',
				currentUserId: null,
				selectedPackage: null, // 默认不选中任何套餐
				isVip: false,
				vipExpireTime: null,
				remainingDays: 0,
				privileges: [
					{
						icon: '👑',
						title: '专属身份标识',
						desc: '尊贵VIP标识，提升个人魅力'
					},
					{
						icon: '💎',
						title: '优先推荐',
						desc: '优先展示给优质用户，提高匹配率'
					},
					{
						icon: '💌',
						title: '无限查看联系方式',
						desc: '查看心仪对象的联系方式，无限制'
					},
					{
						icon: '👀',
						title: '查看访客记录',
						desc: '查看谁看过你，主动出击'
					},
					{
						icon: '📞',
						title: '专属红娘服务',
						desc: '一对一专属红娘，贴心服务'
					},
					{
						icon: '🎉',
						title: '线下活动优先',
						desc: '优先参加平台举办的线下活动'
					}
				],
				packages: []
			}
		},
		onLoad() {
			// 获取登录用户ID - 使用修复后的工具类
			this.currentUserId = userAuth.getUserId()
		
			
			// 加载VIP信息
			this.loadVipInfo()
		},
		computed: {
			selectedPackagePrice() {
				if (this.selectedPackage === null || this.selectedPackage === undefined) {
					return 0
				}
				return this.packages[this.selectedPackage]?.price || 0
			}
		},
		methods: {
			// 加载VIP信息
			loadVipInfo() {
				const params = {}
				if (this.currentUserId) {
					params.userId = this.currentUserId
				}
				
				uni.request({
					url: this.gatewayURL + '/api/vip/inf',
					method: 'GET',
					data: params,
					success: (res) => {
						
						
						if (res.data && res.data.code === 200) {
							const data = res.data.data
							
							// 更新VIP状态
							this.isVip = data.isVip
							this.vipExpireTime = data.vipExpireTime
							this.remainingDays = data.remainingDays
							
							// 更新套餐列表
							this.packages = data.packages.map(pkg => ({
								packageId: pkg.packageId,
								name: pkg.name,
								price: pkg.price,
								originalPrice: pkg.originalPrice,
								duration: pkg.duration,
								benefits: pkg.benefits,
								recommend: pkg.recommend
							}))
						}
					},
					fail: (err) => {
						console.error('获取VIP信息失败:', err)
						uni.showToast({
							title: '加载VIP信息失败',
							icon: 'none'
						})
					}
				})
			},
			
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			
			selectPackage(index) {
				this.selectedPackage = index
			},
			
			handlePurchase() {
				// 检查是否选择了套餐
				if (this.selectedPackage === null || this.selectedPackage === undefined) {
					uni.showToast({
						title: '请先选择一个套餐',
						icon: 'none'
					})
					return
				}
				
				const pkg = this.packages[this.selectedPackage]
				
				if (!pkg) {
					uni.showToast({
						title: '请选择套餐',
						icon: 'none'
					})
					return
				}
				
				// 获取用户ID
				const userId = this.currentUserId || 1
				
				uni.showModal({
					title: '确认开通',
					content: `确认开通${pkg.name}（¥${pkg.price}）？`,
					success: (res) => {
						if (res.confirm) {
							this.requestPay(userId, pkg)
						}
					}
				})
			},
			
			/**
			 * 请求支付参数并调起微信支付
			 */
			requestPay(userId, pkg) {
				uni.showLoading({
					title: '处理中...'
				})
				
				uni.request({
					url: this.gatewayURL + '/api/vip/purchase',
					method: 'POST',
					data: {
						userId: userId,
						packageId: pkg.packageId
					},
					header: {
						'content-type': 'application/json',
						'token': uni.getStorageSync('token') // 携带登录态
					},
					success: (res) => {
						uni.hideLoading()
						
						if (res.data && res.data.code === 200) {
							const payParams = res.data.ext // 后端返回的支付参数
							this.callWxPay(payParams, pkg) // 调起微信支付
						} else {
							uni.showToast({
								title: res.data?.message || '获取支付参数失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('请求支付参数失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			
			/**
			 * 调起微信支付组件
			 */
			callWxPay(payParams, pkg) {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: payParams.timeStamp,
					nonceStr: payParams.nonceStr,
					package: payParams.package,
					signType: payParams.signType,
					paySign: payParams.paySign,
					total_fee: payParams.totalFee,
					success: (payResult) => {
						if (payResult.errMsg === 'requestPayment:ok') {
							uni.showToast({
								title: '支付成功！VIP已开通',
								icon: 'success',
								duration: 2000
							})
							
							// 延迟返回上一页，并触发页面刷新
							setTimeout(() => {
								// 通过事件通知个人页面刷新数据
								uni.$emit('vipPurchased')
								
								// 返回上一页
								uni.navigateBack({
									success: () => {
										
									}
								})
							}, 2000)
						}
					},
					fail: (payError) => {
						console.error('支付失败:', payError)
						if (payError.errMsg.includes('cancel')) {
							uni.showToast({
								title: '已取消支付',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: `支付失败：${payError.errMsg}`,
								icon: 'none'
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 原有样式保持不变 */
	.vip-page {
		height: 100vh;
		background: #F5F5F5;
	}
	
	.bottom-placeholder {
		height: 180rpx;
	}

	.header-bg {
		background: linear-gradient(135deg, #FFB300 0%, #FFA000 100%);
		padding: 60rpx 60rpx 120rpx;
		padding-top: calc(60rpx + env(safe-area-inset-top));
		text-align: center;
		position: relative;
		border-bottom: 4rpx solid #FF8F00;
		
		.back-btn {
			position: absolute;
			left: 30rpx;
			top: calc(60rpx + env(safe-area-inset-top));
			width: 70rpx;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 10;
			background: rgba(255, 255, 255, 0.2);
			border-radius: 8rpx;
			transition: all 0.2s ease;
			
			&:active {
				opacity: 0.8;
			}
			
			.back-icon {
				font-size: 48rpx;
				color: #FFFFFF;
				font-weight: bold;
			}
		}
		
		.crown-icon {
			font-size: 120rpx;
			margin-bottom: 20rpx;
			display: block;
			filter: drop-shadow(0 4rpx 8rpx rgba(0, 0, 0, 0.2));
		}
		
		.title {
			display: block;
			font-size: 44rpx;
			font-weight: bold;
			color: #FFFFFF;
			margin-bottom: 15rpx;
			letter-spacing: 2rpx;
		}
		
		.subtitle {
			display: block;
			font-size: 26rpx;
			color: #FFFFFF;
			opacity: 0.95;
		}
	}

	.privileges-section {
		margin: -20rpx 30rpx 30rpx;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 35rpx 30rpx;
		border: 2rpx solid #E0E0E0;
		
		.section-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 25rpx;
			text-align: center;
		}
		
		.privilege-item {
			display: flex;
			align-items: flex-start;
			margin-bottom: 25rpx;
			padding: 20rpx;
			background: #FFFBF0;
			border-radius: 12rpx;
			border: 2rpx solid #FFE082;
			transition: all 0.2s ease;
			
			&:active {
				background: #FFF8E1;
			}
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.privilege-icon {
				width: 70rpx;
				height: 70rpx;
				background: #FFF3E0;
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 36rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
				border: 2rpx solid #FFD54F;
			}
			
			.privilege-content {
				flex: 1;
				min-width: 0;
				overflow: hidden;
				
				.privilege-title {
					display: block;
					font-size: 28rpx;
					font-weight: bold;
					color: #333333;
					margin-bottom: 8rpx;
					word-wrap: break-word;
					word-break: break-all;
					white-space: normal;
				}
				
				.privilege-desc {
					display: block;
					font-size: 22rpx;
					color: #999999;
					line-height: 1.4;
					word-wrap: break-word;
					white-space: normal;
				}
			}
		}
	}

	.packages-section {
		margin: 30rpx;
		
		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 25rpx;
			text-align: center;
			padding-bottom: 15rpx;
			border-bottom: 3rpx solid #FFB300;
		}
		
		.packages-list {
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			
			.package-card {
				background-color: #FFFFFF;
				border-radius: 16rpx;
				padding: 35rpx 30rpx;
				position: relative;
				border: 3rpx solid #E0E0E0;
				transition: all 0.2s ease;
				
				&:active {
					transform: translateY(-2rpx);
				}
				
				.package-name {
					font-size: 34rpx;
					font-weight: bold;
					color: #333333;
					margin-bottom: 15rpx;
					display: block;
				}
				
				.package-price {
					display: flex;
					align-items: baseline;
					margin-bottom: 8rpx;
					
					.price-symbol {
						font-size: 30rpx;
						color: #FFB300;
						font-weight: bold;
					}
					
					.price-value {
						font-size: 52rpx;
						font-weight: bold;
						color: #FFB300;
						margin: 0 5rpx;
					}
					
					.price-unit {
						font-size: 26rpx;
						color: #999999;
					}
				}
				
				.package-original {
					font-size: 24rpx;
					color: #CCCCCC;
					text-decoration: line-through;
					margin-bottom: 18rpx;
					display: block;
				}
				
				.package-benefits {
					display: flex;
					flex-wrap: wrap;
					gap: 12rpx;
					
					.benefit-item {
						background: #FFF3E0;
						padding: 8rpx 20rpx;
						border-radius: 8rpx;
						font-size: 22rpx;
						color: #F57C00;
						border: 1rpx solid #FFD54F;
						font-weight: 500;
					}
				}
				
				&.active {
					background: linear-gradient(135deg, #FFFBF0 0%, #FFF8E1 100%);
					border-color: #FFB300;
					border-width: 4rpx;
					
					&::before {
						content: '✓ 已选择';
						position: absolute;
						top: 20rpx;
						right: 20rpx;
						background: #FFB300;
						color: #FFFFFF;
						padding: 6rpx 16rpx;
						border-radius: 6rpx;
						font-size: 22rpx;
						font-weight: 600;
					}
				}
			}
		}
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #FFFFFF;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		border-top: 2rpx solid #E0E0E0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		z-index: 999;
		
		.total-info {
			display: flex;
			align-items: baseline;
			
			.total-label {
				font-size: 28rpx;
				color: #666666;
				font-weight: 500;
			}
			
			.total-price {
				font-size: 48rpx;
				font-weight: bold;
				color: #FFB300;
				margin-left: 10rpx;
			}
			
			.total-price-hint {
				font-size: 28rpx;
				color: #999999;
				margin-left: 10rpx;
			}
		}
		
		.buy-btn {
			background: linear-gradient(135deg, #FFB300 0%, #FFA000 100%);
			color: #FFFFFF;
			padding: 20rpx 60rpx;
			border-radius: 50rpx;
			font-size: 30rpx;
			font-weight: bold;
			border: none;
			box-shadow: 0 6rpx 16rpx rgba(255, 179, 0, 0.4);
			transition: all 0.2s ease;
			
			&:active {
				transform: translateY(2rpx);
				box-shadow: 0 4rpx 12rpx rgba(255, 179, 0, 0.3);
			}
			
			&::after {
				border: none;
			}
		}
	}
</style>