<template>
	<view class="content">
		<view>
			<text>车牌号：</text>
			<view style="width: 60%;flex: 3;margin: 0 15rpx;">
				<uni-data-select style="width: 100%;" v-model="state.vehiclePlate" :localdata="state.vehicPlateRange"
					@change="changeColor" :clear="false"></uni-data-select>
			</view>
			<button type="default" class="ui-btn" @click="refresh()" style="flex:0.5;height: 70rpx;line-height: 70rpx;">
				查询
			</button>
		</view>
	</view>
	<view class="details" v-if="state.isDetails">
		<view><text>车牌号</text><text class="car">{{state.details['vehiclePlate']}}</text></view>
		<view><text>车牌颜色</text><text class="car">{{getVehiclePlateColor(state.details['vehiclePlateColor'])}}</text>
		</view>
		<view><text>车主姓名</text><text class="car">{{state.details['ownerName']}}</text></view>
		<view v-if="state.details['handlerName']"><text>办理人</text><text
				class="car">{{state.details['handlerName']}}</text></view>
		<view><text>产品名称</text><text class="car">{{state.details['productName']}}</text></view>
		<view><text style="width:60%;">权益说明</text><text class="car">{{state.details['rightsDesc']}}</text></view>
		<view><text>产品金额</text><text class="car">￥{{state.details['productAmount']*0.01}}</text></view>
		<view><text>应付金额</text><text class="car">￥{{state.details['productAmount']*0.01}}</text></view>
		<view v-if="state.details['orderStep']==7"><text>订单状态</text><text class="car">{{state.words}}</text></view>
		<view v-if="state.details['orderStep']==7"><text>不通过原因</text><text class="car">{{state.details['auditReason']}}</text></view>
		<view class="noborder other-free">无其他费用</view>
		<view class="noborder yansghi" v-if="state.details['etcUserAgreement']=='QT'">
			<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 class="action" style="margin-bottom: 30rpx;" v-if="state.details['orderStep']!=7">
			<button type="default" class="ui-btn" @click="savaHandle()">
				{{state.words}}
			</button>
			<!-- <button type="default" class="ui-btn" @click="sign()" v-else>
				去签署协议
			</button> -->
		</view>
	</view>

</template>

