<template>
  <view class="content">
	  <view><text>车牌号：</text><input placeholder="请输入车牌号" v-model="state.vehiclePlate"/></view>
	  <view><text>车牌颜色：</text>
		  <view style="width: 60%;">
			 <uni-data-select style="width: 100%;" v-model="state.vehiclePlateColor" :localdata="state.colorRange" @change="changeColor"
			  					:clear="false"></uni-data-select>
		  </view>
	  </view>
	  <view><text>身份证后四位：</text><input placeholder="请输入身份证后四位" v-model="state.idCard"/></view>
	  <view><text>手机号码：</text><input placeholder="请输入手机号码" v-model="state.mobile"/></view>
	  <view class="action">
	  	<button type="default" class="ui-btn" @click="query()">
	  		查询
	  	</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>权益说明</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 class="noborder other-free">无其他费用</view>
	  <view class="noborder yansghi">
	  	<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;">
	  	<button type="default" class="ui-btn" @click="savaHandle()" v-if="state.isSign">
	  		{{state.words}}
	  	</button>
	  	<button type="default" class="ui-btn" @click="sign()" v-else>
	  		去签署协议
	  	</button>
	  </view>
  </view>

</template>

<script setup lang="ts">
	import { reactive } from "vue";
	import { onLoad,onShow } from "@dcloudio/uni-app";
	import {
		navTo,hasLogin
	} from "@/utils/utils"
	import {agreementInSertOrder,contractQuery,orderQuery,accountSign,agreeOrderProdcut,envs} 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 { gotoActiveOrder} = useOrderSkip();
	const state = reactive({
		checked:false,
		agreeURL: [],
		agreements:[],
		isSign:false,
		colorRange:[],
		idCard:"",
		mobile:"",
		vehiclePlate:"",
		vehiclePlateColor:"",
		details:{},
		isDetails:false,
		orderId:"",
		words:""
	});
onShow(()=>{
	if(state.orderId){
		contractRequest()
	}
})
	onLoad(() => {
		let getColor = getItem('key')['VEHICLE_COLOR_TYPE'];
		for (var k = 0; k < getColor.length; k++) {
			let obj = {};
			obj['value'] = getColor[k]['code']
			obj['text'] = getColor[k]['name']
			state.colorRange.push(obj)
		}
		// 没登录情况
		if (!hasLogin()) {
			navTo( `/login/login?back=1`)
		}else{
			
		}
		
	})
	const query=()=>{
		if(!state.vehiclePlate){
			msg('请输入车牌号')
			return;
		}
		if(!state.vehiclePlateColor){
			msg('请选择车牌颜色')
			return;
		}
		if(!state.idCard){
			msg('请输入身份证后四位')
			return;
		}
		if(!state.mobile){
			msg('请输入手机号码')
			return;
		}
		const options = {
			type: 2,
			data: {
				vehiclePlate: state.vehiclePlate,
				vehiclePlateColor: state.vehiclePlateColor,
				idCard: state.idCard,
				mobile: state.mobile,
			
			},
			method: "POST",
			showLoading: true,
		};
		requestNew(orderQuery, options).then((res) => {
			console.log("擦寻",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="去激活"
			}
		}
	}
	const savaHandle=()=>{
		if (state.checked) {
			if(state.details['orderStatus']!= OrderStatus.已取消){
				// 去支付
				if(state.details['orderStep']==OrderStatus['完成车辆信息上传/待支付'] || state.details['orderStep']==OrderStatus['待支付2']){
					agreementConfirm().then((value) => {
						console.log("协议确认", value)
						let vehicleId=state.details['vehiclePlate']+"_"+state.details['vehiclePlateColor']
						let isValueCard=1
						// qtSign 有数据 去签约
						if(state.details['qtSign']==0 || state.details['qtSign']==1){
							isValueCard=2
						}else{
							isValueCard=1
						}
						// orderQuery 1 订单查询 0正常订单
						navTo(`/subpackage/orders/order_payment?orderId=${state.orderId}&&isValueCard=${isValueCard}&vehicleId=${vehicleId}&orderQuery=1`);
					})
				}else if(state.details['orderStep'] == OrderStatus['已支付/待签约']){
					// 去签约
					navTo(`/subpackage/orders/release-products?orderId=${state.orderId}`);
				}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=[]
			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)
				}
			}
			contractRequest()
			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) => {
			navTo(`/subpackage/orders/webView?url=${res.shortUrl}`)
			console.log("去签署协议", res.shortUrl)
		});
	}
	const changeColor = (e) => {
		state.vehiclePlateColor = e
		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: 22%;
		}
		input{
			border:1rpx solid #ccc ;
			margin-left: 20rpx;
			padding: 6rpx 10rpx;
			width: 60%;
			border-radius: 5rpx;
			box-sizing: border-box;
			height: 60rpx;
		}
	}
}
.details{
	font-size: 30rpx;
	background-color: white;
	box-sizing: border-box;
	padding: 20rpx 30rpx;
	margin-top: 30rpx;
	view{
		border-bottom: 1rpx solid #ccc;
		height: 62rpx;
		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{
	margin-left: 20rpx;
	box-sizing: border-box !important;
	padding-left: 10rpx !important;
	border:1rpx solid #ccc ;
	height: 56rpx;
}
::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>