<template>
	<navBar title="九州ETC" :scrollTop="scrollTop" :type="state.data.type" :userType="state.data.userType"></navBar>
	<navBgCar></navBgCar>
	<view class="content-wrap">
		<!-- 车牌输入 -->
		<view class="car-input">
			<view class="title">请输入申办车牌</view>
			<car-number-input @numberInputResult="carNumber"></car-number-input>
		</view>
		<!-- 车牌颜色 -->
		<view class="chepai-lane">
			<view class="title">选择车牌颜色</view>
			<numberplate-color :numberplate="state.data.vehiclePlateNumber" :type="state.data.type"
				@numberplateResult="checkNumberplateColor">
			</numberplate-color>
		</view>
		<view style="margin-top: 30rpx" class="action">
			<button type="default" class="button" @click="nextAction()">
				下一步
			</button>
		</view>
		<view>

		</view>
	</view>
	<!-- 地址弹窗 -->
	<u-popup mode="bottom" v-model="state.show">
		<view class="address-line">
			<view v-if="state.addressArray" v-for="(item, index) in state.addressArray" :key="index"
				@click="addressSelected(item)" style="margin-bottom: 60rpx" class="flex-bettwen">
				<view class="flex">
					<view class="xing">
						{{ item.consignee.charAt(0) }}
					</view>
					<view class="content">
						<view class="flex">
							<view class="name">
								{{ item.consignee }}
							</view>
							<view class="phone">
								{{ item.consigneeTel }}
								<text class="default" v-if="item.defaultAddress==1">默认</text>
							</view>
						</view>
						<view class="address">
							{{ item.region + item.address }}
						</view>
					</view>
				</view>
				<view @click.stop="editAddress(item)" style="margin-left: 80rpx" class="picture">
					<image :showLoading="true" :src="`${$imgUrl}applyCard/edit.png`"
						style="width: 48rpx; height: 48rpx"></image>
				</view>
			</view>

			<view :style="state.addressArray ? 'margin-top: 60rpx;' : ''" class="action-bottom">
				<button type="default" class="button" @click="goToAddAddress()">
					添加收货地址
				</button>
			</view>
		</view>
	</u-popup>

</template>