<script setup lang="ts">
	import carNumberInput from "./components/car-number-input.vue";
	import { reactive } from "vue";
	import { onShow} from "@dcloudio/uni-app";
	import {
		navTo, hasLogin
	} from "@/utils/utils"
	import { agreementInSertOrder, contractQuery, orderQuery, accountSign, agreeOrderProdcut, envs, queryKey,orderQueryDetail } from "@/utils/network/api.js";
	import {
		getItem,
		StorageKeys,
		setItem
	} from "@/utils/storage";
	import { requestNew } from "@/utils/network/request.js";
	import { msg } from "@/utils/utils";
	import { vehiclePlateColorPai } from "@/datas/vehiclePlateColor.js";
	import {
		getVehiclePlateColor
	} from "@/datas/vehiclePlateColor";
	import {
		OrderStatus
	} from "@/datas/enum";
	import useOrderSkip from "@/composables/order/useOrderSkip";
	const tools = require("../../static/etcUtil/tools.js");
	const { gotoActiveOrder } = useOrderSkip();
	const state = reactive({
		checked: false,
		agreeURL: [],
		agreements: [],
		isSign: false,
		vehicPlateRange: [],
		idCard: "",
		mobile: "",
		vehiclePlate: "",
		vehiclePlateColor: "",
		details: {},
		isDetails: false,
		orderId: "",
		words: "",
		carAll:"",
	});
	onShow(() => {
		if (state.orderId) {
			// 签约完回来
			orderDetail(state.orderId)
		}else{
			// 没登录情况
			if (!hasLogin()) {
				quanKeyAction()
				navTo(`/login/login?back=1`)
			} else {
				uni.getLocation({
					type: 'gcj02',
					success: function (res) {
					},
				})
			   query()
			}
		}
	})
	// 从其他签约回来点查询，虽然一进来刷新了，但是可能状态没更新回来，需要再次点击查询
	const refresh=()=>{
		if (state.orderId) {
			// 签约完回来
			orderDetail(state.orderId)
		}else{
			// 没登录情况
			if (!hasLogin()) {
				quanKeyAction()
				navTo(`/login/login?back=1`)
			} else {
			   query()
			}
		}
	}
	const quanKeyAction = () => {
		var data = {};
		const options = {
			type: 2,
			data: data,
			method: "POST",
		};
		requestNew(queryKey, options).then((res) => {
			const data = res
			console.log("枚举", data)
			setItem('key', data.dictTypeAndItem)
		})
			.catch((err) => {
				console.log(err);
			});
	}

	const query = () => {
		const options = {
			type: 2,
			data: {},
			method: "POST",
			showLoading: true,
		};
		requestNew(orderQuery, options).then((res) => {
			console.log("擦寻", res,res.vehicPlateOrderList[0]['vehicPlate'])
			state.carAll=res.vehicPlateOrderList
			for (var k = 0; k < res.vehicPlateOrderList.length; k++) {
				let obj = {};
				obj['value'] = res.vehicPlateOrderList[k]['vehicPlate']
				obj['text'] = res.vehicPlateOrderList[k]['vehicPlate']
				state.vehicPlateRange.push(obj)
			}
			state.vehiclePlate=res.vehicPlateOrderList[0]['vehicPlate']
			orderDetail(res.vehicPlateOrderList[0]['orderNo'])
			
		})
	}
	// 车辆详情
	const orderDetail = (orderNo) => {
		const options = {
			type: 2,
			data: {
				orderNo
			},
			method: "POST",
			showLoading: true,
		};
		requestNew(orderQueryDetail, options).then((res) => {
			console.log("orderQueryDetail", res)
			state.details = res
			setItem('orderQueryActivate', res)
			state.isDetails = true
			state.orderId = res.orderNo
			queryAgreement()
		})
	}
	const getWrlds = () => {
		if (state.details['orderStatus'] != OrderStatus.已取消) {
			// 去支付
			if (state.details['orderStep'] == OrderStatus['完成车辆信息上传/待支付'] || state.details['orderStep'] == OrderStatus['待支付2']) {
				state.words = "去支付"
			} else if (state.details['orderStep'] == OrderStatus['已支付/待签约']) {
				// 去签约
				state.words = "去签约"
			} else if (state.details['orderStep'] == OrderStatus['待激活']) {
				// 待激活
				state.words = "去激活"
			} else if (state.details['orderStep'] == OrderStatus['待审核']) {
				// 待审核
				state.words = "待审核"
			} else if (state.details['orderStep'] == OrderStatus['审核不通过']) {
				// 待激活
				state.words = "审核不通过"
			}
		}
	}
	const savaHandle = () => {
		if(state.words == "待审核" || state.words == "审核不通过"){
			return;
		}else{
			
			if (state.checked) {
				if (state.details['orderStatus'] != OrderStatus.已取消) {
					// 去支付
					if (state.details['orderStep'] == OrderStatus['完成车辆信息上传/待支付'] || state.details['orderStep'] == OrderStatus['待支付2']) {
						if(state.details['etcUserAgreement']=='QT'){
							agreementConfirm().then((value) => {
								console.log("协议确认", value)
								let vehicleId = state.details['vehiclePlate'] + "_" + state.details['vehiclePlateColor']
								// qtSign 1 去签约
								// orderQuery 1 订单查询 0正常订单
								// cardType2:储值卡 1:记账卡 3:预存卡
								navTo(`/subpackage/orders/order_payment?orderId=${state.orderId}&&qtSign=${state.details['qtSign']}&vehicleId=${vehicleId}&orderQuery=1&qdSignUrl=${state.details['qdSignUrl']}&qdSignAppId=${state.details['qdSignAppId']}&xianxia=1&cardType=${state.details['cardType']}`);
							})
						}else{
							let vehicleId = state.details['vehiclePlate'] + "_" + state.details['vehiclePlateColor']
							navTo(`/subpackage/orders/order_payment?orderId=${state.orderId}&&qtSign=${state.details['qtSign']}&vehicleId=${vehicleId}&orderQuery=1&qdSignUrl=${state.details['qdSignUrl']}&qdSignAppId=${state.details['qdSignAppId']}&xianxia=1&cardType=${state.details['cardType']}`);
						}
					} else if (state.details['orderStep'] == OrderStatus['已支付/待签约']) {
						// 去签约
						if (state.details['qtSign'] == 0) {
							if(state.details['qdSignAppId']){
								uni.navigateToMiniProgram({
									appId: state.details['qdSignAppId'],
									path: state.details['qdSignUrl'],
									extraData: {},
									envVersion:'trial',
									success(res) {
										console.log(res);
									},
									complete(res) {
										console.log(res);
									},
									fail(res) {
										console.log(res);
										// 未成功跳转到车主小程序
									},
								});
							}else{
								const params = encodeURIComponent(JSON.stringify(state.details['qdSignUrl']))
								tools.toUrl(`/subpackage/personal-center/webview?url=` + params)
							}
							
						} else {
							navTo(`/subpackage/orders/release-products?orderId=${state.orderId}&orderQuery=1`);
						}
					} else if (state.details['orderStep'] == OrderStatus['待激活']) {
						// 待激活
						gotoActiveOrder(state.details)
					}
				}
			
			} else {
				msg("请勾选协议");
			}
		}
		
	}
	// 协议确认接口
	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);
		});
	};
	const checkboxChange = (e) => {
		state.checked = !state.checked;
		console.log(state.checked);
	};
	// 查协议
	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
			// 每次点击先清空
			state.agreeURL = []
			state.agreements = []
			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)
				}
			}
			// 渠道不用勾选默认true
			if(state.details['etcUserAgreement']=='QD'){
				state.checked=true
			}
			 // QT（黔通智联） QD （渠道）
			// 申办ETC的时候，判断如果这个字段的值如果是QD就不需要在九州小程序里签协议
			// if(state.details['etcUserAgreement']=='QT'){
			// 	contractRequest()
			// }else{
				// state.isSign=true
				getWrlds()
			// }
			console.log("查协议", state.agreeURL)
		});
	}
	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) {

			}
		})
	}
	// 查询是否签署协议
	// 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
	// 			// 协议签署了复选框选上
	// 			state.checked = true
	// 		} else {
	// 			state.isSign = false
	// 			state.checked = false
	// 		}
	// 		getWrlds()
	// 		console.log("查询是否签署协议", res)
	// 	});
	// }
	// 去签署协议
	// 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 changeColor = (e) => {
		state.vehiclePlateColor = e
		for(var i=0;i<state.carAll.length;i++){
			if(e==state.carAll[i]['vehicPlate']){
				state.orderId=state.carAll[i]['orderNo']
				return
			}
		}
		console.log(e)
	}
