s<template>
	<view class="content">
		<view class="item" v-for="(item,index) in state.list" :key='index'>
			<view class="title">
				<view>
					<view v-if='item.children' style="display: inline-block;">
						<image :class="item.isShow?'imageChange':'imageDefault'" @click="changeIsShow(index)"
							src="../../static/image/icon-back.png" alt="" srcset=""></image>
					</view>
					<text><text>{{item.productName}}</text>&nbsp;&nbsp;<text>¥{{item.discountPrice * 0.01}}</text></text>
				</view>
				<checkbox-group @change='getValue(index)'>
					<label>
						<checkbox :value="index" />
					</label>
				</checkbox-group>
			</view>
			<view v-if="item.isShow" class="children" v-for="(itemChild,index) in item.children" :key='index'>
				<view><text>{{itemChild.productName}}</text>&nbsp;&nbsp;<text>{{itemChild.discountPrice * 0.01}}</text>
				</view>
			</view>
		</view>
		<!-- <button type="default" class="button" @click="savaHandle()">
			开通服务
		</button> -->
		<button type="default" class="button" @click="addInterestsList()">
			加购权益
		</button>
	</view>
</template>

<script setup lang="ts">
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import { reactive } from "vue";
	import { queryInterestsList } from "@/utils/network/api.js";
	import { stringToJson } from "@/utils/network/encryption";
	import { request } from "@/utils/network/request";
	import { etcQYAction } from "@/utils/network/api.js";
	import { fileURL } from "@/datas/fileURL.js";
	import navBar from "@/components/nav-bar/nav-bar2.vue";
	import navBgCar from "./components/nav-bg-car4";
	// import { setItem } from "@/utils/storage";
	import { msg } from "@/utils/utils";
	import {
		checkOrderStatus,
		orderPay,
		wechatAppID,
		wechatPayConfigId,
		wechatSecret,
		addProduct,
		queryDetails,
		getOpenidApi
	} from "@/utils/network/api";
	import {
		getItem,
		StorageKeys,
		setItem
	} from "@/utils/storage";
	const imgURL = `${fileURL}image/`;

	const state = reactive({
		openid: "",
		orderId: "",
		id: "",
		clientFee: "",
		list: [],  //权益数据
		choiceValue: [],  //选择的权益数据的下标
		choiceValueComplete: []   //选择的权益数据的具体数据
	})

	onLoad((option : any) => {
		getList(option.orderId);
		getOpenID();
		state.orderId = option.orderId;
		state.clientFee = option.clientFee;
		state.id = option.id;

		console.log("option", option)
	})
	const addInterestsList = () => {
		state.choiceValueComplete = [];
		for (var i = 0; i < state.choiceValue.length; i++) {
			state.choiceValueComplete.push(state.list[state.choiceValue[i]])
		}
		let items = encodeURIComponent(JSON.stringify(state.choiceValueComplete));

		console.log("state.openid", state);
		const data = JSON.parse(decodeURIComponent(items));
		let productId = [];
		state.productMoney = 0;
		for (var i = 0; i < data.length; i++) {
			data['isOpened'] = 'node';
			state.productMoney += data[i]['discountPrice'] / 100;
			productId.push(data[i]['equityId'])
		}
		const options = {
			type: 2,
			data: {
				orderId: state.orderId, //订单编号	
			},
			method: "POST",
			showLoading: true,
		};
		console.log("options", options);
		request(queryDetails, options).then((res) => {
			state.detailsObj = stringToJson(res.bizContent);
			console.log("state.detailsObj", state.detailsObj)
			let allMoney = (parseFloat(state.detailsObj.product.oncePrice * 0.01) + parseFloat(state.productMoney)).toFixed(2)

			const optionss = {
				type: 2,
				data: {
					orderId: state.orderId, //订单编号	
					openId: getItem(StorageKeys.OpenId), //操作人 id
					equityId: productId.toString(), //权益Id
					totalAmount: allMoney * 100, //总金额
					isRepeatPurchase: 0
				},
				method: "POST",
				showLoading: true,
			};
			console.log("optionss", optionss);
			request(addProduct, optionss).then((res) => {
				uni.navigateTo({
					url: `/subpackage/orders/order_payment?orderId=${state.orderId}&&clientFee=${state.clientFee}&&id=${state.id}&&data=${items}&&isValueCard=${state.detailsObj.isValueCard}`,
				});
			});

		});

	}


	const getList = (id) => {
		const options = {
			type: 2,
			data: { "orderId": id },
			method: 'POST',
			showLoading: true,
		}
		request(queryInterestsList, options).then((res) => {
			const data = stringToJson(res.bizContent);
			for (var i = 0; i < data.data.length; i++) {
				data.data[i]['isShow'] = false;
			}
			state.list = data.data
			console.log("222", state.list)
		})
	}
	const change = (e) => {
		console.log(e);
	}

	//获取微信小程序openid
	const getOpenID = () => {
		// #ifdef MP-WEIXIN
		uni.login({
			provider: "weixin",
			success: function (e) {
				console.log(e);
				getOpenid(e.code);
				// uni.request({
				// 	url: `https://api.weixin.qq.com/sns/jscode2session?appid=${wechatAppID}&secret=${wechatSecret}&js_code=${e.code}&grant_type=authorization_code`,
				// 	success: (res : any) => {
				// 		state.openid = res.data.openid;
				// 		setItem("QYorder", state);
				// 		console.log(res);
				// 	},
				// 	fail: (err : any) => {
				// 		uni.showToast({
				// 			title: "网络异常，请重试！" + err.errcode,
				// 			icon: "error",
				// 			duration: 500,
				// 		});
				// 		return;
				// 	},
				// });
			},
		});
		//#endif
	};
	const getOpenid = (code) => {
		const options = {
			type: 2,
			data: {
				"jsCode": code
			},
			method: "POST",
			showLoading: true,
		};
		// #ifdef MP-WEIXIN
		request(getOpenidApi, options).then((res) => {
			const result = stringToJson(res.bizContent);
			console.log("获取微信小程序openid", result);
			const openidData = stringToJson(result.data);
			state.openid = openidData.openid;
			setItem("QYorder", state);
			// setItem("QYorder", result.data);
			// state.openid = result.data.openid
		});
		// #endif
	}
	const savaHandle = () => {
		state.choiceValueComplete = [];
		for (var i = 0; i < state.choiceValue.length; i++) {
			state.choiceValueComplete.push(state.list[state.choiceValue[i]])
		}
		let items = encodeURIComponent(JSON.stringify(state.choiceValueComplete));
		console.log("state.choiceValueComplete", state.choiceValueComplete)
		console.log("openid*******", state.openid);
		//如果获取openId成功
		if (state.openid) {
			var data = {
				orderId: state.orderId,
				subOpenId: state.openid,
			};
			const options = {
				type: 2,
				data: data,
				method: "POST",
				showLoading: true,
			};
			request(etcQYAction, options).then((res) => {
				const data = stringToJson(res.bizContent);
				if (data.userState === "UNAUTHORIZED") {
					uni.navigateToMiniProgram({
						appId: "wxbcad394b3d99dac9",
						path: "pages/route/index",
						extraData: {
							appid: "wxcb1388c809fe25a9",
							sub_appid: "wx008c60533388527a",
							mch_id: "1500877591",
							sub_mch_id: "1622652848",
							nonce_str: data.nonceStr,
							sign_type: "HMAC-SHA256",
							trade_scene: "HIGHWAY",
							plate_number: data.plateNumber,
							sub_openid: data.subOpenId,
							sign: data.sign,
						},
						success(res) {
							console.log(res);
						},
						complete(res) {
							console.log(res);
						},
						fail(res) {
							console.log(res);
							// 未成功跳转到车主小程序
						},
					});
				} else if (data.userState === "NORMAL") {
					msg("已开通车主服务");
					
					uni.navigateTo({
						url: `/subpackage/orders/product-detail?orderId=${state.orderId}&&clientFee=${state.clientFee}&&id=${state.id}&&data=${items}`,
					});
				} else if (data.userState === "PAUSED") {
					msg("已暂停车主服务");
					return;
				} else if (data.userState === "OVERDUE") {
					msg("用户已开通车主服务，但欠费状态。提示用户还款，请跳转到车主服务");
					return;
				}
			});
		} else {
			//如果获取openId失败
			uni.showToast({
				title: "网络异常，请重试！",
				icon: "none",
				duration: 1000,
			});
			return;
		}
	};
	const changeIsShow = (index) => {
		console.log(index, state.list[index]['isShow'], !state.list[index]['isShow'])
		state.list[index]['isShow'] = !state.list[index]['isShow']
		console.log("state.list", state.list)
	}
	const getValue = (value) => {
		if (state.choiceValue.length == 0) {
			console.log("第一次")
			state.choiceValue.push(value)
			console.log("state.choiceValue", state.choiceValue)
		} else {
			var index = state.choiceValue.indexOf(value);
			if (index > -1) {//大于0 代表存在，
				state.choiceValue.splice(index, 1);//存在就删除
			} else {
				state.choiceValue.push(value)
			}
			console.log("state.choiceValue", state.choiceValue)
		}

	}
</script>

<style scoped lang="scss">
	.content {
		width: 100%;
		height: 100vh;
	}

	.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;
		margin: 20rpx;
	}

	.imageDefault {
		height: 40rpx;
		width: 40rpx;
		transform: rotate(270deg);
		margin-right: 12rpx;
		color: white;
	}

	.imageChange {
		height: 40rpx;
		width: 40rpx;
		transform: rotate(90deg);
		margin-right: 12rpx;
		color: white;
	}

	.item {
		width: 90%;
		margin: 10rpx auto;
		background-color: rgb(41, 199, 207);
		// height: 150rpx;
		border-radius: 20rpx;
		padding: 20rpx;
		box-sizing: border-box;
		color: white;
		font-size: 32rpx;

	}

	.item>.title {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.title>checkbox-group {
		// float: right;
	}

	.children {
		margin-left: 50rpx;
		margin-top: 16rpx;
	}

	.children>view {
		height: 50rpx;
		line-height: 50rpx;
	}

	.show {
		display: inline-block;
	}

	.hide {
		display: none;
	}

	checkbox {
		transform: scale(0.8);
	}
</style>