<template>
	<view class="recharge-page">
		<!-- 个人服务包选择 -->
		<view class="package-section">
			<view class="section-title">选择个人服务包</view>

			<!-- 服务包列表 -->
			<view v-if="servicePackages.length > 0" class="package-list">
				<view
					v-for="pkg in servicePackages"
					:key="pkg.grfwbid"
					class="package-item"
					:class="{ active: selectedPackage && selectedPackage.grfwbid === pkg.grfwbid }"
					@click="selectPackage(pkg)"
				>
					<view class="package-header">
						<view class="package-name">{{ pkg.mc }}</view>
						<view class="package-info">
							<text class="package-price">¥{{ pkg.num > 0 ? (pkg.jg * pkg.num) : pkg.jg }}</text>
							<text v-if="pkg.num > 0" class="package-weeks">{{ pkg.num }}周 × ¥{{ pkg.jg }}/周</text>
						</view>
					</view>

					<!-- 服务项目列表 -->
					<view v-if="pkg.grfwbmxList && pkg.grfwbmxList.length > 0" class="service-items">
						<view
							v-for="(item, index) in pkg.grfwbmxList"
							:key="index"
							class="service-item"
						>
							<text class="service-name">{{ item.mc }}</text>
							<view class="service-details">
								<text v-if="item.sfmf === 1" class="service-tag free">免费</text>
								<text v-if="item.sc > 0" class="service-tag">{{ item.sc }}分钟</text>
								<text v-if="item.cs > 0" class="service-tag">{{ item.cs }}次</text>
								<text v-if="item.ll > 0" class="service-tag">{{ item.ll }}MB</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-else class="empty-state">
				<text>暂无可用服务包</text>
			</view>
		</view>

		<!-- 支付金额显示 -->
		<view class="pay-info">
			<view class="pay-info-item">
				<text class="label">支付金额：</text>
				<text class="value">¥{{ finalAmount }}</text>
			</view>
		</view>

	<!-- 支付按钮 -->
	<view class="pay-btn-wrapper">
		<button
			class="pay-btn"
			:disabled="!finalAmount || finalAmount <= 0"
			@click="handlePay"
		>
			立即购买
		</button>

		<!-- <button
			class="pay-btn mock-btn"
			type="default"
			@click="goToTestResult"
		>
			测试支付结果页
		</button> -->
	</view>

		<!-- 充值说明 -->
		<!-- <view class="tips">
			<view class="tips-title">充值说明：</view>
			<view class="tips-item">1. 充值金额将实时到账</view>
			<view class="tips-item">2. 如有疑问请联系客服</view>
			<view class="tips-item">3. 充值成功后可在消费记录中查看</view>
		</view> -->
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { grfwApi } from '@/api/grfw'


// 兼容不同字段命名的支付参数
const normalizePayParams = (res) => {
	const data = res?.data.ssData || res || {}
	const payload = data.prepay || data.payInfo || data
	if (!payload) {
		return {}
	}
	return {
		appId: payload.appId,
		timeStamp: payload.timeStamp || payload.timestamp,
		nonceStr: payload.nonceStr || payload.noncestr,
		package: payload.package || payload.packageVal || payload.prepayId,
		signType: payload.signType || payload.sign_type || 'RSA',
		paySign: payload.paySign || payload.sign,
		orderId: data.outTradeNo
	}
}

// 个人服务包数据
const servicePackages = ref([])  // 服务包列表
const selectedPackage = ref(null)  // 选中的服务包

const isPaymentInProgress = ref(false)  // 支付进行中标志

// 最终支付金额（使用服务包价格，周包需要乘以周数）
const finalAmount = computed(() => {
	if (selectedPackage.value) {
		const pkg = selectedPackage.value
		// 如果是周包（num > 0），总价 = 单价 × 周数
		if (pkg.num > 0) {
			return parseFloat(pkg.jg * pkg.num) || 0
		}
		return parseFloat(pkg.jg) || 0
	}
	return 0
})

