<template>
	<view class="container">
		<view v-if="packageList.length > 0" class="card flex-col-g20" v-for="item in packageList">
			<view class="title">
				{{item.name}}
			</view>
			<view class="price">
				￥{{item.accountMoney}}
			</view>
			<view class="desc">
				请在套餐有效期内使用,有效期内流量用完可充值加餐包即可继续使用
			</view>
			<view class="btn">
				<up-button type="primary" @tap="showBuy=true">立即订购</up-button>
			</view>
			<up-modal :title="`您确定要订购${item.name}套餐吗？`" :show="showBuy" showCancelButton @confirm="SubscribeNow(item)"
				@cancel="showBuy=false" />
		</view>

		<view v-else class="card">
			<view class="title" style="text-align: center;">
				该设备暂无套餐, 请联系客服购买
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref
	} from 'vue';

	import {
		userStore
	} from '@/store/index.js';

	let showBuy = ref(false)

	// 套餐列表
	let packageList = reactive([]);

	// 支付列表
	let payList = reactive([]);

	// 获取套餐列表
	const getPackageList = async () => {
		const result = await userStore.actions.getPackageList()
		if (result.smList.length > 0) {
			packageList.push(...result.smList)
		}
	}

	// 立即订购
	const SubscribeNow = async (item) => {
		// 1. 判断当前用户是否已经绑定了微信公众号的 OpenId
		await checkHasGzhOpenId()

		// 2. checkYgosWxInfo 检查当前用户是否具有与微信支付相关的特定信息
		await userStore.actions.checkYgosWxInfo()

		// 3. checkXwzfWxInfo 检查当前用户是否具有与微信支付相关的特定信息
		await userStore.actions.checkXwzfWxInfo()

		// 4. 获取支付列表
		await getPayList(item.id)

		let id = "";

		if (payList.length === 2) {
			id = payList[1].id

		} else {
			uni.showToast({
				title: "未找到微信支付",
				icon: "none"
			})
		}

		const params = {
			mealId: item.id,
			cardID: "",
			money: item.money,
			mealType: item.type,
			cardCount: item.cardCount,
			mealName: item.name,
			strEffectType: "-1",
			__pay_method: "1",
			__merchant_cfg_id: id,
			payPwd: ""
		}

		// 5. 创建订单, 获取支付参数
		await createOrder(params)
	}

	// 1. 判断当前用户是否已经绑定了微信公众号的 OpenId
	const checkHasGzhOpenId = async () => {
		const result = await userStore.actions.checkHasGzhOpenId()
		if (result.wxAuthUrl) {
			// 再次进行授权
			uni.showToast({
				title: "该用户需要再次授权",
				icon: "none"
			})
			toAuth()
		}
	}

	// 4. 获取支付列表
	const getPayList = async (mealId) => {
		const result = await userStore.actions.getPayList(mealId)
		if (result.payMethodList.length > 0) {
			Object.assign(payList, result.payMethodList)
		} else {
			toAuth()
		}
	}

	// 5. 创建订单, 获取支付参数, 并拉起微信支付
	const createOrder = async (params) => {
		showBuy.value = false;

		try {
			// 调用后端接口，获取支付参数
			const data = await userStore.actions.createOrder(params);

			// 如果有错误信息，显示错误提示
			if (data?.errorMsg) {
				uni.showToast({
					title: data?.errorMsg,
					icon: "none"
				});
				return;
			}

			// 调起微信支付
			if (data?.wp) {
				await invokeWechatPay(data?.wp);
			} else {
				uni.showToast({
					title: '获取支付参数失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: "拉起微信支付失败",
				icon: "none"
			})
		}
	};

	// 调起微信支付
	const invokeWechatPay = (payParam) => {
		return new Promise((resolve, reject) => {
			console.log('[PackageOrder] 调起微信支付...', payParam)

			const onBridgeReady = () => {
				window.WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						appId: payParam.appId,
						timeStamp: payParam.timeStamp,
						nonceStr: payParam.nonceStr,
						package: payParam.prepayId,
						signType: payParam.signType || 'MD5',
						paySign: payParam.paySign
					},
					(res) => {
						console.log('[PackageOrder] 微信支付结果:', res)
						if (res.err_msg === 'get_brand_wcpay_request:ok') {
							resolve(res)
						} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
							reject(new Error('用户取消支付'))
						} else {
							reject(new Error('支付失败: ' + res.err_msg))
						}
					}
				)
			}

			if (typeof window.WeixinJSBridge === 'undefined') {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
					document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
				}
			} else {
				onBridgeReady()
			}
		})
	}

	// 跳转到微信授权页面
	const toAuth = async () => {
		try {
			const result = await userStore.actions.getWxUrl();

			if (result.wxAuthUrl) {
				// 获取当前页面的URL
				const currentUrl = window.location.href;

				// 检查当前URL是否已经包含 code 参数
				if (!currentUrl.includes("code=")) {
					// 如果没有code参数，跳转到微信授权页面
					let originalUrl = result.wxAuthUrl;

					// 目标替换的 redirect_uri
					const newRedirectUri = "https://m1.whjhft.com/pages/index/index";

					// 替换 "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxea8c599fe100ce8a&redirect_uri=https://m1.whjhft.com/my/my&response_type=code&scope=snsapi_userinfo&state=cardlogin#wechat_redirect"
					// 使用正则表达式替换 redirect_uri 的值
					const updatedUrl = originalUrl.replace(/(redirect_uri=)[^&]*/,
						`$1${encodeURIComponent(newRedirectUri)}`);

					if (updatedUrl) {
						window.location.href = updatedUrl;
					}
				} else {
					// 如果已经包含code参数, 就进行授权
					authoration()
				}
			} else {
				uni.showToast({
					title: '该用户已授权',
					icon: 'none'
				})

			}
		} catch (e) {
			uni.showToast({
				title: e,
				icon: 'none'
			});
		}
	};

	// 授权
	const authoration = async () => {
		try {
			// 获取当前页面的完整 URL https://m1.whjhft.com/pages/index/index?code=081KSnml23G2Ug4XViml2VFHyJ0KSnmF&state=cardlogin
			// const url = window.location.href; 

			const code = (location.search.match(/[?&]code=([^&]*)/) || [])[1];

			if (code) {
				// 如果 code 存在，则调用获取授权的动作
				await userStore.actions.getAuthorize(code);
				removeCodeFromUrl()
			} else {
				// 如果 code 不存在
				uni.showToast({
					title: "微信授权失败!",
					icon: "none"
				});
			}

		} catch (error) {
			// 错误处理
			console.error('授权失败:', error);
			uni.showToast({
				title: "授权失败，请重试",
				icon: "none"
			});
		}
	};

	onMounted(() => {
		getPackageList()
	})
</script>

<style lang="scss" scoped>
	.container {
		.card {
			.title {
				font-size: 32rpx;
				font-weight: 600;
			}

			.price {
				font-size: 32rpx;
				font-weight: bold;
				color: #aa5500;
			}

			.btn {
				margin-top: 20rpx;
			}
		}

		.container {
			.pay-title {
				font-size: 35rpx;
				text-align: center;
			}
		}
	}
</style>