<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">
						尊敬的车主用户，为保障您与我们的权益，ETC办理需签署电子合同，该合同严格遵循《电子签名法》，与纸质合同具有同等法律效力。
					</view>
				</view>
				<view class="item item2">
					<view class="l-icon"></view>
					<view class="r-txt">
						签署前请您认真阅读合同中条款内容，然后完成合同签署，若您有疑问可随时联系客服解答，感谢您的理解与支持！
					</view>
				</view>
	
			</view>
			
			<view class="as-layout-horizontal agreement">
				<view class="checked-group" @click="checkboxChange">
					<!-- <checkbox :checked="state.checked" style="transform: scale(0.65)" /> -->
					<view class="column-checkbox">
						<view class="checkbox-icon" :class="{'is-checked': state.checked}">
							<u-icon name="checkbox-mark" :color="state.checked ? '#FFFFFF' : '#FFFFFF'"></u-icon>
						</view>
					</view>
					<text class='txt'>签署协议</text>
				</view>
				<!-- <text v-for="(item,index) in state.agreeURL" class="txt xieyi" @click="downAuthD(item)">《{{item.name}}》</text> -->
			</view>
		</view>
	</view>
	
	<FixedFooter>
		<view class="footer-action">
			<!-- <button type="default" class="button" @click="goSign()">去签署</button> -->
			<button type="default" class="button" @click="queryAgreement()">下一步</button>
		</view>
	</FixedFooter>
</template>

