<template>
	<view>
		<view v-for="(item, index) in listData" :key="index" @click="onClick(item)" :data-code="item" class="item">
			<view style="display: flex;justify-content: space-between;">
			   <text>{{ item.name }}</text><text>></text>
			</view>
			<view style="display: flex;justify-content: flex-end;margin-top: 6rpx;">
				<!-- 是否支付 1-已支付，2-未支付支付，3-已取消,4-已下单，未支付 -->
				<text class="btn" v-if="item.isPay==2"
					@click.stop="chooseBuy(item.equityId)">去支付</text>
			</view>
		</view>
	</view>
	<view v-if="listData.length==0" class="no">暂无数据</view>
</template>
<script setup lang='ts'>
	import { reactive } from "vue";
	import {
		getItem,StorageKeys
	} from "@/utils/storage";
	import {
		ref
	} from 'vue';
	import {
		requestNew
	} from "@/utils/network/request.js";
	import {
		equitypurchasepage,equitypurchase,getOpenId,paymentequityapplyapp,payequitydetection
	} from "@/utils/network/api.js";
	import {
		stringToJson
	} from "@/utils/network/encryption";
	import { msg } from "@/utils/utils";
	import {onShow} from "@dcloudio/uni-app";
	let listData = ref([])
    const state = reactive({
		id: "", //支付id
	});
	onShow(()=>{
		query()
	})
	function query(){
		//卡券渠道类型获取单项权益列表
		requestNew(equitypurchasepage, {
			type: 2,
			data: {
				couponAgencyType: ['TUHU', 'ZFB'],
				mobile: getItem('mobile').toString()
			},
			method: "POST",
			showLoading: true,
		}).then((item) => {
			let res = item
			console.log(res, '=========');
			listData.value = res.result
		})
	}
  
	function onClick(singId: any) {
		uni.navigateTo({
			url: '/subpackage/service/equity/equity?singleEquityId=' + singId.singleEquityId +
				'&couponAgencyType=' + singId.couponAgencyType + '&couponId=' + singId.couponId + '&equityId=' + singId.equityId,
		})
	}
	const chooseBuy = (equityId) => {
		const options = {
			type: 2,
			data: {
				"openId": getItem(StorageKeys.OpenId),
				"equityId": equityId
			},
			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 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,
							// openId: 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("权益产品购买成功")
										// 重新查询一遍
										query()
									})
								},
								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)
				request(obtainUserId, optionsUser).then((res) => {
					console.log('支付宝用户编号返回：', res)
					const data = stringToJson(res.bizContent);
					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
	}
	// 权益支付检测
	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);
		});
	}
</script>
<style lang='scss' scoped>
.item{
	background-color: #22dbc8;
	color: white;
	border-radius: 20rpx;
	padding: 15px 30rpx;
	margin: 20rpx;
	font-size: 28rpx;
}
.btn {
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 30rpx;
		padding: 0 24rpx;
		font-size: 23rpx;
		box-sizing: border-box;
		margin-right: 12rpx;
		border: 1px solid #fff;
		color:  #fff;
		display: inline-block;
	}
.no{
	text-align: center;
	margin: 40rpx auto;
	font-size: 28rpx;
}
</style>