<template>
	<view class="add_box">
		<view class="address_box">
			<view class="address_item" v-for="(item,index) in addressData" :key="index">
				<view class="top_box" @click="turnToOrder(item)">
					<view class="top_item" v-if="item.address == deAddress && item.consignee == deConsignee && item.phone == dePhone &&
					item.province == deProvince && item.city == deCity && item.area == deDistrict && item.isDefault == isDefaultAddress">
						<view class="top">
							<span class="name_txt">{{item.consignee}}</span>
							<span class="phone_txt">{{item.phone}}</span>
						</view>
						<view class="bottom" style="color: #D73232;">
							{{item.province}}{{item.city}}{{item.area}}{{item.address}}
						</view>
					</view>
					<view class="top_item" v-else>
						<view class="top">
							<span class="name_txt">{{item.consignee}}</span>
							<span class="phone_txt">{{item.phone}}</span>
						</view>
						<view class="bottom">
							{{item.province}}{{item.city}}{{item.area}}{{item.address}}
						</view>
					</view>
					<view class="edit_box" @click.stop="handleEdit(item)">
						<view class="img_box">
							<image class="img" src="../../../static/image/edit.png" mode=""></image>
						</view>
					</view>
				</view>
				<view class="bottom_item">
					<view class="no_checked_box" v-if="item.isDefault == 0" @click.stop="handleDefault(item)">
						<view class="no_checked"></view>
						<p class="no_default">设为默认</p>
					</view>
					<view class="check_box" v-if="item.isDefault == 1">
						<view class="checked">
							<p class="item"></p>
						</view>
						<p class="default_txt">默认地址</p>
					</view>

				</view>
			</view>
			<uni-load-more iconType="circle" :status="status" @clickLoadMore="loadMore"
				:content-text="contentText"></uni-load-more>
		</view>

		<view class="btn_box">
			<p class="btn" @click="handleAdd">添加新地址</p>
		</view>
		<view class="pop_box">
			<uni-popup ref="popup" style="width: 100%;" background-color="#fff">
				<view class="popup-content">
					<view class="title_box">
						<view class="tit_txt">
							{{title}}
						</view>
						<view class="image_box" @click="closePop">
							<image class="img" src="../../../static/image/cancel.png" mode=""></image>
						</view>
					</view>
					<view class="content_box">
						<view class="content_item">
							<view class="left_item">
								收货人：
							</view>
							<view class="right_item">
								<uni-easyinput v-model="buyUser" :inputBorder="false"
									placeholder="请输入收货人姓名"></uni-easyinput>
							</view>
						</view>
						<view class="content_item">
							<view class="left_item">
								联系电话：
							</view>
							<view class="right_item">
								<uni-easyinput v-model="buyPhone" :inputBorder="false"
									placeholder="请输入联系方式"></uni-easyinput>
							</view>
						</view>
						<view class="content_item">
							<view class="left_item">
								位置：
							</view>
							<view class="right_item">
								<!-- 山东省青岛市市北区 -->

								<!-- <view class="right_icon" @click="changeAddress">
								<image src="../../../static/image/icon-arrow-right.png"></image>
							</view> -->
								<picker class="picker_box" :range="locationArr" @change="cityChange"
									mode="multiSelector" @columnchange="columnchange" :value="multiIndex">
									<view class="city_box" v-if="province !== '' && city !== ''">
										{{province}} / {{city}} {{district ? '/' : ''}} {{district}}
									</view>
									<view class="city_box" v-if="province == '' && city == '' && district == ''">
										<span style="color: #999;">请选择地区</span>
									</view>
								</picker>
							</view>
						</view>
						<view class="content_item">
							<view class="left_item">
								详细地址：
							</view>
							<view class="right_item">
								<uni-easyinput type="textarea" :inputBorder="false" autoHeight v-model="address"
									placeholder="请输入详细地址"></uni-easyinput>
							</view>
							<!-- <view class="right_icon" @click="handlePosition">
								<image src="../../../static/image/position.png"></image>
							</view> -->
						</view>
					</view>
					<view class="button_box">
						<p class="btn" v-if="!isEdit" @click="closePop">取消</p>
						<p class="btn" v-if="isEdit" @click="handleDelete">删除</p>
						<p class="btn" @click="handleSave">保存</p>
					</view>
				</view>
			</uni-popup>
		</view>

	</view>
