<template>
	<view class="container">
		<navbar :config="config" backColor="#666666"></navbar>

		<form @submit="formSubmit">
			<view class="u-bg-fff">
				<view class="u-plr30">
					<view class="u-flex-center border u-border-one-one ht104">
						<view class="wt140 u-font28 u-1A1A1A">收货人：</view>
						<input class="u-ml10" maxlength="8" name="name" :value="dataform.name"
							placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
							placeholder="请填写收货人姓名" />
					</view>
					<view class="u-flex-center border u-border-one-one ht104">
						<view class="wt140 u-font28 u-1A1A1A">手机号码：</view>
						<input class="u-ml10" type="number" name="phone" maxlength="11" :value="dataform.phone"
							placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
							placeholder="请输入手机号码" />
					</view>
					<!-- <picker class="pickerList" mode="multiSelector" :range="newProvinceDataList" range-key="label"
						:value="multiIndex" @change="pickerChange" @columnchange="pickerColumnchange">
						<view class="u-flex-center border u-border-one-one ht104">
							<view class="wt140 u-font28 u-1A1A1A">所在地区：</view>
							<input class="u-ml10" placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
								placeholder="请选择地区" disabled
								:value="dataform.province_name + '' + dataform.city_name + '' + dataform.area_name" />
							<view class="iconfont u-ml25">&#xe6c7;</view>
						</view>
					</picker> -->
					<view class="u-flex-center border u-border-one-one ht104" @click="areaShow=true">
						<view class="wt140 u-font28 u-1A1A1A">所在地区：</view>
						<input class="u-ml10" placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
							placeholder="请选择地区" disabled
							:value="dataform.province_name + '' + dataform.city_name + '' + dataform.area_name" />
						<view class="iconfont u-ml25">&#xe6c7;</view>
					</view>
					<!-- <picker class="pickerList" :disabled="!dataform.area_name" @click="streetClick" :range="streetList" range-key="label" :value="streetListIndex"
						@change="picker2Change">
						<view class="u-flex-center border u-border-one-one ht104">
							<view class="wt140 u-font28 u-1A1A1A">所在街道：</view>
							<input class="u-ml10" placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
								placeholder="请选择街道" disabled :value="dataform.street_name" />
							<view class="iconfont u-ml25">&#xe6c7;</view>
						</view>
					</picker> -->
					<!-- <picker class="pickerList" :disabled="!dataform.street_name" @click="communityClick" :range="communityList" range-key="label" :value="communityListIndex"
						@change="picker3Change">
						<view class="u-flex-center border u-border-one-one ht104">
							<view class="wt140 u-font28 u-1A1A1A">所在社区：</view>
							<input class="u-ml10" placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
								placeholder="请选择社区" disabled :value="dataform.community_name" />
							<view class="iconfont u-ml25">&#xe6c7;</view>
						</view>
					</picker> -->
					<view class="u-flex-center ht132" style="align-items: center;">
						<view class="wt140 u-font28 u-1A1A1A" style="flex-shrink:0">详细地址：</view>
						<textarea class="u-ml10" style="height: 90rpx;width: 70%;margin-top: 36rpx;" maxlength="50"
							name="address" placeholder-style="color: #d9d9d9;font-weight: 400;font-size: 26rpx; "
							v-model="dataform.address" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元室等"></textarea>
						<view class="getBtn" @click="getLocation()">获取地址</view>
					</view>
				</view>
			</view>
			<view class="default border u-mt20 u-bg-fff u-flex-center-sb">
				<view>设为默认收货地址</view>
				<view>
					<switch @change="isDefault" color="#FA6138" :checked="dataform.is_default"
						style="transform:scale(0.7)"></switch>
				</view>
			</view>

			<view class="u-plr30 mt104">
				<!-- <button class="u-btn-two u-bg-00321E u-FFF" @click="getWxAddress">一键获取微信地址</button> -->
				<button class="u-btn-two" style="color: #ffffff; background-color: #FA6138;"
					form-type="submit">保存</button>
			</view>
		</form>
		<!-- 地区 -->
		<u-select v-model="areaShow" mode="mutil-column-auto" :list="newProvinceDataList" @confirm="areaConfirm"></u-select>
	</view>
</template>