// 选择服务包
const selectPackage = (pkg) => {
	selectedPackage.value = pkg
	console.log('选中服务包：', pkg)
}

// 发起支付
const handlePay = async () => {
	if (isPaymentInProgress.value) {
		console.log('支付进行中，请勿重复点击')
		return
	}

	// 检查是否选择了服务包
	if (!selectedPackage.value) {
		uni.showToast({
			title: '请选择服务包',
			icon: 'none'
		})
		return
	}

	const amount = finalAmount.value
	if (!amount || amount <= 0) {
		uni.showToast({
			title: '支付金额异常',
			icon: 'none'
		})
		return
	}

	try {
		isPaymentInProgress.value = true

		// 1. 创建订单，获取支付参数
		console.log('创建个人服务包订单，包ID：', selectedPackage.value.grfwbid)
		console.log('支付金额：', amount)

		const payParamsRaw = await grfwApi.grfw_prepayGrfwb({
			grfwbid: selectedPackage.value.grfwbid
		})
		console.log('创建订单接口原始返回：', payParamsRaw.data.ssData)

		const payParams = normalizePayParams(payParamsRaw)
		if (!payParams.timeStamp || !payParams.nonceStr || !payParams.package || !payParams.paySign) {
			throw new Error('支付参数不完整')
		}

		console.log('支付参数：', payParams)

		// 2. 调用微信支付
		const paymentResult = await uni.requestPayment({
			provider: 'wxpay',
			timeStamp: String(payParams.timeStamp),
			nonceStr: payParams.nonceStr,
			package: payParams.package,
			signType: payParams.signType || 'RSA',
			paySign: payParams.paySign,
		})

		console.log('支付结果：', paymentResult)

		// 3. 支付成功 - 跳转到支付结果页面
		const resultOrderId = payParams.orderId

		if (resultOrderId) {
			// 跳转到支付结果页面，进行订单状态查询，传递 grfwbid 用于确认服务
			uni.redirectTo({
				url: `/pages/payment/result?orderId=${resultOrderId}&grfwbid=${selectedPackage.value.grfwbid}`
			})
		} else {
			// 如果没有订单ID，直接提示成功
			uni.showToast({
				title: '支付成功',
				icon: 'success',
				duration: 2000
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 2000)
		}

	} catch (error) {
		console.error('支付失败：', error)

		// 处理不同的错误情况
		if (error.errMsg) {
			// 微信支付相关错误
			if (error.errMsg.includes('cancel')) {
				uni.showToast({
					title: '已取消支付',
					icon: 'none'
				})
			} else if (error.errMsg.includes('fail')) {
				uni.showToast({
					title: '支付失败，请重试',
					icon: 'none'
				})
			}
		} else {
			// 其他错误（比如创建订单失败）
			uni.showToast({
				title: error.message || '操作失败',
				icon: 'none'
			})
		}
	} finally {
		isPaymentInProgress.value = false
	}
}

// 加载个人服务包列表
const loadServicePackages = async () => {
	try {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})

		const res = await grfwApi.grfw_initGrfwbBuy({})
		console.log('获取服务包列表返回：', res)
		console.log('res.data:', res.data)
		console.log('res.data.ssData:', res.data?.ssData)

		// 数据在 res.data.ssData 里
		if (res && res.data && res.data.ssData && Array.isArray(res.data.ssData)) {
			const ssData = res.data.ssData
			console.log('ssData 长度:', ssData.length)
			console.log('ssData 内容:', JSON.stringify(ssData))

			// 跳过第一个元素（minJzsj），从第二个元素开始获取服务包
			if (ssData.length > 1) {
				const packages = ssData.slice(1)
				console.log('提取的服务包（去除第一个元素）:', packages)

				servicePackages.value = packages.filter(item => item.grfwbid)
				console.log('过滤后的服务包列表:', servicePackages.value)
				console.log('服务包数量:', servicePackages.value.length)
			} else {
				console.log('ssData 长度不足，没有服务包数据')
			}
		} else {
			console.log('res.data.ssData 不存在或不是数组')
		}
	} catch (error) {
		console.error('加载服务包失败：', error)
		uni.showToast({
			title: '加载服务包失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 页面加载
onLoad((options) => {
	console.log('充值页面加载，参数：', options)

	// 加载服务包列表
	loadServicePackages()
})

// 测试跳转到支付结果页
const goToTestResult = () => {
	// 使用固定的订单号测试
	const testOrderId = 'pmsgrfwb7m05clpYYgwHG8qlroZB1'
	const testGrfwbid = selectedPackage.value?.grfwbid || ''

	uni.redirectTo({
		url: `/pages/payment/result?orderId=${testOrderId}&grfwbid=${testGrfwbid}`
	})
}
</script>

<style lang="scss" scoped>
.recharge-page {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 30rpx;
}

.package-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
}

.package-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.package-item {
	padding: 30rpx;
	border: 2rpx solid #e5e5e5;
	border-radius: 12rpx;
	background: #fff;
	transition: all 0.3s;
}

.package-item.active {
	border-color: #07c160;
	background: #f0f9ff;
}

.package-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.package-name {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}

.package-item.active .package-name {
	color: #07c160;
	font-weight: bold;
}

.package-info {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 8rpx;
}

.package-price {
	font-size: 36rpx;
	color: #ff4d4f;
	font-weight: bold;
}

.package-item.active .package-price {
	color: #07c160;
}

.package-weeks {
	font-size: 24rpx;
	color: #999;
	background: #f5f5f5;
	padding: 4rpx 12rpx;
	border-radius: 4rpx;
}

.package-item.active .package-weeks {
	background: #e6f7ff;
	color: #1890ff;
}

.service-items {
	border-top: 1rpx solid #f0f0f0;
	padding-top: 20rpx;
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 12rpx;
}

.service-item {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	padding: 12rpx 16rpx;
	background: #fafafa;
	border-radius: 8rpx;
}

.package-item.active .service-item {
	background: #f0f9ff;
}

.service-name {
	font-size: 28rpx;
	color: #666;
	font-weight: 500;
}

.service-details {
	display: flex;
	flex-wrap: wrap;
	gap: 6rpx;
}

.service-tag {
	font-size: 22rpx;
	color: #666;
	background: #fff;
	padding: 2rpx 8rpx;
	border-radius: 4rpx;
	border: 1rpx solid #e5e5e5;
	white-space: nowrap;
}

.service-tag.free {
	color: #52c41a;
	background: #f6ffed;
	border-color: #b7eb8f;
}

.empty-state {
	text-align: center;
	padding: 60rpx 0;
	color: #999;
	font-size: 28rpx;
}

.pay-info {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.pay-info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.pay-info-item .label {
	font-size: 32rpx;
	color: #333;
}

.pay-info-item .value {
	font-size: 40rpx;
	color: #ff4d4f;
	font-weight: bold;
}

.pay-btn-wrapper {
	padding: 40rpx 0;
}

.pay-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	background: linear-gradient(135deg, #07c160 0%, #05a050 100%);
	color: #fff;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
	box-shadow: 0 8rpx 20rpx rgba(7, 193, 96, 0.3);
}

.pay-btn[disabled] {
	background: #e5e5e5;
	color: #999;
	box-shadow: none;
}

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

.mock-btn {
	margin-top: 20rpx;
	background: #f5f5f5;
	color: #333;
	border: 1px solid #d9d9d9;
	box-shadow: none;
}

.tips {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
}

.tips-title {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.tips-item {
	font-size: 26rpx;
	color: #999;
	line-height: 40rpx;
	margin-bottom: 10rpx;
}
</style>
