<template>
	<view class="container">
		<view class="t-card">
			<view class="title">
				<image :src="`${$imgUrl}issuance/title-bg.png`" mode="aspectFit" class='bg'></image>
				<image :src="`${$imgUrl}issuance/bg-xia.png`" mode="aspectFit" class='bg-xia'></image>
				<view class="txt">
					微信车主服务
				</view>
			</view>
			<view class="value">
				<view class="item">
					<view class="l-icon"></view>
					<view class="r-txt">
						微信车主服务是微信支付为车主用户提供的安全便捷的智慧服务
					</view>
				</view>
				<view class="item item2">
					<view class="l-icon"></view>
					<view class="r-txt">
						本次将为贵州黔通智联科技股份有限公司开启免密支付服务，后续相关的费用将通过微信车主服务从你的微信支付账户扣除
					</view>
				</view>

			</view>
		</view>

	<!-- 	<view class="action">
			<view class="btn-tip">
				<image :src="`${$imgUrl}issuance/note.png`" mode="aspectFit" class="tip-icon"></image>
				注：签约成功后请返回本页面，再次点击{{state.channelSing=="0"?'开通服务':'恢复签约'}}
			</view>
			<button type="default" class="button" @click="savaHandle()">
				{{state.channelSing=="0"?'开通服务':'恢复签约'}}
			</button>
		</view> -->
		
		<FixedFooter>
			<view class="footer-action">
				<view class="btn-tip">
					<image :src="`${$imgUrl}issuance/note.png`" mode="aspectFit" class="tip-icon"></image>
					注：签约成功后请返回本页面，再次点击{{state.channelSing=="0"?'开通服务':'恢复签约'}}
				</view>
				<button type="default" class="button" @click="savaHandle()">
					{{state.channelSing=="0"?'开通服务':'恢复签约'}}
				</button>
			</view>
		</FixedFooter>
	</view>
</template>

