<template>
	<view>
		<form @submit="formSubmit" report-submit="true">
			<view class="addAddress">
				<view class="list borRadius14">
					<view class="item acea-row row-between-wrapper" style="border: none">
						<view class="name">姓名</view>
						<input type="text" placeholder="请输入姓名" placeholder-style="color:#ccc;" name="realName"
							:value="userAddress.realName" placeholder-class="placeholder" maxlength="4" />
					</view>
					<view class="item acea-row row-between-wrapper">
						<view class="name">联系电话</view>
						<input type="number" placeholder="请输入联系电话" placeholder-style="color:#ccc;" name="phone"
							:value="userAddress.phone" placeholder-class="placeholder" maxlength="11" />
					</view>
					<view class="item acea-row row-between-wrapper relative">
						<view class="name">所在地区</view>
						<view class="address">
							<picker mode="multiSelector" @change="bindRegionChange" @columnchange="bindMultiPickerColumnChange"
								:value="valueRegion" :range="multiArray">
								<view class="acea-row">
									<view class="picker line1">{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</view>

									<image class="abs_right" src="@/static/images/right.png" mode=""></image>
								</view>
							</picker>
						</view>
					</view>
					<view class="item">
						<view class="name">详细地址</view>
						<!-- <input type="text" placeholder="请填写具体地址" placeholder-style="color:#ccc;" name="detail"
							placeholder-class="placeholder" v-model="userAddress.detail" maxlength="100" /> -->
						<view class="ipt">
							<textarea v-model="userAddress.detail" maxlength="100" placeholder="请填写具体地址"
								placeholder-style="color:#999999;" name="detail"></textarea>
						</view>
						<view class="iconfont icon-dizhi font-color abs_right" @tap="chooseLocation"></view>
					</view>
					<view class="item acea-row row-between-wrapper">
						<view class="name">设为默认</view>
						<switch @change="ChangeIsDefault" color="#F8C008" style="transform:scale(0.8)" :checked="userAddress.isDefault"></switch>
					</view>
				</view>
				<view class="footer">
					<button class="keepBnt" form-type="submit">立即保存</button>
				</view>
				
				<!-- #ifdef MP -->
				<view class="wechatAddress" v-if="!id" @click="getWxAddress">导入微信地址</view>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view class="wechatAddress" v-if="wechat.isWeixin() && !id" @click="getAddress">导入微信地址</view>
				<!-- #endif -->
			</view>
		</form>
		<!-- #ifdef MP -->
		<!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
		<!-- #endif -->
		<!-- <home></home> -->
	</view>
</template>

<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		ref,
		reactive,
		watch
	} from "vue";
	import {
		useAppStore
	} from "@/stores/app.js";
	import {
		editAddress,
		getAddressDetail
	} from "@/api/user.js";
	import {
		getCity
	} from "@/api/api.js";
	import {
		toLogin
	} from "@/libs/login.js";
	import {
		useToast
	} from "@/hooks/useToast.js";
	import wechat from "@/libs/wechat.js";
	import Cache from "@/utils/cache";
	// #ifdef MP
	// import authorize from '@/components/Authorize';
	// #endif
	import home from "@/components/home";

	const {
		Toast
	} = useToast();
	const appStore = useAppStore();

	const regionDval = ["浙江省", "杭州市", "滨江区"];
	const cartId = ref("");
	const pinkId = ref(0);
	const couponId = ref(0);
	const id = ref(0);
	const userAddress = reactive({
		isDefault: false,
		realName: "",
		phone: "",
		detail: "",
	});
	const region = ref(["省", "市", "区"]);
	const valueRegion = ref([0, 0, 0]);
	const isAuto = ref(false);
	const isShowAuth = ref(false);
	const district = ref([]);
	const multiArray = ref([
		[],
		[],
		[]
	]);
	const multiIndex = ref([0, 0, 0]);
	const cityId = ref(0);
	const defaultRegion = ["广东省", "广州市", "番禺区"];
	const defaultRegionCode = "440113";
	const bargain = ref(false);
	const combination = ref(false);
	const secKill = ref(false);
	const preOrderNo = ref(0);
	const isFlashSale = ref(false); // 秒杀标记
	const isGroupBuy = ref(false); // 团购标记

	watch(
		() => appStore.isLogin,
		(newV) => {
			if (newV) {
				getUserAddress();
				getCityList();
			}
		}
	);

	onLoad((options) => {
		if (appStore.isLogin) {
			preOrderNo.value = options.preOrderNo || 0;
			id.value = options.id || 0;
			isFlashSale.value = options.isFlashSale === "1";
			isGroupBuy.value = options.isGroupBuy === "1";
			uni.setNavigationBarTitle({
				title: options.id ? "修改地址" : "新增地址",
			});
			getUserAddress();
			if (Cache.has("cityList")) {
				district.value = Cache.getItem("cityList");
				initialize();
			} else {
				getCityList();
			}
		} else {
			toLogin();
		}
	});

	function getCityList() {
		getCity().then((res) => {
			district.value = res.data;
			let oneDay = 24 * 3600 * 1000;
			Cache.setItem({
				name: "cityList",
				value: res.data,
				expires: oneDay * 7
			}); //设置七天过期时间
			initialize();
		});
	}

	function initialize() {
		if (district.value.length) {
			let province = [],
				city = [],
				area = [];
			let cityChildren = district.value[0].child || [];
			let areaChildren = cityChildren.length ? cityChildren[0].child || [] : [];
			district.value.forEach((item) => province.push(item.name));
			cityChildren.forEach((item) => city.push(item.name));
			areaChildren.forEach((item) => area.push(item.name));
			multiArray.value = [province, city, area];
		}
	}

	function bindRegionChange(e) {
		const mi = multiIndex.value;
		const province = district.value[mi[0]] || {
			child: []
		};
		const city = province.child[mi[1]] || {
			cityId: 0
		};
		const ma = multiArray.value;
		const value = e.detail.value;
		region.value = [ma[0][value[0]], ma[1][value[1]], ma[2][value[2]]];
		cityId.value = city.cityId;
		valueRegion.value = [0, 0, 0];
		initialize();
	}

	function bindMultiPickerColumnChange(e) {
		const column = e.detail.column;
		const value = e.detail.value;
		const ma = multiArray.value;
		const mi = multiIndex.value;
		mi[column] = value;
		switch (column) {
			case 0:
				const currentCity = district.value[value] || {
					child: []
				};
				const areaList = currentCity.child[0] || {
					child: []
				};
				ma[1] = currentCity.child.map((item) => item.name);
				ma[2] = areaList.child.map((item) => item.name);
				break;
			case 1:
				const cityList = district.value[mi[0]].child[mi[1]].child || [];
				ma[2] = cityList.map((item) => item.name);
				break;
			case 2:
				break;
		}
		multiArray.value = [...ma];
		multiIndex.value = [...mi];
	}

	function getUserAddress() {
		if (!id.value) return;
		getAddressDetail(id.value).then((res) => {
			const regionArr = [res.data.province, res.data.city, res.data.district];
			Object.assign(userAddress, res.data);
			region.value = regionArr;
			cityId.value = res.data.cityId;
		});
	}

	function chooseLocation() {
		uni.chooseLocation({
			success: (res) => {
				userAddress.detail = res.address.replace(
					/.+?(省|市|自治区|自治州|县|区)/g,
					""
				);
			},
		});
	}

	// 导入微信地址（小程序）
	function getWxAddress() {
		uni.authorize({
			scope: "scope.address",
			success: function() {
				uni.chooseAddress({
					success: function(res) {
						let addressP = {
							province: res.provinceName,
							city: res.cityName,
							district: res.countyName,
							cityId: 0,
						};
						editAddress({
								address: addressP,
								isDefault: 1,
								realName: res.userName,
								postCode: res.postalCode,
								phone: res.telNumber,
								detail: res.detailInfo,
								id: 0,
							})
							.then((res2) => {
								setTimeout(() => {
									const newAddressId = id.value ? id.value : res2.data.id;

									if (isFlashSale.value && preOrderNo.value > 0) {
										// 秒杀页面
										uni.redirectTo({
											url: `/pages/users/utils/flashSale/confirmOrder?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
										});
									} else if (isGroupBuy.value && preOrderNo.value > 0) {
										// 团购页面
										uni.redirectTo({
											url: `/pages/group_buying/paydetail?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
										});
									} else if (cartId.value) {
										let url =
											`/pages/users/order_confirm/index?cartId=${cartId.value}&addressId=${newAddressId}&pinkId=${pinkId.value}&couponId=${couponId.value}&secKill=${secKill.value}&combination=${combination.value}&bargain=${bargain.value}`;
										cartId.value = "";
										pinkId.value = "";
										couponId.value = "";
										uni.navigateTo({
											url
										});
									} else {
										uni.navigateBack({
											delta: 1
										});
									}
								}, 1000);
								Toast({
									title: "添加成功",
									icon: "success"
								});
							})
							.catch((err) => {
								Toast({
									title: err
								});
							});
					},
					fail: function(res) {
						if (res.errMsg == "chooseAddress:cancel")
							return Toast({
								title: "取消选择"
							});
					},
				});
			},
			fail: function() {
				uni.showModal({
					title: "您已拒绝导入微信地址权限",
					content: "是否进入权限管理，调整授权？",
					success(res) {
						if (res.confirm) {
							uni.openSetting({});
						} else if (res.cancel) {
							Toast({
								title: "已取消！"
							});
						}
					},
				});
			},
		});
	}

	// 导入共享地址（微信）；
	function getAddress() {
		wechat
			.openAddress()
			.then((userInfo) => {
				editAddress({
						id: id.value,
						realName: userInfo.userName,
						phone: userInfo.telNumber,
						address: {
							province: userInfo.provinceName,
							city: userInfo.cityName,
							district: userInfo.countryName,
							cityId: 0,
						},
						detail: userInfo.detailInfo,
						isDefault: 1,
						postCode: userInfo.postalCode,
					})
					.then((res2) => {
						setTimeout(() => {
							const newAddressId = id.value ? id.value : res2.data.id;

							if (isFlashSale.value && preOrderNo.value > 0) {
								// 秒杀页面
								uni.navigateTo({
									url: `/pages/users/utils/flashSale/confirmOrder?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
								});
							} else if (isGroupBuy.value && preOrderNo.value > 0) {
								// 团购页面
								uni.navigateTo({
									url: `/pages/group_buying/paydetail?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
								});
							} else if (cartId.value) {
								let url =
									`/pages/users/order_confirm/index?cartId=${cartId.value}&addressId=${newAddressId}&pinkId=${pinkId.value}&couponId=${couponId.value}&secKill=${secKill.value}&combination=${combination.value}&bargain=${bargain.value}`;
								cartId.value = "";
								pinkId.value = "";
								couponId.value = "";
								uni.navigateTo({
									url
								});
							} else {
								uni.navigateTo({
									url: "/pages/users/user_address_list/index"
								});
							}
						}, 1000);
						Toast({
							title: "添加成功",
							icon: "success"
						});
					})
					.catch((err) => {
						Toast({
							title: err || "添加失败"
						});
					});
			})
			.catch((err) => {
				console.log(err);
			});
	}

	function formSubmit(e) {

		const value = e.detail.value;
		
		if (!value.realName) return Toast({
			title: "请填写收货人姓名"
		});
		if (!value.phone) return Toast({
			title: "请填写联系电话"
		});
		if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.phone))
			return Toast({
				title: "请输入正确的手机号码"
			});
		if (region.value == "省-市-区") return Toast({
			title: "请选择所在地区"
		});
		if (!value.detail) return Toast({
			title: "请填写详细地址"
		});
		value.id = id.value;
		let regionArray = region.value;
		value.address = {
			province: regionArray[0],
			city: regionArray[1],
			district: regionArray[2],
			cityId: cityId.value,
		};
		value.isDefault = userAddress.isDefault;

		uni.showLoading({
			title: "保存中",
			mask: true,
		});
		editAddress(value)
			.then((res2) => {
				Toast({
					title: id.value ? "修改成功" : "添加成功",
					icon: "success",
				});
				setTimeout(() => {
					const newAddressId = id.value ? id.value : res2.data.id;

					// 根据来源页面返回到相应的页面
					if (isFlashSale.value && preOrderNo.value > 0) {
						// 秒杀页面：返回秒杀确认订单页
						uni.redirectTo({
							url: `/pages/users/utils/flashSale/confirmOrder?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
						});
					} else if (isGroupBuy.value && preOrderNo.value > 0) {
						// 团购页面：返回团购支付详情页
						uni.redirectTo({
							url: `/pages/group_buying/paydetail?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
						});
					} else if (preOrderNo.value > 0) {
						// 普通订单确认页
						uni.redirectTo({
							url: `/pages/users/order_confirm/index?preOrderNo=${preOrderNo.value}&addressId=${newAddressId}`,
						});
					} else {
						// 没有来源页面，直接返回
						// #ifdef H5
						history.back();
						// #endif
						// #ifndef H5
						uni.navigateBack({
							delta: 1
						});
						// #endif
					}
				}, 1000);
			})
			.catch((err) => {
				Toast({
					title: err
				});
			});
	}

	function ChangeIsDefault() {
		userAddress.isDefault = !userAddress.isDefault;
	}