<script setup lang="ts">
	/*导航*/
	import navBgCar from "./components/nav-bg-car2";
	import carNumberInput from "@/components/car-number-input/car-number-input.vue";
	import numberplateColor from "./components/layout-numberplate-color";
	import { getItem, StorageKeys } from "@/utils/storage";
	import { stringToJson } from "@/utils/network/encryption";
	import navBar from "@/components/nav-bar/nav-bar2.vue";
	import { onLoad, onShow, onPageScroll, onUnload } from "@dcloudio/uni-app";
	import {
		addressQuery,
		etcCreatOrder,
		etcVehiclePlateVer,
		searchOrder,
		productReCode,
		getGlobalParam,
		infoQuery,
		envs,
		addProduct,
		isSubmitOrderApi
	} from "@/utils/network/api.js";
	import { request } from "@/utils/network/request.js";
	import { reactive, ref } from "vue";
	import { msg, noticeUser } from "@/utils/utils";
	// import  amap from "../../lib/amap-uni.130.js";//引入高德地图小程序插件
	const scrollTop = ref(0);
	const state = reactive({
		data: {
			vehiclePlate: undefined, //车牌号
			vehiclePlateNumber: "", //车牌号
			vehiclePlateColor: 0, //车牌颜色
			type: "1", //车牌类型
			userType: 1,
			whetherToMail: getItem(StorageKeys.OpenId) ? 0 : "", //是否需要邮寄 小程序默认邮寄 0邮寄||1不邮寄 不登录为1
			orderSource: "WECHAT",
			opId: "",
			consignee: "", //收货人
			consigneeTel: "", //收货电话
			region: "",
			address: "",
			postalCode: "",
			promoteId: "",
			longitude: "",
			latitude: "",
			detailedAddress: '',  //通过经纬度转的地址
			cardType: ''  //卡类型
		},
		show: false,
		addressArray: [],
		isSign: '',
		isValueCard: '',
		agreeURL: "",
		orderId: "",
		totalAmount: "",
		equityId: ""
	});
	// const globalParam = () => {
	// 	const options = {
	// 		type: 2,
	// 		data: {
	// 			"loginSource": getItem("loginSource")
	// 		},
	// 		method: "POST",
	// 		showLoading: true,
	// 	};
	// 	request(getGlobalParam, options).then((res) => {
	// 		const result = stringToJson(res.bizContent);
	// 		console.log("配置", result);
	// 	});
	// }

	// const getInfo = () => {
	// 	//参数说明
	// 	let options = {
	// 		type: 2, //type: 2,JSON格式提交数据(默认表单形式提交)
	// 		data: {
	// 			businessType: 'USER_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);
	// 		});
	// }
	/* 选择车牌颜色 */
	const checkNumberplateColor = (item : any) => {
		state.data.vehiclePlateColor = item;
	};

	const goToAddAddress = () => {
		uni.navigateTo({
			url: "/subpackage/orders/addAddress",
		});
	};
	const editAddress = (val) => {
		console.log("val", val)
		uni.navigateTo({
			url: `/subpackage/orders/editAddress?content=` + JSON.stringify(val),
		});
	};
	const carNumber = (val : any) => {
		state.data.vehiclePlate = val;
		state.data.vehiclePlateNumber = val;
	};

	const addressSelected = (val : any) => {
		console.log("val", val)
		state.data = {
			...state.data,
			...val,
		};
		console.log("state.data.address", state.data.address)
		state.show = false;
	};
	const nextAction = () => {
		if (!state.data.vehiclePlate) {
			msg("请输入申办车牌");
			return;
		}
		noticeUser(() => {
			nextActionRequest()
		});
	};
	const nextActionRequest = () => {
		if (!state.data.vehiclePlate) {
			msg("请输入申办车牌");
			return;
		}
		state.data.vehiclePlate = state.data.vehiclePlate.trim();

		console.log(state.data.vehiclePlate);
		console.log(state.data.vehiclePlate.length);

		if (state.data.vehiclePlate.length < 7) {
			msg("请输入正确的申办车牌");
			return;
		}
		//1.优先车牌校验 2.在进行订单创建
		isSubmitOrderRequest(state.data.vehiclePlate, state.data.vehiclePlateColor).then((item) => {
			console.log("item.data.data.canSubmit", item.data.data.canSubmit)
			if (item.data.data.canSubmit == 1) {
				var vehicleData = {
					vehiclePlate: state.data.vehiclePlate,
					vehiclePlateColor: state.data.vehiclePlateColor,
				};

				const options = {
					type: 2,
					data: vehicleData,
					method: "POST",
					showLoading: true,
				};
				console.log("车牌信息", options)
				request(etcVehiclePlateVer, options).then((res) => {
					uni.redirectTo({
						url: `/subpackage/orders/essential-information-two?promoteId=${getItem("promoteId")}&userType=${state.data.userType}&type=${state.data.type}&isValueCard=${state.isValueCard}&totalAmount=${state.totalAmount}&equityId=${state.equityId}&vehiclePlate=${state.data.vehiclePlate}&vehiclePlateColor=${state.data.vehiclePlateColor}`,
					});
				});
			} else {
				msg(item.data.data.canSubmitMsg);
			}
		})
	}
	//按照订单阶段去跳转
	const orderGoAction = () => {
		var orderParmas = {
			vehicleId: state.data.vehiclePlate + "_" + state.data.vehiclePlateColor,
			opId: getItem(StorageKeys.OpenId),
			source: "WECHAT",
		};
		const options = {
			type: 2,
			data: orderParmas,
			method: "POST",
			showLoading: true,
		};
		request(searchOrder, options).then((res) => {
			const data = stringToJson(res.bizContent);
			console.log(data);
			orderStepGoActon(data);
		});
	};
	//订单状态舔砖
	const orderStepGoActon = (val : any) => {
		console.log("订单状态舔砖", val);
		//完成填写基本信息
		if (val.orderStep === 1) {
			if (state.data.userType === 1 || val.orderStep === 27) {
				uni.redirectTo({
					url: `/subpackage/orders/opening-account-people?orderId=${val.orderId}&&vehiclePlateColor=${val.vehiclePlateColor}`,
				});
			} else {
				uni.redirectTo({
					url: `/subpackage/orders/opening-account-unit?orderId=${val.orderId}&&vehiclePlateColor=${val.vehiclePlateColor}`,
				});
			}
		} else if (val.orderStep === 2) {
			uni.redirectTo({
				url: `/subpackage/orders/car-release?orderId=${val.orderId}&&vehiclePlateColor=${val.vehiclePlateColor}`,
			});
		} else if (val.orderStep === 3) {
			uni.redirectTo({
				url: `/subpackage/orders/choice-product?orderId=${val.orderId}`,
			});
		} else if (val.orderStep === 4) {
			uni.redirectTo({
				url: `/subpackage/orders/product-detail?orderId=${val.orderId}&&clientFee=${val.product.clientFee}&&id=${val.productId}`,
			});
		} else if (val.orderStep === 26) {
			uni.redirectTo({
				url: `/subpackage/orders/product-detail?orderId=${val.orderId}&&clientFee=${val.product.clientFee}&&id=${val.productId}`,
			});
		}
	};

	onLoad((option : any) => {
		state.data.type = option.type; //1客车  2货车
		state.data.opId = getItem(StorageKeys.OpenId);
		state.data.userType = option.userType;
		state.data.promoteId = option.promoteId;
		state.isValueCard = option.isValueCard
		state.data.cardType = option.isValueCard
		state.totalAmount = option.totalAmount;
		state.equityId = option.equityId;
		console.log("订单选择推广发行产品接口", option)
		// getInfo();
		// globalParam();
		// uni.getLocation({
		// 	type: 'wgs84',
		// 	success: function (res) {
		// 		state.data.longitude = res.longitude;
		// 		state.data.latitude = res.latitude;
		// 		console.log("成功回调", res)
		// 		uni.request({
		// 			url: 'https://apis.map.qq.com/ws/geocoder/v1/',
		// 			data: {
		// 				location: (res.latitude + "," + res.longitude),
		// 				key: 'U3EBZ-EITC3-SRW3P-3PKVC-LWFD6-SJBAE',
		// 			},
		// 			success: function (res) {
		// 				console.log("成功回调", res)
		// 				state.data.detailedAddress = res.data.result.address;  // 详细地址信息
		// 				// 处理获取到的地址信息
		// 			},
		// 			fail: function (error) {
		// 				// 请求失败的处理
		// 			}
		// 		});
		// 	}
		// });
	});

	//监听页面滚动
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop;
	});

	onShow((option) => {
		var data = {
			openId: getItem(StorageKeys.OpenId),
		};
		if (getItem(StorageKeys.OpenId)) {
			const options = {
				type: 2,
				data: data,
				method: "POST",
				showLoading: true,
			};
			request(addressQuery, options).then((res) => {
				const data = stringToJson(res.bizContent);
				console.log("111", data);
				state.addressArray = data.data ? data.data : [];
				for (var i = 0; i < state.addressArray.length; i++) {
					if (state.addressArray[i]['defaultAddress'] == 1) {
						state.data = {
							...state.data,
							...state.addressArray[i],
						};
					}
				}

			});
		}
		uni.$on('updateData', function (data) {
			var arr = [];
			arr.push(data)
			state.addressArray = arr
			console.log("dizhi", arr)
		})
		// 删除地址
		if (option) {
			if (option.del == 1) {
				state.addressArray = [];
			}
		}
	});
	onUnload(() => {
		uni.$off('updateData');
	})

	const productReCodeAction = (orderId) => {
		var data = {
			promoteId: state.data.promoteId,
			orderId: orderId,
			isValueCard: state.isValueCard,
			loginSource: getItem("loginSource")
		};
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};

		return new Promise(async (resolve, reject) => {
			const res = await request(productReCode, options);
			const data = stringToJson(res.bizContent);
			console.log("111")
			resolve(data);
		}).catch((error) => {
			console.log("222")
			reject(error);
		});
	};
	const addProductRequest = () => {
		const options = {
			type: 2,
			data: {
				orderId: state.orderId, //订单编号	
				openId: getItem(StorageKeys.OpenId), //操作人 id
				equityId: state.equityId, //权益Id
				totalAmount: state.totalAmount, //总金额
				isRepeatPurchase: 0
			},
			method: "POST",
			showLoading: true,
		};
		console.log("optionss", options);
		return new Promise(async (resolve, reject) => {
			const res = await request(addProduct, options);
			const data = stringToJson(res.bizContent);
			console.log("111")
			resolve(data);
		}).catch((error) => {
			console.log("222")
			reject(error);
		});
	}
	// 老中台-检测能否提交订单
	const isSubmitOrderRequest = (vehiclePlate, vehiclePlateColor) => {
		const options = {
			type: 2,
			data: {
				vehicleId: vehiclePlate + "_" + vehiclePlateColor
			},
			method: "POST",
			showLoading: true,
		};
		return new Promise(async (resolve, reject) => {
			const res = await request(isSubmitOrderApi, options);
			const data = stringToJson(res.bizContent);
			console.log("111")
			resolve(data);
		}).catch((error) => {
			console.log("222")
			reject(error);
		});
	}
