<template>
	<view class="selectCar-box">
		<view v-if="state.list" class="item" v-for="(item,i) in state.list" :key="i">
			<view>权益名称：{{item.name}}</view>
			<view>权益金额：￥{{item.fee * 0.01}}元</view>
			<view v-if="item.insertTime">购买时间：{{item.insertTime}}</view>
			<view v-if="item.payTime">支付时间：{{item.payTime}}</view>
			<view style="display: flex;justify-content: flex-end;">
				<text class="btn btn-primary" v-if="item.evaluate==1">已评价</text>
				<text class="btn btn-primary" v-else @click="goQuanyi(item)">去评价</text>
				<!-- 是否支付 1-已支付，2-未支付支付，3-已取消,4-已下单，未支付 -->
				<text class="btn btn-primary" v-if="item.isPay==2"
					@click="equityPaymentOrderRequest(item.id)">去支付</text>
			</view>
		</view>

		<view v-else>
			<empty title='暂无权益记录' />
		</view>
		<view style="text-align: center;margin: 20rpx;font-size: 30rpx;" v-if="state.flags">我是有底线的~</view>

	</view>
</template>

<script lang="ts" setup>
	import empty from "@/components/empty/empty.vue";
	import {
		reactive,
		ref
	} from "vue"
	import {
		msg,
		navTo
	} from "@/utils/utils"
	import {
		onLoad, onReachBottom, onShow
	} from "@dcloudio/uni-app";
	import {
		showEquityListApi, getOpenId, equityPaymentOrderApi, equityPaymentTestApi, obtainUserId, aliPayConfigIdTwo
	} 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";

	const state = reactive({
		list: [],//车辆list,
		equtyId: "",//权益id
		flags: false,
		pageSize: 10,
		pageNo: 1,
		id: "",
		totalCount: "",//总条数
	});
	const flag = ref('0') //默认选择0
	onShow(() => {
		state.pageNo = 1
		state.list = []
		showEquityListRequest()
	})
	const showEquityListRequest = () => {
		const options = {
			type: 2,
			data: {
				"openId": getItem(StorageKeys.OpenId),
				"pageNo": state.pageNo,
				"pageSize": state.pageSize,
			},
			method: 'POST',
			showLoading: true,
		}
		request(showEquityListApi, options).then((res) => {
			const data = stringToJson(res.bizContent);
			state.totalCount = data.totalCount
			let dataAll = [...state.list, ...stringToJson(res.bizContent).data]
			for (var i = 0; i < dataAll.length; i++) {
				console.log("111", dataAll[i]['insertTime'], dataAll[i]['insertTime'].replace("T", " "))
				if (dataAll[i]['insertTime']) {
					dataAll[i]['insertTime'] = dataAll[i]['insertTime'].replace("T", " ")
				}
				if (dataAll[i]['payTime']) {
					dataAll[i]['payTime'] = dataAll[i]['payTime'].replace("T", " ")
				}
			}
			state.list = dataAll

			console.log("购买2", data.totalCount, data.data, state.list.length > 0)
		})
	}
	onReachBottom(() => {
		console.log("触底了", state.list.length, state.pageNo * 10)
		if (Number(state.totalCount) == state.list.length) return state.flags = true
		if (state.list.length < state.pageNo * 10) return state.flags = true
		console.log("触底了")
		state.pageNo++
		showEquityListRequest()
	})
	const goQuanyi = (item) => {
		navTo(`/subpackage/after-sale/add-equity/equity-product-evaluation?equityId=${item.equityId}&id=${item.id}&orderId=${item.orderId}`)
	}
	// 权益支付下单
	const equityPaymentOrderRequest = (id) => {
		state.id = id
		// #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) => {
					const result = res;
					const openidData = stringToJson(result.data);
					const options = {
						type: 2,
						data: {
							id: state.id,
							payType: "EQUITY",
							wxOpenid: openidData.openid,
						},
						method: 'POST',
						showLoading: true,
					}
					request(equityPaymentOrderApi, options).then((res) => {
						const data = stringToJson(res.bizContent);
						console.log("权益支付下单", data)
						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) => {
									msg("权益产品购买成功")
									state.pageNo = 1
									state.list = []
									showEquityListRequest()
								})
							},
							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)
					request(equityPaymentOrderApi, 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)
										equityPaymentTestRequest().then((item : any) => {
											msg("权益产品购买成功")
											state.pageNo = 1
											state.list = []
											showEquityListRequest()
										})
									})
								}
							},
							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 request(equityPaymentTestApi, options);
			const data = stringToJson(res.bizContent);
			resolve(data);
		}).catch((error) => {
			reject(error);
		});

	}
</script>

<style>
	page {
		width: 100%;
		height: 100%;
		background-color: #EEF7F7;
	}
</style>
<style lang="scss" scoped>
	.selectCar-box {
		padding: 30rpx;

		.item {
			padding: 20rpx;
			align-items: center;
			font-size: 30rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(223, 223, 223, 0.8);
			border-radius: 20rpx;
			margin-bottom: 30rpx;

			.iten-left {
				align-items: center;
				font-size: 30rpx;

				text {
					margin-left: 20rpx;
					font-size: 32rpx;
					font-family: Noto Sans S Chinese;
					font-weight: 400;
					color: #333333;
				}
			}

			.choose-item {
				width: 44rpx;
				height: 44rpx;
				background: #FFFFFF;
				border: 2rpx solid #00B38B;
				border-radius: 50%;
				margin-right: 20rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				box-sizing: content-box;
			}

			.active {
				width: 34rpx;
				height: 34rpx;
				background: #00B38B;
				border-radius: 50%;
			}
		}
	}

	.btn-primary {
		border: 1px solid #00b38b;
		color: #00b38b;
	}

	.btn {
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 30rpx;
		padding: 0 24rpx;
		font-size: 23rpx;
		box-sizing: border-box;
		margin-right: 12rpx;
	}
</style>