<template>
	<view class="allContent">
		<view class="list-item">
			<view><text>权益名称：</text><text>{{state.params['equityName']}}</text></view>
			<view><text>权益金额：</text><text>￥{{state.params['discountPrice']* 0.01}}</text></view>
			<view><text>权益介绍：</text><rich-text :nodes="state.params['productIntro']" class="last" /></view>
			<view><text>卖点：</text><text>{{state.params['sellingPoint']}}</text></view>
			<view><text>开始时间：</text><text>{{state.params['startDate']}}</text></view>
			<view><text>结束时间：</text><text>{{state.params['endDate']}}</text></view>

		</view>
		<view style="margin-top: 30rpx" class="action">
			<button type="default" class="button" @click="buy()">
				购买
			</button>
		</view>
	</view>

</template>

<script setup lang="ts">
	import { reactive } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { equitypurchase, getOpenId, paymentequityapplyapp, payequitydetection, aliPayConfigIdTwo, obtainUserId } from "@/utils/network/api.js";
	import {
		request, requestNew
	} from "@/utils/network/request.js";
	import {
		getItem,
		StorageKeys,
	} from "@/utils/storage";
	import {
		stringToJson
	} from "@/utils/network/encryption";
	import { msg } from "@/utils/utils";
	const state = reactive({
		id: "", //支付id
		params: {},  //上一个页面传递过来的参数
	});
	onLoad((options) => {
		state.params = JSON.parse(decodeURIComponent(options.params))
		state.params['startDate'] = state.params['startDate'].replace("T", ' ')
		state.params['endDate'] = state.params['endDate'].replace("T", ' ')
		console.log("options", state.params)
	})
	const buy = () => {
		if(state.params['hasDate']){
			uni.showModal({
				title: '提示',
				content: '重复购买此权益',
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确定');
						chooseBuy()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}else{
			chooseBuy()
		}
	}
	const chooseBuy = () => {
		const options = {
			type: 2,
			data: {
				"openId": getItem(StorageKeys.OpenId),
				"equityId": state.params['equtyId']
			},
			method: 'POST',
			showLoading: true,
		}
		// 权益购买入参有个属性是type:1，代表查询是否已经买过了权益，返回的数据中hasData:true表示买过了，如果hasData:false表示没买过。type:2,表示购买
		requestNew(equitypurchase, options).then((res) => {
			const data = res;
			console.log("购买2", data)
			state.id = data.id
			// 权益支付下单
			equityPaymentOrderRequest()
		})
	}
	// 权益支付检测
	const equityPaymentTestRequest = () => {
		const options = {
			type: 2,
			data: {
				id: state.id,
			},
			method: 'POST',
			showLoading: true,
		}
		return new Promise(async (resolve, reject) => {
			const res = await requestNew(payequitydetection, options);
			const data = res;
			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	}
	// 权益支付下单
	const equityPaymentOrderRequest = () => {
		// #ifdef MP-WEIXIN
		uni.login({
			provider: "weixin",
			success: function (e) {
				const options1 = {
					type: 2,
					data: {
						"jsCode": e.code
					},
					method: "POST",
					showLoading: true,
				};
				requestNew(getOpenId, options1).then((res) => {
					console.log("state.id",state.id)
					console.log("state.id",res)
					const result = res;
					const openidData = stringToJson(result.data);
					console.log("openidData",openidData)
					const options = {
						type: 2,
						data: {
							id: state.id,
							payType: "EQUITY",
							wxOpenid: openidData.openid
						},
						method: 'POST',
						showLoading: true,
					}
					requestNew(paymentequityapplyapp, options).then((res) => {
						const data = res;
						console.log("权益支付下单", data)
						if (data.info == "购买权益记录已支付") {
							uni.showModal({
								title: '提示',
								content: data.info,
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										uni.navigateBack({
											delta: 2
										})
									}
								}
							});
						} else {
							uni.requestPayment({
								provider: "wxpay",
								orderInfo: "",
								timeStamp: data.timestamp,
								nonceStr: data.noncestr,
								package: data.wxPackage ? data.wxPackage : "",
								signType: data.signType,
								paySign: data.sign,
								success: function (e) {
									console.log("支付成功", res);
									// 权益支付检测
									equityPaymentTestRequest().then((item : any) => {
										console.log("权益支付检测", data)
										msg("权益产品购买成功,到【我的】权益查看")
										setTimeout(() => {
											uni.navigateBack({
												delta: 2
											})
										}, 2000)
									})
								},
								fail: function (err) {
									confirm(err, () => { }, "支付失败", false);
								},
							})
						}
					})
				})
			},
		})
		// #endif
		// #ifdef MP-ALIPAY
		my.getAuthCode({
			scopes: 'auth_base',
			success: res => {
				const optionsUser = {
					type: 2,
					data: {
						payConfigId: aliPayConfigIdTwo,
						code: res.authCode
					},
					method: "POST",
					showLoading: true,
				};
				console.log('支付宝用户编号请求：', optionsUser)
				requestNew(obtainUserId, optionsUser).then((res) => {
					console.log('支付宝用户编号返回：', res)
					const data = res;
					console.log("data", data)
					const optionsali = {
						type: 2,
						data: {
							id: state.id,
							payType: "EQUITY",
							wxOpenid: data.openId,
						},
						method: "POST",
						showLoading: true,
					};
					console.log('支付下单请求：', optionsali)
					requestNew(paymentequityapplyapp, optionsali).then((res) => {
						const data = stringToJson(res.bizContent);
						console.log('支付下单返回：', data)
						my.tradePay({
							// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号 trade_no
							tradeNO: data.tranPackage,
							success: res => {
								console.log("支付成功", res);
								if (res.resultCode != "6001") {
									// 权益支付检测
									equityPaymentTestRequest().then((item : any) => {
										console.log("权益支付检测", data)
										msg("权益产品购买成功,到【我的】权益查看")
										setTimeout(() => {
											uni.navigateBack({
												delta: 2
											})
										}, 2000)
									})
								}

							},
							fail: res => {
								console.log("支付失败", res);
							},
						});

					});
				});
			},
			fail: err => {
				console.log('my.getAuthCode 调用失败', err)
			}
		});
		// #endif
	}
</script>

<style scoped lang="scss">
	.allContent {
		background-color: #EEF7F7;
		height: 100vh;
		padding: 30rpx 0;
		width: 100%;
		overflow-x: auto;
	}

	.list-item {
		width: 95%;
		border-radius: 10rpx;
		margin: 0rpx auto;
		font-size: 28rpx;
		border: 1rpx solid #ccc;
		padding: 12rpx;
		box-sizing: border-box;
		background-color: white;
	}

	.list-item>view {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.list-item>view>text:first-child {
		width: 26%;
		display: inline-block;
	}

	.list-item>view>text:last-child {
		width: 74%;
		display: inline-block;
		word-break: break-all;
	}

	.last {
		width: 74%;
		display: inline-block;
		word-break: break-all;
	}

	.action {
		padding-bottom: 100rpx;
		width: 90%;
		margin: 0 auto;

		.button {
			height: 80rpx;
			background: linear-gradient(-90deg, #43a1e0 0%, #13e7c1 100%);
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: 400;
			color: #ffffff;
			line-height: 80rpx;
		}
	}
</style>