</script>

<style lang="scss" scoped>
	.flex {
		display: flex;
		align-items: center;
	}

	.content-wrap {
		position: relative;
		margin-top: -50rpx;
		padding: 0rpx 30rpx;

		.title {
			font-size: 30rpx;
			font-family: Noto Sans S Chinese;
			font-weight: 400;
			color: #000000;
			line-height: 30rpx;
			margin-bottom: 30rpx;
		}

		.car-input {}

		.chepai-lane {
			margin-top: 60rpx;
			margin-bottom: 20rpx;
		}

		.address-lane {
			margin-bottom: 30rpx;

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

	.address-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid #dcdcdc;

		.name {
			font-size: 26rpx;
			font-family: Microsoft YaHei;
			font-weight: 400;
			color: #999999;
			font-size: 26rpx;
		}

		.phone {
			font-size: 26rpx;
			font-family: Microsoft YaHei;
			font-weight: 400;
			color: #999999;
			line-height: 26rpx;
			margin-left: 20rpx;
		}

		.arror .icon {
			width: 36rpx;
			height: 36rpx;
		}

		.address {
			font-size: 32rpx;
			font-family: Microsoft YaHei;
			font-weight: 400;
			color: #333333;
			line-height: 32rpx;
		}
	}

	.address-line {
		padding: 20px;

		.flex-bettwen {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.xing {
			width: 68rpx;
			height: 68rpx;
			background: rgba(0, 179, 139, 0.2);
			border-radius: 50%;
			font-size: 26rpx;
			font-weight: 400;
			color: #00b38b;
			line-height: 68rpx;
			text-align: center;
		}

		.content {
			margin-left: 20px;

			.name {
				font-size: 30rpx;
				font-family: Microsoft YaHei;
				font-weight: 500;
				color: #333333;
			}

			.phone {
				margin-left: 10rpx;
				font-size: 24rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				color: #999999;
				line-height: 36rpx;
			}

			.address {
				margin-top: 10rpx;
				font-size: 26rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				color: #333333;
				line-height: 36rpx;
			}

			.picture {
				width: 48rpx;
				height: 48rpx;
			}

			.editIcon {
				width: 48rpx;
				height: 48rpx;
			}
		}
	}

	.action {
		padding-bottom: 100rpx;

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

	.action-bottom {
		padding-bottom: 30rpx;

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

	:deep(.numberplates .numberplate-bg) {
		width: 190rpx;
	}

	:deep(.numberplates .numberplate) {
		margin-right: 0rpx !important;
		width: 190rpx;
	}

	:deep(.numberplates) {
		justify-content: space-between;
	}

	.default {
		border: 1rpx solid #00b38b;
		border-radius: 5rpx;
		padding: 2rpx 4rpx;
		color: #00b38b;
		margin-left: 4rpx;
	}
</style>