</script>

<style scoped lang="scss">
	.content {
		font-size: 30rpx;
		background-color: white;
		box-sizing: border-box;
		padding: 20rpx 30rpx 40rpx 30rpx;

		view {
			display: flex;
			margin-bottom: 4rpx;
			align-items: center;
			height: 76rpx;

			text {
				width: 30%;
				flex: 1;
			}
		}
	}

	.details {
		font-size: 30rpx;
		background-color: white;
		box-sizing: border-box;
		padding: 20rpx 30rpx;
		margin-top: 30rpx;

		view {
			border-bottom: 1rpx solid #ccc;
			padding: 6rpx 0;
			line-height: 62rpx;
			display: flex;
			justify-content: space-between;

			.car {
				font-weight: bold;
			}
		}

		.noborder {
			border-bottom: none;
		}

		.other-free {
			display: flex;
			justify-content: flex-end;
		}

		.sure {
			margin: 30rpx 0;
		}
	}

	.action {
		margin-top: 30rpx;
	}

	::v-deep .uni-select {
		box-sizing: border-box !important;
		padding-left: 10rpx !important;
		border: 1rpx solid #ccc;
		height: 60rpx !important;
	}

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

	.yansghi {
		height: auto !important;
		line-height: normal !important;
		display: flex !important;
		justify-content: flex-start !important;
		flex-shrink: 1 !important;
		flex-wrap: wrap !important;
		align-items: center !important;
	}
</style>