<template>
	<navBar title="产品详情" navbgClass="nav-bgXin" fontColor='#fff'></navBar>
	<navBgCar :activeNum='5'></navBgCar>
	<view class="content-wrap">
		<view class="value-wrapper">
			<view class="flex" v-for="(item,index) in state.dataArray">
				<view class="title"> {{item.payName}} </view>
				<view class="value">
					<text class='unit'>¥</text>
					<text>{{item.fee * 0.01}}</text>
				</view>
			</view>
			<view class="flex">
				<view class="title"> 运费 </view>
				<view class="value"> <text class='unit'>¥</text><text>0.00</text> </view>
			</view>
			<view class="flex">
				<view class="title"> 实付款 </view>
				<view class="value">
					<text class='unit'>¥</text><text>{{ state.allMoney }}</text>
				</view>
			</view>

			<view class="as-layout-horizontal agreement">
				<checkbox-group @change="checkboxChange">
					<checkbox :checked="state.checked" style="transform: scale(0.65)" />
					<text class='txt'>我已阅读并同意</text>
				</checkbox-group>
				<text v-for="(item,index) in state.agreeURL" class="txt xieyi" @click="downAuthD(item)">《{{item.name}}》</text>
			</view>
		</view>

		<view class="action">
			<button type="default" class="button" @click="savaHandle()" v-if="state.isSign">
				确认办理
			</button>
			<button type="default" class="button" @click="sign()" v-else>
				去签署协议
			</button>
		</view>

	</view>
</template>

<script setup lang="ts">
	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";

	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);

		console.log("fileType", fileType)
		uni.downloadFile({
			url: item.url,
			filePath: uni.env.USER_DATA_PATH + '/' + item.name + '.' + fileType,
			success(res) {
				const filePath = res.filePath
				console.log("filePath", filePath)
				uni.openDocument({
					filePath: filePath,
					fileType: fileType,
					showMenu: true, //关键点
					success: function (res) {
					},
					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.data);
			state.openid = openidData.openid;
		});
		// #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;
		console.log("传递过来的参数", option)
		console.log("查协议", envs[process.env.NODE_ENV].baseUrl)
		state.id = option.id;
		state.vehicleId = option.vehicleId;
		getOpenID();
		refresh();
		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
	});
	// 查协议
	const queryAgreement = () => {
		const options = {
			type: 2,
			data: {
				orderId: state.orderId, //订单编号
				status: 1

			},
			method: "POST",
			showLoading: true,
		};
		requestNew(agreementInSertOrder, options).then((res) => {
			let data = res;
			let supAgreeArr = data.data
			console.log("data==", supAgreeArr)
			for (var m = 0; m < supAgreeArr.length; m++) {
				let obj = {}
				obj['name'] = supAgreeArr[m]['name']
				for (var k = 0; k < supAgreeArr[m]['address'].length; k++) {
					state.agreements.push(supAgreeArr[m]['address'][k]['id'])
					obj['url'] = envs[process.env.NODE_ENV].baseUrl + supAgreeArr[m]['address'][k]['url']
					state.agreeURL.push(obj)
				}
			}
			console.log("查协议", state.agreeURL,state.agreements)
		});
	}
	const checkboxChange = (e) => {
		state.checked = !state.checked;
		console.log(state.checked);
	};
	const refresh = () => {
		let source = ""
		// #ifdef MP-ALIPAY
		source = "ALI"
		// #endif
		// #ifdef MP-WEIXIN
		source = "WECHAT"
		// getOpenID();
		// #endif
		var data = {
			orderId: state.orderId
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		console.log("输出内容", options);
		requestNew(payQuery, options).then((res) => {
			const data = res
			console.log(data);
			// console.log(typeof(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: {
				orderId: state.orderId, //订单编号
		
			},
			method: "POST",
			showLoading: true,
		};
		requestNew(contractQuery, options).then((res) => {
			if(res.contractState==1){
				state.isSign=true
			}else{
				state.isSign=false
			}
			console.log("查询是否签署协议", res)
		});
	}
</script>

<style lang="scss" scoped>
	.action {
		position: absolute;
		bottom: 0rpx;
		left: 0;
		height: 128rpx;
		background-color: #fff;
		border-radius: 30rpx 30rpx 0 0;
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;

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

	.value-wrapper {
		background-color: #fff;
		padding: 40rpx 30rpx;
		border-radius: 12rpx;
		font-family: SourceHanSansCN, SourceHanSansCN;

		.flex {
			padding: 20rpx 0rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.title {
				font-size: 28rpx;
				font-weight: 400;
				line-height: 28rpx;
				color: #666666;
			}

			.value {
				font-size: 30rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				line-height: 36rpx;
				color: #111111;

				.unit {
					margin-right: 4rpx;
					font-size: 22rpx;
					color: #111111;
				}
			}

		}
	}

	.content-wrap {
		position: absolute;
		top: 370rpx;
		width: 100%;
		min-height: calc(100% - 370rpx);
		box-sizing: border-box;
		padding: 0 30rpx 210rpx;

		.ul-item {
			padding: 5px 20rpx;
			display: flex;
			align-items: center;

			.item-value {
				padding: 20rpx;
				position: absolute;
				display: flex;
				align-items: center;
				// justify-content: space-around;
				width: 80%;

				.content {
					width: 48%;

					.title {
						font-size: 32rpx;
						font-family: Microsoft YaHei;
						font-weight: 400;
						color: #ffffff;
					}

					.tip {
						font-size: 24rpx;
						font-family: Microsoft YaHei;
						font-weight: 400;
						color: #ffffff;
					}
				}
			}

			.icon-tip {
				width: 100rpx;
				height: 100rpx;
			}

			.content {
				margin-left: 40rpx;
			}
		}
	}

	.del_item {
		background-color: rgb(41, 199, 207) !important;
	}

	.content-box {
		background-color: rgb(41, 199, 207);
		line-height: 80rpx;
		color: white;
		font-size: 32rpx;
		border-radius: 10rpx 0 0 10rpx;
		padding: 20rpx;
		box-sizing: border-box;
	}

	::v-deep.uni-swipe_button-text {
		font-size: 30rpx !important;
	}

	::v-deep.uni-swipe_button-group {
		font-size: 28rpx !important;
	}

	.add_all {
		width: 95%;
		margin: 0 auto;
	}

	.uni-swipe_box {
		margin-bottom: 16rpx !important;
	}

	::v-deep.uni-swipe {
		margin-bottom: 16rpx !important;
	}

	.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;
	}

	.price {
		color: white;
	}

	.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;
		}
	}
</style>