<script setup lang="ts">
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import { reactive } from "vue";
	import { request, requestNew } from "@/utils/network/request.js";

	import { stringToJson } from "@/utils/network/encryption";
	import { fileURL } from "@/datas/fileURL.js";
	import { getItem, setItem } from "@/utils/storage";
	import { msg, navTo } from "@/utils/utils";
	import FixedFooter from '@/components/common/FixedFooter.vue'
	import {
		infoQuery,
		envs, channelSingQueryApi, userSign, getOpenId, reSign, getSignParams, reSignCheck
	} from "@/utils/network/api";
	const imgURL = `${fileURL}image/`;
	import useOrderSkip from "@/composables/order/useOrderSkip";
	const { gotoActiveOrder} = useOrderSkip();
	const state = reactive({
		openid: "",
		orderId: "",
		id: "",
		clientFee: "",
		checked: false,
		agreeURL: "",
		channelSing: "0",//0 正常签约  1恢复签约
		vehiclePlate: "",
		code: "",
		orderQuery:"0",
		from: "",
		vehicleId: "",
		isTestSign: 0 // 是否开始检测已经签约，大于等于1的时候再去检测
	});
	onLoad((option : any) => {
		getOpenID();
		state.orderId = option.orderId;
		if (option.from == '37') {
			state.from = option.from;
			state.vehicleId = decodeURIComponent(option.vehicleId);
		}
		
		if (option.channelSing) {
			state.channelSing = option.channelSing;
		}
		state.vehiclePlate = option.vehiclePlate;
		state.orderQuery = option.orderQuery;
		getInfo();
	});
	
	onShow(() => {
		console.log()
		if (state.isTestSign >= 1) {
			if (state.from == '37') { // 恢复签约
				isReSignCheck()
			} else {
				isUserSign()
			}
		} else {
			state.isTestSign += 1
		}
	})
	
	const checkboxChange = (e) => {
		state.checked = !state.checked;
		console.log(state.checked);
	};
	
	// 签约检测
	const isUserSign = () => {
		let options = {
			type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
			data: {
				orderNo: state.orderId,
				subOpenId: state.openid,
				signChannelType: 1,
			}, //请求参数
			method: "POST", //提交方式(默认POST)
			showLoading: true, //是否显示加载中(默认显示)
		};
		
		requestNew(userSign, options).then(res => {
			console.log(res)
			let { userState, step } = res
			if (userState === "NORMAL") {
				msg("已开通车主服务");
				// 如果是等待激活
				if(step === 'WAITING_ACTIVE'){
					gotoActiveOrder(getItem('orderQueryActivate'))
				}else{
					// 正常订单
					setTimeout(() => {
						uni.redirectTo({
							url:  `/pages/order/order?index=0`
						})
					}, 1500)
				}
				
			} else if (userState === "PAUSED") {
				msg("已暂停车主服务");
				return;
			} else if (userState === "OVERDUE") {
				msg("用户已开通车主服务，但欠费状态。提示用户还款，请跳转到车主服务");
				return;
			}
			
		})
	}
	
	// 恢复签约检测
	const isReSignCheck = () => {
		let options = {
			type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
			data: {
				subOpenId: state.openid,
				signChannelType: 1,
				vehicleId: state.vehicleId,
			}, //请求参数
			method: "POST", //提交方式(默认POST)
			showLoading: true, //是否显示加载中(默认显示)
		};
		
		requestNew(reSignCheck, options).then(res => {
			console.log(res)
			let { userState, step } = res
			if (userState === "NORMAL") {
				msg("已开通车主服务");
				// 如果是等待激活
				navTo('/pages/service/service')
				
			} else if (userState === "PAUSED") {
				msg("已暂停车主服务");
				return;
			} else if (userState === "OVERDUE") {
				msg("用户已开通车主服务，但欠费状态。提示用户还款，请跳转到车主服务");
				return;
			}
		})
	}
	
	const getInfo = () => {
		//参数说明
		let options = {
			type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
			data: {
				businessType: 'WITHHOLD_AGREEMENT' //代扣协议
			}, //请求参数
			method: "POST", //提交方式(默认POST)
			showLoading: true, //是否显示加载中(默认显示)
		};

		//调用方式
		requestNew(infoQuery, options)
			.then((res) => {
				let data = res
				if (data.textType = "URL") {
					state.agreeURL = envs[process.env.NODE_ENV].baseUrl + data.text
				}
				console.log("代扣协议", state.agreeURL);
			})
			.catch((err) => {
				console.log(err);
			});
	}
	//获取微信小程序openid
	const getOpenID = () => {
		// #ifdef MP-WEIXIN
		uni.login({
			provider: "weixin",
			success: function (e) {
				console.log(e);
				state.code = e.code
				getOpenid(e.code);
			},
		});
		// #endif
	};
	const downAuthD = () => {
		uni.downloadFile({
			url: state.agreeURL,
			filePath: wx.env.USER_DATA_PATH + '/' + '代扣协议.docx',
			success(res) {
				const filePath = res.filePath
				uni.openDocument({
					filePath: filePath,
					fileType: 'docx',
					showMenu: true, //关键点
					success: function (res) {
						msg("打开文档成功");
					},
					fail: function (err) {
						msg("打开文档失败");
					}
				});
			},
			fail: function (err) {
				msg("下载文档失败");
				console.log("err", err)
			},
			complete(res) {

			}
		})
	}
	const getOpenid = (code) => {
		const options = {
			type: 2,
			data: {
				"jsCode": code
			},
			method: "POST",
			showLoading: true,
		};
		// #ifdef MP-WEIXIN
		uni.showLoading({
			mask: true
		})
		requestNew(getOpenId, options).then((res) => {
			const result = res;
			state.openid = result.openid;
			console.log("获取微信小程序openid", state.openid);
			setItem("wxOpenid", result.openid);
			uni.hideLoading()
		}).catch(() => {
			uni.hideLoading()
		});
		// #endif
	}
	const savaHandle = () => {
		console.log("openid*******", state.openid);
		//如果获取openId成功
		if (state.openid) {
			// 从恢复签约列表进入进行恢复签约
			if (state.from == '37') {
				const options = {
					data: {
						signChannelType: 1,
						subOpenId: state.openid,
						vehicleId: state.vehicleId,
					},
					method: "POST",
					showLoading: true
				};
				requestNew(reSign, options).then((res) => {
					console.log(res, 3222);
					const data = res;
					// if (data.userState === "UNAUTHORIZED") {
					uni.navigateToMiniProgram({
						appId: "wxbcad394b3d99dac9",
						path: "pages/route/index",
						extraData: {
							appid: data.appId,
							sub_appid: data.subAppId,
							mch_id: data.mchId,
							sub_mch_id: data.subMchId,
							nonce_str: data.nonceStr,
							sign_type: data.signType,
							trade_scene: data.tradeScene,
							plate_number: data.plateNumber,
							sub_openid: data.subOpenId,
							sign: data.sign,
							channel_type: data.channelType
						},
						success(res) {
							console.log(res);
						},
						complete(res) {
							console.log(res);
						},
						fail(res) {
							console.log(res);
							// 未成功跳转到车主小程序
						},
					});
					// } else {
					// 	msg("用户已签约");
					// 	setTimeout(() => {
					// 		uni.navigateBack();
					// 	}, 1000);
					// }
				});
				return;
			}
			var data = {
				orderNo: state.orderId,
				subOpenId: state.openid,
				signChannelType: 1,
			};
			const options = {
				type: 2,
				data: data,
				method: "POST",
				showLoading: true,
			};
			requestNew(getSignParams, options).then((res) => {
				const data = res;
				console.log("data", data)
				uni.navigateToMiniProgram({
					appId: "wxbcad394b3d99dac9",
					path: "pages/route/index",
					extraData: {
						appid: data.appId,
						sub_appid: data.subAppId,
						mch_id: data.mchId,
						sub_mch_id: data.subMchId,
						nonce_str: data.nonceStr,
						sign_type: data.signType,
						trade_scene: data.tradeScene,
						plate_number: data.plateNumber,
						sub_openid: data.subOpenId,
						sign: data.sign,
						channel_type: data.channelType
					},
					success(res) {
						console.log("签约返回信息返回信息",res);
					},
					complete(res) {
						console.log(res);
					},
					fail(res) {
						console.log(res);
						// 未成功跳转到车主小程序
					},
				});
				
				
				
				// if (data.userState === "UNAUTHORIZED") {
				// 	console.log("state.channelSing",state.channelSing,state.channelSing=="0")
				// 	if (state.channelSing == "0") {
				// 		uni.navigateToMiniProgram({
				// 			appId: "wxbcad394b3d99dac9",
				// 			path: "pages/route/index",
				// 			extraData: {
				// 				appid: data.appId,
				// 				sub_appid: data.subAppId,
				// 				mch_id: data.mchId,
				// 				sub_mch_id: data.subMchId,
				// 				nonce_str: data.nonceStr,
				// 				sign_type: data.signType,
				// 				trade_scene: data.tradeScene,
				// 				plate_number: data.plateNumber,
				// 				sub_openid: data.subOpenId,
				// 				sign: data.sign,
				// 				channel_type: data.channelType
				// 			},
				// 			success(res) {
				// 				console.log("签约返回信息返回信息",res);
				// 			},
				// 			complete(res) {
				// 				console.log(res);
				// 			},
				// 			fail(res) {
				// 				console.log(res);
				// 				// 未成功跳转到车主小程序
				// 			},
				// 		});
				// 	}

				// } else if (data.userState === "NORMAL") {
				// 	msg("已开通车主服务");
				// 	console.log("开通车主服务",data)
				// 	if(data.step === 'WAITING_ACTIVE'){
				// 		// 查询订单直接去激活
				// 		// 待激活
				// 		gotoActiveOrder(getItem('orderQueryActivate'))
				// 	}else{
				// 		// 正常订单
				// 		setTimeout(() => {
				// 			uni.redirectTo({
				// 				url:  `/pages/order/order?index=0`
				// 			})
				// 		}, 1500)
				// 	}

				// } else if (data.userState === "PAUSED") {
				// 	msg("已暂停车主服务");
				// 	return;
				// } else if (data.userState === "OVERDUE") {
				// 	msg("用户已开通车主服务，但欠费状态。提示用户还款，请跳转到车主服务");
				// 	return;
				// }
			});
		} else {
			//如果获取openId失败
			uni.showToast({
				title: "网络异常，请重试！",
				icon: "none",
				duration: 1000,
			});
			return;
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		background: #E9EDF0;
		height: 100vh;
		width: 100%;
		position: relative;
		overflow: hidden;

		.t-card {
			margin: 30rpx;
			background-color: #fff;
			border-radius: 12rpx;
			padding: 50rpx 30rpx;
		}
	}

	.footer-action {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;

		.btn-tip {
			font-family: SourceHanSansSC, SourceHanSansSC;
			font-weight: 400;
			font-size: 24rpx;
			color: #CCB375;
			margin-bottom: 14rpx;
			display: flex;
			align-items: center;
			.tip-icon{
				width: 26rpx;
				height: 26rpx;
				margin-right: 10rpx;
			}
		}

		.button {
			height: 88rpx;
			background: radial-gradient(at 0% 0%, #C6B077 0%, #DFCC96 100%);
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: 400;
			color: #ffffff;
			line-height: 88rpx;
			width: 660rpx;
			margin: 0 auto;
		}
	}

	.title {
		margin: 0 auto;
		width: 322rpx;
		height: 44rpx;
		position: relative;

		.bg {
			width: 322rpx;
			height: 44rpx;
		}

		.bg-xia {
			left: 50%;
			position: absolute;
			width: 200rpx;
			height: 8rpx;
			transform: translateX(-50%);
			bottom: 0;
		}

		.txt {
			font-family: SourceHanSansSC, SourceHanSansSC;
			font-weight: bold;
			font-size: 36rpx;
			color: #004576;
			position: absolute;
			width: 322rpx;
			text-align: center;
			bottom: 0;
		}
	}

	.item {
		display: flex;
		margin-top: 60rpx;
		font-size: 28rpx;
		font-family: SourceHanSansSC, SourceHanSansSC;
		font-weight: 400;
		color: #222;
		line-height: 48rpx;

		.l-icon {
			margin-top: 20rpx;
			flex-shrink: 0;
			border-radius: 50%;
			height: 10rpx;
			width: 10rpx;
			background-color: #004576;
			margin-right: 18rpx;
			

		}
	}

	.item2 {
		margin-top: 30rpx;
	}
</style>