</template>

<script>
	import allCityData from "../../../util/all_city.json"
	export default {
		data() {
			return {
				isEdit: false,
				buyUser: '',
				buyPhone: '',
				address: '',
				imgPrefix: getApp().globalData.imgPrefix,
				locationArr: [
					[],
					[],
					[]
				],
				multiIndex: [0, 0, 0],
				province: '',
				city: '',
				district: '',
				addressData: [
					// {name:'张三',phone:'15612345678',address:'山东省青岛市市北区大港街道大港三路8号铁路住宅小区6号楼6单元666室',status:1},
					// {name:'张三',phone:'15612345678',address:'山东省青岛市市北区大港街道大港三路8号铁路住宅小区6号楼6单元666室',status:0},
				],
				allCityData,
				current: 0,
				size: 10,
				hasMore: true,
				status: '',
				contentText: {
					contentdown: "点击查看更多",
					contentrefresh: "正在加载...",
					contentnomore: "没有更多数据了",
				},
				title: '',
				addressId: '',
				userInfo: {},
				pageFrom: '',
				orderId:'',
				deAddress:'',
				deConsignee:'',
				dePhone:'',
				deProvince:'',
				deCity:'',
				deDistrict:'',
				isDefaultAddress:''
			}
		},
		onLoad(options) {
			console.log(options)
			this.pageFrom = options.from;
			this.orderId = options.orderId;
			this.deAddress = options.address;
			this.deConsignee = options.consignee;
			this.dePhone = options.phone;
			this.deProvince = options.province;
			this.deCity = options.city;
			this.deDistrict = options.area;
			this.isDefaultAddress = options.isDefaultAddress;
			this.getData()
			let userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				this.userInfo = JSON.parse(userInfo);
				if (this.userInfo.id != undefined) {
					this.loadMore();
				}
			}
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
			// console.log(userInfo)
		},
		methods: {
			// 保存地址
			handleSave() {
				if (this.userInfo) {
					if (!this.isEdit) {
						if (this.address == '' || this.province == '' || this.buyUser == '' || this.buyPhone == '') {
							uni.showToast({
								title: '请完整填写信息',
								icon: 'none'
							})
						} else {
							let params = {
								userId: this.userInfo.id,
								consignee: this.buyUser,
								phone: this.buyPhone,
								province: this.province,
								city: this.city,
								area: this.district ? this.district : '',
								address: this.address,
								isDefault: 0
							}
							uni.request({
								url: getApp().globalData.baseUrl + '/address/save',
								method: 'POST',
								header: {
									'Blade-Auth': 'bearer ' + uni.getStorageSync('token')
								},
								data: params,
								success: (res) => {
									console.log(res)
									if (res.data.code == 200) {
										uni.showToast({
											title: '新增成功',
											icon: 'none'
										})
										this.addressData = []
										this.$refs.popup.close();
										this.hasMore = true;
										this.current = 0;
										this.loadMore()
									}else if (res.data.code == 401) {
										this.doLogin()
									}else{
										uni.showToast({
											title: res.data.msg,
											icon: 'none'
										})
									}
								}
							})
						}
					} else {
						if (this.address == '' || this.province == '' || this.buyUser == '' || this.buyPhone == '') {
							uni.showToast({
								title: '请完整填写信息',
								icon: 'none'
							})
						} else {
							let params = {
								id: this.addressId,
								userId: this.userInfo.id,
								consignee: this.buyUser,
								phone: this.buyPhone,
								province: this.province,
								city: this.city,
								area: this.district ? this.district : '',
								address: this.address,
							}
							uni.request({
								url: getApp().globalData.baseUrl + '/address/update',
								method: "POST",
								header: {
									'Blade-Auth': 'bearer ' + uni.getStorageSync('token')
								},
								data: JSON.stringify(params),
								success: res => {
									console.log(res)
									if (res.data.code == 200) {
										uni.showToast({
											title: '地址修改成功',
											icon: 'none'
										});
										this.addressData = []
										this.$refs.popup.close();
										this.hasMore = true;
										this.current = 0;
										this.loadMore()
									}else if (res.data.code == 401) {
										this.doLogin()
									} else {
										uni.showToast({
											title: res.data.msg,
											icon: 'none'
										})
									}
								}
							})
						}
					}
				}
				console.log(this.address)
			},
			// 编辑地址
			handleEdit(item) {
				console.log(item)
				this.title = '编辑地址'
				this.addressId = item.id
				this.isEdit = true;
				this.buyUser = item.consignee;
				this.buyPhone = item.phone;
				this.address = item.address;
				this.province = item.province;
				this.city = item.city;
				this.district = item.area;
				this.getCurrentArea(this.province)
				this.$refs.popup.open('bottom')
			},
			// 编辑页面时获取省市区数据
			getCurrentArea(value) {
				this.locationArr[1] = []
				this.locationArr[2] = []
				this.allCityData.map((item, index) => {
					if (item.province == this.province) {
						this.multiIndex[0] = index;
						item.citys.map((item1, index1) => {
							if (item1.city == this.province) {
								console.log(item1)
								item1.areas.map((item2, index2) => {
									if (item2.area == this.city) {
										this.multiIndex[1] = index2;
									}
									this.locationArr[1].push(item2.area);
								})
							} else {
								if (item1.city == this.city) {
									this.multiIndex[1] = index1;
									item1.areas.map((item3, index3) => {
										this.locationArr[2].push(item3.area)
										if (item3.area == this.district) {
											console.log('item3 ==>', item3)
											console.log('index3 ==>', index3)
											this.multiIndex[2] = index3;
										}
									})
								}
								this.locationArr[1].push(item1.city);

							}
						})

					}
				})
				console.log('multiIndex', this.multiIndex)
				console.log('locationArr', this.locationArr)
			},
			// 删除地址
			handleDelete() {
				uni.showModal({
					title: '提示',
					content: '确认删除该地址？',
					success: (res) => {
						if (res.confirm) {
							uni.request({
								url: getApp().globalData.baseUrl + '/address/delete?ids=' + this
									.addressId,
								method: "POST",
								header: {
									'Blade-Auth': 'bearer ' + uni.getStorageSync('token')
								},
								success: (res) => {
									console.log(res)
									if (res.data.code == 200) {
										uni.showToast({
											title: '删除成功',
											icon: 'none'
										})
										this.addressData = []
										this.$refs.popup.close();
										this.hasMore = true;
										this.current = 0;
										this.loadMore()
									}else if (res.data.code == 401) {
										this.doLogin()
									} else {
										uni.showToast({
											title: res.data.msg,
											icon: 'none'
										})
									}
								},
							})
						} else if (res.cancel) {

						}
					},
				})
			},
			// 添加默认
			handleDefault(item) {
				uni.showModal({
					title: '提示',
					content: '确认将该地址设置为默认地址？',
					success: (res) => {
						if (res.confirm) {
							let params = {
								id: item.id,
								userId: this.userInfo.id,
								isDefault: 1
							}
							uni.request({
								url: getApp().globalData.baseUrl + '/address/update',
								method: "POST",
								header: {
									'Blade-Auth': 'bearer ' + uni.getStorageSync('token')
								},
								data: JSON.stringify(params),
								success: res => {
									console.log(res)
									if (res.data.code == 200) {
										uni.showToast({
											title: '默认地址设置成功',
											icon: 'none'
										});
										this.addressData = []
										this.$refs.popup.close();
										this.hasMore = true;
										this.current = 0;
										this.loadMore()
									}else if (res.data.code == 401) {
										this.doLogin()
									} else {
										uni.showToast({
											title: res.data.msg,
											icon: 'none'
										})
									}
								}
							})
						} else if (res.cancel) {

						}
					}
				})
			},
			// 跳转到提交订单页面
			turnToOrder(item) {
				if (this.pageFrom == 1) {
					var pages = getCurrentPages(); // 获取页面栈
					var currPage = pages[pages.length - 1]; // 当前页面
					var prevPage = pages[pages.length - 2]; // 上一个页面
					console.log(pages)
					console.log(prevPage)
					if (prevPage.route == 'pages/pages_zhentou/order/confirmOrder') {
						uni.setStorageSync('address', JSON.stringify(item))
						uni.navigateBack();
					}
				}else if(this.pageFrom == 'order'){
					var pages = getCurrentPages(); // 获取页面栈
					var currPage = pages[pages.length - 1]; // 当前页面
					var prevPage = pages[pages.length - 2]; 
					if (prevPage.route == 'pages/pages_zhentou/order/checkOrder') {
						console.log('111')
						let params ={
							id:this.orderId,
							consignee:item.consignee,
							consigneePhone:item.phone,
							address:item.address,
							province:item.province,
							city:item.city,
							district:item.area,
							isDefaultAddress:item.isDefault
						}
						console.log(params)
						uni.request({
							url:getApp().globalData.baseUrl + "/blade-desk/order/updateAddress?id=" + this.orderId + '&consignee=' + item.consignee + 
							'&consigneePhone=' + item.phone + '&address=' + item.address + '&province=' + item.province + '&city=' + item.city + 
							'&district=' + item.area + '&isDefaultAddress=' + item.isDefault,
							 method:"POST",
							 header:{
								 'Blade-Auth': 'bearer ' + uni.getStorageSync('token')
							 },
							 // params:params,
							 success:(res) =>{
								 console.log(res)
								 if(res.data.code == 200){
									uni.setStorageSync('orderId', this.orderId);
									uni.navigateBack();
								 }else if (res.data.code == 401) {
									this.doLogin()
								 }else{
									 uni.showToast({
									 	title: res.data.msg,
									 	icon: 'none'
									 })
								 }
							 }
						})
					}
				}
			},
			// 取消新增
			closePop() {
				this.$refs.popup.close();
			},
			// 获取地区数据
			getData() {
				this.locationArr = [
					[],
					[],
					[]
				]
				this.allCityData.map(item => {
					this.locationArr[0].push(item.province);
				})
				this.allCityData[0].citys[0].areas.map(item => {
					this.locationArr[1].push(item.area)
				})

				console.log(this.locationArr)
			},
			// 省市区确定地址
			cityChange(e) {
				this.multiIndex = e.detail.value;
				this.province = this.locationArr[0][this.multiIndex[0]]
				this.city = this.locationArr[1][this.multiIndex[1]]
				this.district = this.locationArr[2][this.multiIndex[2]];
				this.address = ''
			},
			// 列切换
			columnchange(e) {
				let value = e.detail.value;
				console.log(e.detail)
				if (e.detail.column == 0) {
					this.locationArr[1] = [];
					this.locationArr[2] = []
					let tmp = this.allCityData.find(item => item.province == this.locationArr[0][value])
					console.log(tmp)
					if (tmp.citys.length == 1) {
						tmp.citys[0].areas.map(item => {
							this.locationArr[1].push(item.area)
						})
					} else {
						tmp.citys.map(item => {
							this.locationArr[1].push(item.city)
						})
						tmp.citys[0].areas.map(item => {
							this.locationArr[2].push(item.area);
						})
					}
					// 第一列滑动  第二列 和第三列 都变为第一个
					this.multiIndex = [value, 0, 0]

				}
				if (e.detail.column == 1) {
					this.locationArr[2] = [];
					this.multiIndex[1] = value;
					if (this.allCityData[this.multiIndex[0]].citys.length !== 1) {
						this.allCityData[this.multiIndex[0]].citys[value].areas.map(item => {
							this.locationArr[2].push(item.area)
						})
					}
					this.multiIndex.splice(2, 1, 0)
					console.log(this.multiIndex)
				}
				// 第三列滑动
				if (e.detail.column === 2) {
					this.multiIndex[2] = e.detail.value
				}
			},
			// 添加地址
			handleAdd() {
				this.isEdit = false;
				this.title = '新增地址'
				this.buyUser = '';
				this.buyPhone = '';
				this.address = '';
				this.province = '';
				this.city = '';
				this.district = '';
				this.getData();
				this.multiIndex = [0, 0, 0]
				this.$refs.popup.open('bottom')
			},
			// 定位
			handlePosition() {
				uni.getLocation({
					type: " wgs84",
					isHighAccuracy: true,
					success: (res) => {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						uni.request({
							url: `https://restapi.amap.com/v3/geocode/regeo?location=${res.longitude},${res.latitude}&key=b8e2796701c731e4a97f4d0bc4e51385&radius=1000&extensions=all`,
							method: "get",
							success: res => {
								console.log(res.data)
								this.province = res.data.regeocode.addressComponent.province;
								this.city = res.data.regeocode.addressComponent.city;
								this.district = res.data.regeocode.addressComponent.district;
								console.log(this.province)
								this.allCityData.map(item1 => {
									if (item1.province == this.province) {
										item1.citys.map(item2 => {
											this.locationArr[1].push(item2.city)
											if (item2.city == this.city) {
												item2.areas.map(item3 => {
													this.locationArr[2]
														.push(item3.area)
												})
											}
										})
									}
								})
								console.log(this.locationArr)
								this.locationArr[0].map((item, index) => {
									if (item == this.province) {
										this.multiIndex[0] = index
									}
								});
								this.locationArr[1].map((item, index) => {
									if (item == this.city) {
										this.multiIndex[1] = index
									}
								});
								this.locationArr[2].map((item, index) => {
									if (item == this.district) {
										this.multiIndex[2] = index
									}
								})
							}
						})
					}
				})
			},
			//加载更多
			loadMore() {
				console.log('loadmore')
				if (this.hasMore) {
					this.current = this.current + 1;
					this.staus = 'loading';
					uni.request({
						url: getApp().globalData.baseUrl + '/address/list?id=' + this.userInfo.id + '&current=' +
							this
							.current + '&size=' + this.size,
						method: 'GET',
						header: {
							'Blade-Auth': 'bearer ' + uni.getStorageSync('token')
						},
						success: (res) => {
							if (res.data.code == 200) {
								this.addressData = this.addressData.concat(res.data.data.records);
								if (res.data.data.records.length == 0 || res.data.data.total < this.size) {
									this.hasMore = false;
									this.status = 'nomore';
								} else {
									this.status = 'more';
								}
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
							}
						},
					})
				}
			},

			//登录
			doLogin(type) {
				uni.showLoading({
					title: '登录中',
					mask: true
				});
				uni.request({
					url: getApp().globalData.baseUrl + '/blade-auth/getToken',
					method: 'POST',
					data: {
						openId: getApp().globalData.openId,
						phone: this.phone
					},
					header: {
						'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0'
					},
					success: (res) => {
						if (res.data.code == 200) {
							uni.setStorageSync('token', res.data.data.access_token);
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					complete: () => {
						uni.hideLoading();
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.add_box {
		width: 100%;
		height: 100%;

		.address_box {
			height: 82%;
			width: 690rpx;
			background: #FFFFFF;
			border-radius: 30rpx 30rpx 30rpx 30rpx;
			margin: 0 auto;
			margin-top: 30rpx;

			.address_item {
				width: 100%;
				height: 255rpx;
				border-bottom: 1rpx solid #F2F2F2;
				display: flex;
				flex-direction: column;

				.bottom_item {
					width: 100%;
					height: 25%;
					display: flex;
					align-items: center;

					.no_checked_box {
						width: 100%;
						display: flex;

						.no_checked {
							width: 28rpx;
							height: 28rpx;
							background: #FFFFFF;
							border: 1rpx solid #666666;
							border-radius: 50%;
							margin: 0 30rpx;
						}
					}


					.check_box {
						width: 100%;
						display: flex;

						.checked {
							width: 28rpx;
							height: 28rpx;
							background: #FFFFFF;
							border: 1rpx solid #D73232;
							border-radius: 50%;
							margin: 0 30rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							.item {
								width: 16rpx;
								height: 16rpx;
								background: #D73232;
								border-radius: 50%;
							}
						}
					}



					.default_txt {
						font-size: 22rpx;
						color: #D73232;
					}

					.no_default {
						color: #B8B8B8;
						font-size: 22rpx;
					}
				}

				.top_box {
					width: 100%;
					height: 75%;
					display: flex;

					.top_item {
						width: 85%;
						margin-left: 30rpx;

						.top {
							margin-top: 30rpx;
							display: flex;
							height: 40rpx;
							align-items: flex-end;

							.name_txt {
								font-size: 28rpx;
								color: #333;
								font-weight: bold;
							}

							.phone_txt {
								font-size: 22rpx;
								color: #999;
								margin-left: 20rpx;
							}
						}

						.bottom {
							width: 484rpx;
							height: 74rpx;
							font-size: 26rpx;
							color: #333;
							margin-top: 20rpx;
							line-height: 40rpx;
						}
					}
				}

				.edit_box {
					height: 100%;
					display: flex;
					align-items: center;

					.img_box {
						width: 44rpx;
						height: 44rpx;
					}

					.img {
						width: 100%;
						height: 100%;
					}
				}

			}
		}

		.btn_box {
			width: 100%;
			height: 150rpx;
			background: #FFFFFF;
			position: fixed;
			bottom: 0;
			display: flex;
			justify-content: center;

			.btn {
				width: 690rpx;
				height: 78rpx;
				background: #D73232;
				border-radius: 20rpx 20rpx 20rpx 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				font-size: 28rpx;
				margin-top: 30rpx;
			}
		}

		.pop_box {
			width: 100%;

			/deep/ .uni-popup {
				width: 100%;
			}

			.popup-content {
				width: 100%;
				background: #fff;
				padding-top: 40rpx;
				border-radius: 30rpx 30rpx 0rpx 0rpx;


				.title_box {
					width: 100%;
					height: 50rpx;
					display: flex;
					align-items: center;
					// justify-content: space-between;

					.tit_txt {
						width: 90%;
						text-align: center;
						font-weight: bold;
						font-size: 36rpx;
						color: #000;
					}

					.image_box {
						width: 44rpx;
						height: 44rpx;

						.img {
							width: 100%;
							height: 100%;
						}
					}
				}

				.content_box {
					width: 100%;
					margin-top: 20rpx;

					.content_item {
						width: 100%;
						padding: 30rpx 0;
						display: flex;
						align-items: center;
						border: 1rpx solid #F2F2F2;

						.left_item {
							width: 140rpx;
							height: 100%;
							display: flex;
							align-items: center;
							margin-left: 30rpx;
							font-size: 26rpx;
							color: #333;

						}

						.right_item {
							width: 406rpx;
							height: 100%;
							display: flex;
							align-items: center;
							margin-left: 30rpx;
							font-size: 26rpx;
							color: #333;

							.picker_box {
								padding-left: 20rpx;
							}

							/deep/.uni-easyinput__content {
								// padding-left: 30rpx;

								.uni-easyinput__content-textarea {
									min-height: 40rpx !important;
									padding-left: 20rpx;
								}
							}
						}

						.right_icon {
							width: 44rpx;
							height: 44rpx;
							margin-left: 66rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}
					}
				}

				.button_box {
					width: 100%;
					height: 120rpx;
					display: flex;
					margin-top: 20px;
					align-items: center;
					justify-content: center;

					.btn {
						width: 320rpx;
						height: 78rpx;
						background: #FFFFFF;
						border-radius: 20rpx 20rpx 20rpx 20rpx;
						border: 1rpx solid #D73232;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 26rpx;
						color: #D73232;

						&:last-child {
							background: #D73232;
							margin-left: 50rpx;
							color: #FFFFFF;
						}
					}
				}
			}

		}
	}
</style>