<script>
	import {
		myUserInfo
	} from "@/api/government.js"
	export default {
		data() {
			return {
				config: {
					back: true, //false是tolbar页面 是则不写
					title: '添加收货地址',
					color: '#1A1A1A',
					//背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
					backgroundColor: [1, '#fff'],
					statusBarFontColor: '#1A1A1A'
				},
				oldpProvinceDataList: [],
				newProvinceDataList: [
					// [],
					// [],
					// []
				], // 省市区
				multiIndex: [0, 0, 0],
				streetList: [], // 街道
				streetListIndex: [0],
				communityList: [], // 社区
				communityListIndex: [0],
				dataform: {
					name: '', //收货人姓名
					phone: '', //联系电话
					province_name: '', //省的名称
					province_code: '', //省编号
					city_code: '', //市编号
					city_name: '', //市名称
					area_name: '', //区名称
					area_code: '', //区编号
					street_code: '', //街道编号
					street_name: '', //街道名称
					community_code: '', //社区编号
					community_name: '', //社区名称
					address: '', //详细地址
					longitude: '', //微信经度
					latitude: '', //微信纬度
					is_default: false ,//是否是默认
				},
				areaShow:false,
				user:{}
			};
		},
		onLoad(options) {
			
			this.getLocation()
			//获取地址详情（id查询）
			if (options.id) {
				this.$http.get('/useraddress/info/' + options.id)
					.then(async res => {
						if (res.code == 200) {
							this.dataform = res.data;
						}
						this.getAreaList2()
					})
			} else {
				this.getUserData();
				this.getAreaList2();
			}
		},
		methods: {
			getUserData() {
				myUserInfo().then(res => {
					this.user = res.data;
					this.dataform.name=this.user.realName;
					this.dataform.phone=this.user.mobile;
				})
			},
			getLocation(){
				uni.getLocation({
					type: 'gcj02',
					geocode:true,
					success:(res)=>{
						console.log(res);
						this.dataform.province_name=res.address.province;
						this.dataform.city_name=res.address.city;
						this.dataform.area_name=res.address.district;
						// this.$set(this.dataform,'address',res.address.street+res.address.streetNum+res.address.poiName)
						this.$nextTick(()=>{
							this.$set(this.dataform,'address',res.address.street+res.address.streetNum+res.address.poiName)
								this.dataform.address=res.address.street+res.address.streetNum+res.address.poiName
						})
					},
					fail:(e)=>{
						console.log(e)
					}
				});
			},
			streetClick(){
				if(!this.dataform.area_name){
					uni.showToast({
						icon:"none",
						title: '请先选择地区',
						duration: 2000
					});
					return false
				}
			},
			communityClick(){
				if(!this.dataform.street_name){
					uni.showToast({
						icon:"none",
						title: '请先选择街道',
						duration: 2000
					});
					return false
				}
			},
			// 获取省市区
			getAreaList2() {
				let that = this;
				let req = this.$http.get('/cnarea/tree-lbs', {});
				req.then(res => {
					let provincesList = res.tree.children;
					let multiIndex = [0, 0, 0];
					// for (let i = 0; i < provincesList.length; i++) {
					// 	this.newProvinceDataList[0].push(provincesList[i]);
					// 	if (provincesList[i].value == this.dataform.province_code) {
					// 		multiIndex[0] = i;
					// 	}
					// 	for (let c = 0; c < provincesList[i].children.length; c++) {
					// 		this.newProvinceDataList[1].push(provincesList[i].children[c]);
					// 		if (provincesList[i].children[c].value == this.dataform.city_code) {
					// 			multiIndex[1] = c;
					// 		}
					// 		if (provincesList[i].children[c].children) {
					// 			for (let a = 0; a < provincesList[i].children[c].children.length; a++) {
					// 				this.newProvinceDataList[2].push(provincesList[i].children[c].children[a]);
					// 				if (provincesList[i].children[c].children[a].value == this.dataform
					// 					.area_code) {
					// 					multiIndex[2] = a;
					// 				}
					// 			}
					// 		} else {
					// 			this.newProvinceDataList[2] = [];
					// 		}
					// 	}
					// }
					this.newProvinceDataList=provincesList
					console.log(this.newProvinceDataList)
					that.oldpProvinceDataList = provincesList;
					that.multiIndex = multiIndex;
					// that.getAreaList(that.newProvinceDataList[2][that.multiIndex[2]].value, 'street');
				})
				return req;
			},
			// 获取地区
			areaConfirm(e){
				if(e.length>0){
					this.dataform.province_name=e[0].label;
					this.dataform.province_code=e[0].value;
					this.dataform.city_name=e[1].label;
					this.dataform.city_code=e[1].value;
					this.dataform.area_name=e[2].label;
					this.dataform.area_code=e[2].value;
					this.getAreaList(this.dataform.area_code, 'street');
					this.dataform.street_name="";
					this.dataform.street_code="";
					this.dataform.community_name="";
					this.dataform.community_code=""
				}
			},
			formSubmit: function(e) {
				let that = this;
				let target = e.detail.value;
				if (!target.name) {
					this.$mUtil.toast('请输入收货人姓名');
					return false;
				}
				if (!target.phone) {
					this.$mUtil.toast('请输入联系电话');
					return false;
				}
				if (!target.phone.match(this.$mConfig.telRegex)) {
					this.$mUtil.toast('请输入正确手机号');
					return false;
				}
				if (!that.dataform.province_name) {
					this.$mUtil.toast('请选择省市区');
					return false;
				}
				// if (!that.dataform.street_name) {
				// 	this.$mUtil.toast('请选择街道');
				// 	return false;
				// }
				// if (!that.dataform.community_name) {
				// 	this.$mUtil.toast('请选择社区');
				// 	return false;
				// }
				if (!target.address) {
					this.$mUtil.toast('请输入详细地址');
					return false;
				}
				this.dataform.name = target.name;
				this.dataform.phone = target.phone;
				this.dataform.address = target.address;
				if (this.dataform.id) {
					this.$http.put('/useraddress/update', this.dataform).then(async res => {
						if (res && res.code == 200) {
							uni.showToast({
								title: '修改成功',
								icon: 'none',
								duration: 3000,
								success() {
									// var pages = getCurrentPages();
									// var prevPage = pages[pages.length - 2];
									// prevPage.$vm.listAddress(1)
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										});
									},1000)
								}
							});
						}
					});
				} else {
					this.$http.post('/useraddress/save', this.dataform).then(res => {
						if (res && res.code == 200) {
							uni.showToast({
								title: '添加成功',
								icon: 'none',
								duration: 3000,
								success() {
									var pages = getCurrentPages();
									var prevPage = pages[pages.length - 2];
									prevPage.$vm.listAddress(1);
									uni.navigateBack({
										delta: 1
									});
								}
							});
						}
					});
				}
			},
			//是否设置默认地址
			isDefault: function(e) {
				this.dataform.is_default = e.target.value;
			},
			//获取微信地址
			getWxAddress() {
				let that = this;
				uni.getSetting({
					success(res) {
						if (res.authSetting['scope.address']) {
							uni.chooseAddress({
								success(res) {
									that.dataform = {
										name: res.userName, //收货人姓名
										phone: res.telNumber, //联系电话
										province_name: res.provinceName, //省的名称
										province_code: '', //省编号
										city_code: '', //市编号
										city_name: res.cityName, //市名称
										area_name: res.countyName, //区名称
										area_code: '', //区编号
										address: res.detailInfo, //详细地址
										longitude: '', //微信经度
										latitude: '', //微信纬度
										is_default: false //是否是默认
									}
								}
							});
						} else {
							if (res.authSetting['scope.address'] == false) {
								uni.openSetting({
									success(res) {}
								});
							} else {
								uni.chooseAddress({
									success(res) {}
								});
							}
						}
					}
				});
			},
			// 省市区确认事件
			pickerChange(e) {
				this.multiIndex = e.detail.value;
				if (this.newProvinceDataList[2][this.multiIndex[2]] != undefined) {
					this.dataform.province_name = this.newProvinceDataList[0][this.multiIndex[0]].label;
					this.dataform.province_code = this.newProvinceDataList[0][this.multiIndex[0]].value;
					this.dataform.city_name = this.newProvinceDataList[1][this.multiIndex[1]].label;
					this.dataform.city_code = this.newProvinceDataList[1][this.multiIndex[1]].value;
					this.dataform.area_name = this.newProvinceDataList[2][this.multiIndex[2]].label;
					this.dataform.area_code = this.newProvinceDataList[2][this.multiIndex[2]].value;
					this.dataform.latitude = this.newProvinceDataList[2][this.multiIndex[2]].latitude;
					this.dataform.longitude = this.newProvinceDataList[2][this.multiIndex[2]].longitude;
				} else {
					this.dataform.province_name = this.newProvinceDataList[0][this.multiIndex[0]].label;
					this.dataform.province_code = this.newProvinceDataList[0][this.multiIndex[0]].value;
					this.dataform.city_name = this.newProvinceDataList[1][this.multiIndex[1]].label;
					this.dataform.city_code = this.newProvinceDataList[1][this.multiIndex[1]].value;
					this.dataform.latitude = this.newProvinceDataList[1][this.multiIndex[1]].latitude;
					this.dataform.longitude = this.newProvinceDataList[1][this.multiIndex[1]].longitude;
					this.dataform.area_name = '';
					this.dataform.area_code = '';
				}
			},
			pickerColumnchange(e) {
				// 第几列滑动
				// console.log(e.detail.column);
				// 第几列滑动的下标
				// console.log(e.detail.value)
				// 第一列滑动
				if (e.detail.column === 0) {
					this.multiIndex[0] = e.detail.value;
					this.newProvinceDataList[1] = this.oldpProvinceDataList[this.multiIndex[0]].children.map((item,
						index) => {
							return item;
						});
					//当三级存在
					if (this.oldpProvinceDataList[this.multiIndex[0]].children[0].children) {
						if (this.oldpProvinceDataList[this.multiIndex[0]].children[this.multiIndex[1]]) {
							this.newProvinceDataList[2] = this.oldpProvinceDataList[this.multiIndex[0]].children[this
								.multiIndex[1]].children.map((item, index) => {
								return item;
							});
						}
					} else {
						this.newProvinceDataList[2] = [];
					}
					// 第一列滑动  第二列 和第三列 都变为第一个
					this.multiIndex.splice(1, 1, 0);
					this.multiIndex.splice(2, 1, 0);
				}
				// 第二列滑动
				if (e.detail.column === 1) {
					this.multiIndex[1] = e.detail.value;
					if (this.oldpProvinceDataList[this.multiIndex[0]].children[this.multiIndex[1]].children) {
						this.newProvinceDataList[2] = this.oldpProvinceDataList[this.multiIndex[0]].children[this
							.multiIndex[1]].children.map((item, index) => {
							return item;
						});
					} else {
						this.newProvinceDataList[2] = [];
					}
					// 第二列 滑动 第三列 变成第一个
					this.multiIndex.splice(2, 1, 0);
				}
				// 第三列滑动
				if (e.detail.column === 2) {
					// console.log('第三列滑动')
					// console.log(this.multiIndex)

					if (this.multiIndex[2] != e.detail.value) {
						this.dataform.street_code = '';
						this.dataform.street_name = '';
						this.dataform.community_code = '';
						this.dataform.community_name = '';
					}

					this.multiIndex[2] = e.detail.value;
					this.getAreaList(this.newProvinceDataList[2][this.multiIndex[2]].value, 'street');
				}
			},
			/**
			 * @param {Object} parentCode
			 * @param {Object} type    value: 'street' or 'community'
			 *@description 根据上一级查询下一级。例如根据“区”查“街道”，根据“街道”查“社区”。10000是查询所有省
			 */
			getAreaList(parentCode, type) {
				// this.$http.get(`/cnarea/lbs-children/${parentCode}`, {}).then(res => {
				// 	if (res && res.code == 200) {
				// 		if (type == 'street') {
				// 			this.streetList = res.list;
				// 			this.getAreaList(this.streetList[this.streetListIndex].value, 'community');
				// 		} else {
				// 			this.communityList = res.list;
				// 		}
				// 	}
				// });
			},
			picker2Change(e) {
				if (this.streetListIndex != e.detail.value) {
					this.dataform.community_code = '';
					this.dataform.community_name = '';
				}
				this.streetListIndex = [e.detail.value];
				this.getAreaList(this.streetList[this.streetListIndex].value, 'community');
				this.dataform.street_code = this.streetList[this.streetListIndex].value;
				this.dataform.street_name = this.streetList[this.streetListIndex].label;
				this.dataform.community_name="";
				this.dataform.community_code=""
			},
			picker3Change(e) {
				this.communityListIndex = [e.detail.value];
				this.dataform.community_code = this.communityList[this.communityListIndex].value;
				this.dataform.community_name = this.communityList[this.communityListIndex].label;
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
	}

	.border {
		border-bottom: 3rpx solid #e7e7e7;
	}

	.wt140 {
		width: 140rpx;
	}

	.ht104 {
		height: 104rpx;
		line-height: 104rpx;
	}

	.ht132 {
		height: 132rpx;
		// line-height: 132rpx;
	}

	.mt104 {
		margin-top: 104rpx;
	}

	input {
		width: 70%;
	}

	.default {
		padding: 38rpx 30rpx;
	}
	.getBtn{
		flex-shrink: 0;
		background: rgb(250, 97, 56);
		color: #fff;
		border-radius: 10rpx;
		padding:10rpx 20rpx;
		font-size: 24rpx;
	}
</style>