<script setup lang="ts">
	import FixedFooter from '@/components/common/FixedFooter.vue'
	import {
		onLoad, onShow
	} from "@dcloudio/uni-app";
	import {
		reactive,
		ref
	} from "vue";
	import {
		getOpenId,
		envs, payQuery, agreementInSertOrder, agreeOrderProdcut, contractQuery, accountSign
	} from "@/utils/network/api.js";
	import { requestNew } from "@/utils/network/request.js";

	import {
		stringToJson
	} from "@/utils/network/encryption";
	import navBgCar from "./components/nav-bg-car1";
	import navBar from "@/components/nav-bar/nav-bar2.vue";
	import {
		msg, navTo
	} from "@/utils/utils";
	
	let signFlag = "NO";//触发按钮标识

	const savaHandle = () => {
		console.log("state.productId.length", state.productId.length, "111", state.typeScanCode)
		if (state.typeScanCode == 2) {
			console.log("233")
			// 扫码进来
			if (state.checked) {
				agreementConfirm().then((value) => {
					console.log("协议确认", value)
					msg("协议确认成功");
				})
			} else {
				msg("请勾选协议");
			}

		} else {
			console.log("state.checked", state.checked)
			if (state.checked) {
				agreementConfirm().then((value) => {
					console.log("协议确认", value)
					navTo(
						`/subpackage/orders/order_payment?orderId=${state.orderId}&&clientFee=${state.clientFee}&&id=${state.id}&&isValueCard=${state.isValueCard}&vehicleId=${state.vehicleId}`,
					);
				})

			} else {
				msg("请勾选协议");
			}
		}

	};
	const downAuthD = (item) => {
		console.log('=======123', item)
		console.log("uni.env.USER_DATA_PATH '", uni.env.USER_DATA_PATH + '/' + '产品协议.docx')
		// 文件后缀截取
		var index = item.url.lastIndexOf("\.");
		let fileType = item.url.substring(index + 1, item.url.length);
		let arr = item.url.split(".");
		fileType = arr[arr.length - 1];

		console.log("fileType", fileType)
		uni.downloadFile({
			url: item.url,
			// filePath: uni.env.USER_DATA_PATH + '/' + item.name + '.' + fileType,
			// uni.env.USER_DATA_PATH + '/' + item.name + '.' + fileType
			success(res) {
				console.log("文件下载返回数据：", res)
				const filePath = res.tempFilePath
				console.log("filePath", filePath)
				uni.openDocument({
					filePath: filePath,
					fileType: fileType,
					showMenu: true, //关键点
					success: function (res) {
						state.isWatchContract = true
					},
					fail: function (err) {
						msg("打开文档失败");
					}
				});
			},
			fail: function (err) {
				msg("下载文档失败");
				console.log("err", err)
			},
			complete(res) {

			}
		})
	}
	//获取微信小程序openid
	const getOpenID = () => {
		uni.login({
			provider: "weixin",
			success: function (e) {
				getOpenid(e.code);
			},
		});
	};
	const getOpenid = (code) => {
		const options = {
			type: 2,
			data: {
				"jsCode": code
			},
			method: "POST",
			showLoading: true,
		};
		// #ifdef MP-WEIXIN
		requestNew(getOpenId, options).then((res) => {
			const result = res;
			console.log("获取微信小程序openid", result);
			const openidData = stringToJson(result.bizContent);
			console.log("获取微信小程序openid====", openidData);
			state.openid = openidData.openid;
			refresh();
		});
		// #endif
	}

	// 协议确认接口
	const agreementConfirm = () => {
		const options = {
			type: 2,
			data: {
				orderId: state.orderId,
				protocol: state.checked ? 1 : 0,
				agreements: state.agreements
			},
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await requestNew(agreeOrderProdcut, options);
			const data = res;
			console.log("确认协议", data)

			resolve(data);
		}).catch((error) => {
			reject(error);
		});
	};
	onLoad((option : any) => {
		state.orderId = option.orderId;
		state.isValueCard = option.isValueCard;
		state.redirectUrl = option.redirectUrl // 重定向页面
		console.log("传递过来的参数", option)
		console.log("查协议", envs[process.env.NODE_ENV].baseUrl)
		state.id = option.id;
		state.vehicleId = option.vehicleId;
		// getOpenID();
		if (option.typeScanCode) {
			state.typeScanCode = option.typeScanCode
			console.log("state.agreeURL", state.agreeURL)
		}
		// queryAgreement();

	});
	onShow(() => {
		contractRequest()
	})
	const state = reactive({
		openid: "",
		orderId: "",
		clientFee: undefined,
		id: "",
		options2: [{
			text: '删除',
			style: {
				backgroundColor: '#F56C6C'
			}
		}],
		list: [],
		productMoney: 0,
		allMoney: 0,
		productId: [],
		// 弹框
		type: 'center',
		msgType: 'success',
		messageText: '这是一条成功提示',
		value: '',
		detailsObj: '',
		isValueCard: "",
		dataArray: [],
		checked: false,
		agreeURL: [],
		typeScanCode: 0,//扫码进来得
		vehicleId: "",
		agreements: [],
		isSign: false,
		isWatchContract: false,
		redirectUrl: ''
	});
	// 查协议
	const queryAgreement = () => {
		if(signFlag === "NO") return;
		const options = {
			type: 2,
			data: {
				orderNo: state.orderId, //订单编号
				customerId: "",
				protocol: state.checked ? 1 : 0,
			},
			method: "POST",
			showLoading: true,
		};
		if (state.isSign) {

			if (state.checked) {
				requestNew(agreementInSertOrder, options).then((res) => {
					goNextPage()
				});
			} else {
				msg("请勾选协议");
			}
		} else {
			goNextPage()
		}

	}
	
	const goNextPage = () => {
		if (state.redirectUrl) {
			navTo(decodeURIComponent(state.redirectUrl))
		} else {
			navTo(
				`/subpackage/orders/order_payment?orderId=${state.orderId}&&clientFee=${state.clientFee}&&id=${state.id}&&isValueCard=${state.isValueCard}&vehicleId=${state.vehicleId}`,
			);
			
		}
	}
	
	const checkboxChange = () => {
		  wx.navigateToMiniProgram({
		    appId: 'wx371151823f6f3edf', // 电子签appId; 联调时, 请使用demo小程序appId: 'wx371151823f6f3edf'
		    path: 'pages/home/home-index', // 跳转的页面路径，可选，默认跳转到目标小程序首页; 签署时，需使用后台API返回的完整链接（类似pages/guide?id=xxx&foo=bar）
		    extraData: { // 需要传递给目标小程序的数据，可选；签署时，腾讯电子签小程序未使用到该参数
		      foo: 'bar'
		    },
		    envVersion: 'release', // 跳转正式或demo小程序，都需要传 'release'
		    success(res) {
		      // 成功跳转到目标小程序后的回调函数
			  console.log(res)
		    },
		    fail(res) {
				console.log(res)
		      // 跳转失败的回调函数
		    }
		  })
		
		// if (state.isWatchContract) {
		// 	state.checked = !state.checked;
		// } else {
		// 	msg("请先阅读相关文件");
		// }
	};
	const refresh = () => {
		let source = ""
		// #ifdef MP-ALIPAY
		source = "ALI"
		// #endif
		// #ifdef MP-WEIXIN
		source = "WECHAT"
		// #endif
		var data = {
			orderNo: state.orderId,
			wxOpenId: state.openid,
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		console.log("输出内容", options);
		requestNew(payQuery, options).then((res) => {
			const data = res
			console.log(data);
			if (data.paymentStatus == 'ALLSUCCESS') {
				state.allMoney = data.sumFee * 0.01
				return;
			}
			state.dataArray = data.datas;
			// HANDLE("办理费",1){},
			//     MARGIN("保证金",2){},
			//     PRESTORE("预存金",3){},
			//     EQUITY("权益费",4){},
			for (let i = 0; i < state.dataArray.length; i++) {
				if (state.dataArray[i].payType === 'HANDLE') {
					state.dataArray[i].payName = '权益金'
				} else if (state.dataArray[i].payType === 'MARGIN') {
					state.dataArray[i].payName = '保证金'
				} else if (state.dataArray[i].payType === 'PRESTORE') {
					state.dataArray[i].payName = '预存金'
				} else if (state.dataArray[i].payType === 'EQUITY') {
					state.dataArray[i].payName = '权益费'
				} else {
					state.dataArray[i].payName = '未知费'
				}
				// SUCCESS("支付成功",1){},
				//     PAYING("支付中",2){},
				//     FAILED("支付失败",3){},
				//     UNPAY("未支付",4){},
				//     CLOSED("已关闭",5){},
				//     CANCELED("已撤销",6){},
				//     REFUND("转入退费",7){},
				if (state.dataArray[i].payStatus === 'SUCCESS') {
					state.dataArray[i].payStatusName = '已支付'
				} else if (state.dataArray[i].payStatus === 'PAYING') {
					state.dataArray[i].payStatusName = '支付中'
				} else if (state.dataArray[i].payStatus === 'FAILED') {
					state.dataArray[i].payStatusName = '支付失败'
				} else if (state.dataArray[i].payStatus === 'UNPAY') {
					state.dataArray[i].payStatusName = '未支付'
				} else if (state.dataArray[i].payStatus === 'CLOSED') {
					state.dataArray[i].payStatusName = '已关闭'
				} else if (state.dataArray[i].payStatus === 'CANCELED') {
					state.dataArray[i].payStatusName = '已撤销'
				} else if (state.dataArray[i].payStatus === 'REFUND') {
					state.dataArray[i].payStatusName = '转入退费'
				} else {
					state.dataArray[i].payStatusName = '未知'
				}
				state.allMoney += state.dataArray[i]["fee"] * 0.01
			}
			console.log("state.dataArray", state.dataArray)
		});
	}
	// 去签署协议
	const sign = () => {
		const options = {
			type: 2,
			data: {
				orderId: state.orderId, //订单编号

			},
			method: "POST",
			showLoading: true,
		};
		requestNew(accountSign, options).then((res) => {
			uni.navigateToMiniProgram({
				appId: 'wxeee4ac6e61915479',
				path: `/pages/externel/view/view?random=${res.random}&envType=product`,
				envVersion: 'release',
				fail: (error) => {
					console.log(error);
				}
			})
			console.log("去签署协议", res)
		});
	}
	
	// 查询是否签署协议
	const contractRequest = () => {
		const options = {
			type: 2,
			data: {
				orderNo: state.orderId, //订单编号
			},
			method: "POST",
			showLoading: true,
		};
		requestNew(contractQuery, options).then((res) => {
			if (res.flag) {
				state.isSign = true
			} else {
				state.isSign = false
			}
			signFlag = "YES"
			console.log("查询是否签署协议", res)

			// let data = res;
			// let supAgreeArr = data.agreements;
			// if (state.agreeURL && state.agreeURL.length === 0) {
			// 	state.agreeURL = [];
			// 	console.log("data==", supAgreeArr)
			// 	for (var m = 0; m < supAgreeArr.length; m++) {
			// 		let obj = {}
			// 		for (let key in supAgreeArr[m]) {
			// 			obj['name'] = key;
			// 			obj['url'] = supAgreeArr[m][key];
			// 			state.agreeURL.push(obj);
			// 		}
			// 	}
			// }
			console.log("查协议", state.agreeURL, state.agreements)
		});
	}
	
	// 签署
	const goSign = () => {
		
	}
</script>

<style>
	page{
		background: #E9EDF0;
	}
</style>

<style lang="scss" scoped>
	.t-card {
		margin: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 50rpx 30rpx;
	}
	.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;
	}
	
	.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;
		}
	}

	.agreement {
		font-size: 30rpx;
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		align-items: center;

		.txt {
			font-size: 24rpx;
			font-family: SourceHanSansCN, SourceHanSansCN;
			font-weight: 400;
			color: #111111;
		}

		.xieyi {
			color: #999;
			text-decoration: underline;
		}
	}
	
	.checked-group{
		display: flex;
		align-items: center;
	}
	.column-checkbox{
		display: flex;
		align-items: center;
		flex: 1;
		.u-icon{
			font-size: 24rpx;
			color: #004576;
		}
		.checkbox-icon{
			width: 32rpx;
			height: 32rpx;
			border: 1px solid #c8c9cc;
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-right: 20rpx;
			margin-left: 24rpx;
		}
		.is-checked{
			border-color: #004576;
			background-color: #004576;
		}
		.u-icon{
			margin-right: 10rpx;
		}
	}
</style>