</script>
<style>
	page {
		background: #F9F7F0;
	}
</style>
<style scoped lang="scss">

	.addAddress {}

	.addAddress .list {
		padding: 16rpx;
	}

	.addAddress .list .item {
		padding: 28rpx 16rpx;
		border-radius: 16rpx;
		background: #FFFFFF;
		margin-bottom: 16rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.addAddress .list .item .name {

		font-size: 28rpx;
		color: #333333;
	}

	.addAddress .list .item .address {
		flex: 1;
	}

	.addAddress .list .item input {
		flex: 1;
		text-align: right;
		font-size: 28rpx;
	}

	.addAddress .list .item .placeholder {
		color: #ccc;
	}

	.addAddress .list .item picker .picker {

		flex: 1;
		text-align: right;
		font-size: 28rpx;
	}
	.ipt {
		margin-top: 16rpx;
		
		padding: 16rpx;
		height: 264rpx;
		background: #F9F7F0;
		border-radius: 16rpx;
		textarea {
			font-size: 28rpx;
		}
	}


	.acea-row {
		align-items: center;
	}

	.footer {
		width: 100%;
		bottom: 0;
		position: fixed;
		padding: 22rpx 32rpx 56rpx;
		
	}
	.addAddress .keepBnt {
		
		background: #F8C008;
		border-radius: 16rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: 32rpx;
		color: #333333;
		font-weight: bold;
		&::after {
			width: 0;
			border: none;
		}
	}

	.addAddress .wechatAddress {
		width: 690rpx;
		height: 86rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 86rpx;
		margin: 0 auto;
		font-size: 32rpx;
		color: #e93323;
		border: 1px solid #e93323;
	}

	.relative {
		position: relative;
	}

	.icon-dizhi {
		font-size: 44rpx;
		z-index: 100;
	}

	.abs_right {
		width: 32rpx;
		height: 32rpx;
		margin-left: 16rpx;
	}
</style>