<template>
	<navBar title="九州ETC" navbgClass="nav-bgXin" fontColor='#fff' :scrollTop="scrollTop" :type="state.data.vanType"
		:userType="state.data.userType"></navBar>
	<!-- <navBgCar></navBgCar> -->
	<navBgCar :activeNum='2'></navBgCar>
	<view class="content-wrap">
		<!-- 车牌输入 -->
		<view class="car-input">
			<view class="title">请输入申办车牌</view>
			<car-number-input @numberInputResult="carNumber" inputColor='#ECF1F4'></car-number-input>
		</view>
		<!-- 车牌颜色 -->
		<view class="chepai-lane">
			<view class="title">选择车牌颜色 <text class='tips'>(非车身颜色)</text></view>
			<numberplate-color :numberplate="state.data.vehiclePlateNumber" :type="state.data.vanType"
				:numberplateCor='state.data.vehiclePlateColor' @numberplateResult="checkNumberplateColor">
			</numberplate-color>
		</view>
		<!-- 收货地址 -->
		<view class="chepai-lane">
			<view class="title">请选择或新增收货地址</view>
			<view class="address-box">
				<view class="add-con" v-if='state.data.consigneeTel'>
					<image :showLoading="true" :src="`${$imgUrl}issuance/l-icon.png`" class='l-icon' />
					<view class="c-con">
						<view class="add-txt">
							{{ state.data.region + state.data.address }}
						</view>
						<view class="flex">
							<view class="name">
								{{ state.data.consignee }}
							</view>
							<view class="phone">
								{{ state.data.consigneeTel }}
							</view>
						</view>
					</view>
					<view class="arror" @click.stop="editAddress(state.data)">
						<image :src="`${$imgUrl}issuance/r-more.png`" class="icon" mode='aspectFit'></image>
					</view>
				</view>
				<view class="add-btn" @click="state.show = true">
					<image :showLoading="true" :src="`${$imgUrl}issuance/add-btn.png`" class='l-icon' />
					<text class='txt'>添加收货地址</text>
				</view>
			</view>
		</view>
		<view class="action">
			<button type="default" class="button" @click="nextAction()">
				下一步
			</button>
		</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"
						mode="aspectFit"></image>
				</view>
			</view>

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

</template>

<script setup lang="ts">
	/*导航*/
	import navBgCar from "./components/nav-bg-car1";
	import carNumberInput from "./components/car-number-input.vue";
	import numberplateColor from "./components/layout-numberplate-color";
	import { getItem, StorageKeys } from "@/utils/storage";
	import navBar from "@/components/nav-bar/nav-bar2.vue";
	import { onLoad, onShow, onPageScroll, onUnload } from "@dcloudio/uni-app";
	import {
		plateCheck,
		addressQueryNew,
		orderAdd, orderDetailQuery
	} from "@/utils/network/api.js";
	import { requestNew } from "@/utils/network/request.js";
	import { reactive, ref } from "vue";
	import { msg, noticeUser,navTo } from "@/utils/utils";

	const scrollTop = ref(0);
	const state = reactive({
		data: {
			vehiclePlate: undefined, //车牌号
			vehiclePlateNumber: "", //车牌号
			vehiclePlateColor: 0, //车牌颜色
			vanType: 1, //车牌类型
			userType: 1,
			whetherToMail: getItem(StorageKeys.OpenId) ? true : "", //是否需要邮寄 小程序默认邮寄 true邮寄||1不邮寄 不登录为1
			orderSource: "WECHAT",
			opId: "",
			consignee: "", //收货人
			consigneeTel: "", //收货电话
			region: "",
			address: "",
			postalCode: "",
			longitude: "",
			latitude: "",
			detailedAddress: '',  //通过经纬度转的地址
			cardType: '',//卡类型
			productId: ""
		},
		show: false,
		addressArray: [],
		isSign: '',
		isValueCard: '',
		agreeURL: "",
		orderId: "",
		totalAmount: "",
		equityId: ""
	});
	/* 选择车牌颜色 */
	const checkNumberplateColor = (item : any) => {
		state.data.vehiclePlateColor = item;
	};

	const goToAddAddress = () => {
		navTo(
			"/subpackage/orders/addAddress",
		);
	};
	const editAddress = (val) => {
		console.log("val", val)
		navTo(
			 `/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 = () => {
		uni.showLoading({
			title:"请稍后",
			mask: true //是否显示透明蒙层，防止触摸穿透
		})
		if (!state.data.vehiclePlate) {
			uni.hideLoading()
			msg("请输入申办车牌");
			return;
		}
		noticeUser(() => {
			nextActionRequest()
		});
	};
	const nextActionRequest = () => {
		if (!state.data.vehiclePlate) {
			uni.hideLoading()
			msg("请输入申办车牌");
			return;
		}

		state.data.vehiclePlate = state.data.vehiclePlate.trim();


		if (state.data.vehiclePlate.length < 7) {
			uni.hideLoading()
			msg("请输入正确的申办车牌");
			return;
		}
		if (!state.data.region) {
			uni.hideLoading()
			msg("请选择收货地址");
			return;
		}
		//1.优先车牌校验 2.在进行订单创建
		var vehicleData = {
			vehiclePlate: state.data.vehiclePlate,
			vehiclePlateColor: state.data.vehiclePlateColor,
		};
       
		const options = {
			type: 2,
			data: vehicleData,
			method: "POST",
			showLoading: true,
		};
		console.log("车牌信息", options)
		// 车牌校验有问题 还没改好
		requestNew(plateCheck, options).then((res) => {
			nextAddress()
		});
	}
	onLoad((option : any) => {
		state.data.vanType = option.vanType; //1客车  2货车
		state.data.opId = getItem(StorageKeys.OpenId);
		state.data.userType = option.userType;
		state.data.productId = option.productId;
		state.isValueCard = option.isValueCard
		state.data.cardType = option.cardType
		state.totalAmount = option.totalAmount;
		state.equityId = option.equityId;
		console.log("订单选择推广发行产品接口", option)
		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) => {
		let opid = getItem(StorageKeys.OpenId)

		if (opid) {
			var data = {
				openId: opid,
			};
			getAddressArray(data)
		}
		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 getAddressArray = (data) => {
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};
		requestNew(addressQueryNew, options).then((res) => {
			const data = res;
			console.log("111", data);
			state.addressArray = data.result ? data.result : [];
			for (var i = 0; i < state.addressArray.length; i++) {
				if (state.addressArray[i]['defaultAddress'] == 1) {
					state.data = {
						...state.data,
						...state.addressArray[i],
					};
				}
			}
		});
	}
	let addKey = false //表示未添加
	const nextAddress = () => {
		var data = state.data;
		// #ifdef MP-ALIPAY
		data.orderSource = 'ALI'
		// #endif
		const options = {
			type: 2,
			data: data,
			method: "POST",
			showLoading: true,
		};

		requestNew(orderAdd, options).then((res) => {
			console.log("res===", res);
			if (res.statusCode === 600) {
				orderGoAction();
			} else {
				const data = res;
				state.orderId = data.orderId
				console.log(data);
				addKey = true
				var vehicleId = state.data.vehiclePlate + "_" + state.data.vehiclePlateColor
				console.log("state.data.vehiclePlate", state.data.vehiclePlate, state.data.vehiclePlateColor, vehicleId)
				if (state.data.userType == 1) {
					navTo(
						 `/subpackage/orders/opening-account-people?orderId=${data.orderId}&&vehiclePlateColor=${state.data.vehiclePlateColor}&isSign=${state.isValueCard}&vanType=${state.data.vanType}&vehicleId=${vehicleId}`,
					);
				} else {
					navTo(
						`/subpackage/orders/opening-account-unit?orderId=${data.orderId}&&vehiclePlateColor=${state.data.vehiclePlateColor}&isSign=${state.isValueCard}&vanType=${state.data.vanType}&vehicleId=${vehicleId}`,
					);
				}
			}
		});
	}
	//按照订单阶段去跳转
	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,
		};
		requestNew(orderDetailQuery, options).then((res) => {
			const data = res;
			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} `,
			});
		}
	};
