<template>
	<image style="
      margin-top: 20rpx;
      width: 100%;
      height: 240rpx;
      background-color: #eeeeee;
    " :src="`${$imgUrl}applyCard/car-service.png`"></image>
	<view class="title"> 微信车主服务 </view>
	<view class="value">
		<view class="content_1">
			微信车主服务是微信支付为车主用户提供的安全便捷的智慧服务
		</view>
		<view class="content_2">
			本次将为贵州黔通智联科技股份有限公司开启免密支付服务，后续相关的费用将通过微信车主服务从你的微信支付账户扣除
		</view>
		<view class="content_3">
			注：签约成功后请返回本页面，再次点击{{state.channelSing=="0"?'开通服务':'恢复签约'}}
		</view>
	</view>

	<view class="as-layout-horizontal agreement">
		<checkbox-group @change="checkboxChange">
			<checkbox :checked="state.checked" style="transform: scale(0.8)" />我已阅读并同意
		</checkbox-group>
		<text style="color:#007AFF;text-decoration: underline;" @click="downAuthD()">《代扣协议》</text>
	</view>
	<view class="action">
		<button type="default" class="button" @click="savaHandle()">
			{{state.channelSing=="0"?'开通服务':'恢复签约'}}
		</button>
	</view>
</template>

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

	import { stringToJson } from "@/utils/network/encryption";
	import { fileURL } from "@/datas/fileURL.js";
	import { setItem } from "@/utils/storage";
	import { msg } from "@/utils/utils";
	import {
		getOpenidApi,
		infoQuery,
		envs, etcQYAction, channelSingQueryApi
	} from "@/utils/network/api";
	const imgURL = `${fileURL}image/`;

	const state = reactive({
		openid: "",
		orderId: "",
		id: "",
		clientFee: "",
		checked: false,
		agreeURL: "",
		channelSing: "0",//0 正常签约  1恢复签约
		vehiclePlate: "",
		code: ""
	});
	onLoad((option : any) => {
		getOpenID();
		state.orderId = option.orderId;
		if (option.channelSing) {
			state.channelSing = option.channelSing;
		}
		state.vehiclePlate = option.vehiclePlate;
		getInfo();
	});
	const checkboxChange = (e) => {
		state.checked = !state.checked;
		console.log(state.checked);
	};
	const getInfo = () => {
		//参数说明
		let options = {
			type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
			data: {
				businessType: 'WITHHOLD_AGREEMENT' //代扣协议
			}, //请求参数
			method: "POST", //提交方式(默认POST)
			showLoading: true, //是否显示加载中(默认显示)
		};

		//调用方式
		request(infoQuery, options)
			.then((res) => {
				let data = stringToJson(res.bizContent)
				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
		request(getOpenidApi, options).then((res) => {
			const result = stringToJson(res.bizContent);
			const openidData = stringToJson(result.data);
			state.openid = openidData.openid;
			console.log("获取微信小程序openid", state.openid);
			setItem("QYorder", state);
		});
		// #endif
	}
	const savaHandle = () => {
		if (!state.checked) {
			msg("请勾选协议！")
			return;
		}
		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);
				console.log("data", data)
				if (data.userState === "UNAUTHORIZED") {
					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 {
						// 恢复签约
						const optionss = {
							type: 2,
							data: {
								plateNumber: state.vehiclePlate,
								openid: state.openid,
								channelId: '52010188925',
								tradeScene: 'HIGHWAY',
								code: state.code
							},
							method: "POST",
							showLoading: true,
						};
						request(channelSingQueryApi, optionss)
							.then((res) => {
								let data = stringToJson(res.bizContent)
								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) {

									},
									complete(res) {
										console.log(res);
									},
									fail(res) {
										console.log(res);

										// 未成功跳转到车主小程序
									},
								});

							})
							.catch((err) => {
								console.log(err);
							});
					}

				} else if (data.userState === "NORMAL") {
					msg("已开通车主服务");
					setTimeout(() => {
						uni.switchTab({
							url: "/pages/order/order"
						})
					}, 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>
	.action {
		margin-top: 40rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		padding-bottom: 30rpx;

		.button {
			height: 80rpx;
			background: linear-gradient(-90deg, #3F85FE 0%, #c9caff 100%);
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: 400;
			color: #ffffff;
			line-height: 80rpx;
		}
	}

	.title {
		text-align: center;
		margin-top: 15rpx;
		font-size: 36rpx;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #333333;
		line-height: 36rpx;
	}

	.value {
		padding: 0rpx 60rpx;
	}

	.content_1 {
		margin-top: 60rpx;
		font-size: 30rpx;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #666666;
		line-height: 58rpx;
	}

	.content_2 {
		margin-top: 50rpx;
		font-size: 30rpx;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #666666;
		line-height: 58rpx;
	}

	.content_3 {
		margin-top: 50rpx;
		font-size: 30rpx;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #ff0000;
		line-height: 58rpx;
	}

	.agreement {
		font-size: 30rpx;
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		align-items: center;
		justify-content: center;
	}
</style>