</script>

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

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

		.title {
			font-size: 30rpx;
			font-weight: bold;
			line-height: 30rpx;
			margin-bottom: 30rpx;
			font-family: SourceHanSansSC, SourceHanSansSC;
			color: #01243A;
		}

		.car-input {
			background-color: #fff;
			padding: 40rpx 30rpx;
			border-radius: 12rpx;
		}

		.chepai-lane {
			background-color: #fff;
			padding: 30rpx;
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			border-radius: 12rpx;

			.tips {
				font-size: 24rpx;
				color: #999999;
				margin-left: 20rpx;
				font-weight: normal;
			}
		}

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

			.title {
				font-size: 30rpx;
				font-weight: bold;
				line-height: 30rpx;
				margin-bottom: 30rpx;
				font-family: SourceHanSansSC, SourceHanSansSC;
				color: #01243A;


			}
		}
	}

	.address-box {


		.add-con {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.l-icon {
				flex-shrink: 0;
				width: 74rpx;
				height: 74rpx;
			}

			.c-con {
				box-sizing: border-box;
				padding: 0 20rpx;
				flex: 1 1 auto;

				.add-txt {
					font-size: 28rpx;
					font-family: SourceHanSansSC, SourceHanSansSC;
					font-weight: 500;
					color: #111111;
				}

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

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

			.arror {
				flex-shrink: 0;

				.icon {
					width: 24rpx;
					height: 24rpx;
				}
			}
		}



		.add-btn {
			background: #F8F4E7;
			border-radius: 14rpx;
			border: 1rpx solid #CCB375;
			display: flex;
			align-items: center;
			justify-content: center;
			height: 80rpx;
			margin-top: 30rpx;

			.l-icon {
				width: 34rpx;
				height: 34rpx;
			}

			.txt {
				margin-left: 10rpx;
				font-family: SourceHanSansSC, SourceHanSansSC;
				font-weight: 400;
				font-size: 28rpx;
				color: #CCB375;
				line-height: 34rpx;
			}
		}


	}


	.action {
		// padding-bottom: 100rpx;
		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;
		}
	}

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

	.address-line {
		padding: 20px;

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

		.xing {
			width: 68rpx;
			height: 68rpx;
			background: rgba(0, 52, 87, 0.2);
			border-radius: 50%;
			font-size: 26rpx;
			font-weight: 400;
			color: #fff;
			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;
			}
		}
	}
</style>