<template>
	<view class="app-container">
		<view class="row">
			<view class="title">收货人</view>
			<view class="right input"><input type="text" placeholder="请输入收货人" v-model="formData.name"></view>
		</view>
		<view class="row">
			<view class="title">手机号码</view>
			<view class="right input"><input type="number" placeholder="请输入手机号码" v-model="formData.phone"></view>
		</view>
		<view class="row">
			<view class="title">所在地区</view>
			<view class="right">
				<picker @change="onRegionChange" v-model="regionValue" mode="region">
					<view class="picker">
						<view v-if="regionValue.length">{{regionValue[0] + '/' +regionValue[1] + '/' +regionValue[2]}}</view>
						<view v-else style="color: #666666;">请选择省/市/区</view>
						<image src="@/static/icon/right.png"></image>
					</view>
				</picker>
			</view>
		</view>
		<view class="row">
			<view class="title">所在街道</view>
			<view class="right">
				<picker @change="onStreetChange" :value="streetValue" :range="streetList" range-key="name" :disabled="!regionValue[2]">
					<view class="picker">
						<view v-if="streetValue !== ''">{{streetList[streetValue].name}}</view>
						<view v-else style="color: #666666;">请选择街道</view>
						<image src="@/static/icon/right.png"></image>
					</view>
				</picker>
			</view>
		</view>
		
		<view class="row">
			<view class="title">收货地址</view>
			<view class="right textarea">
				<textarea placeholder="请输入收货地址" auto-height v-model="formData.address"></textarea>
				<view class="r" @tap="getLocation"><image src="@/static/icon/address2.png"></image>定位</view>
			</view>
		</view>
		<view class="row">
			<view class="title">门牌号</view>
			<view class="right input"><input type="text" placeholder="请输入门牌号" maxlength="15" v-model="formData.houseNo"></view>
		</view>
		<view class="row">
			<view class="title">设为默认地址</view>
			<view class="right default"><switch @change="switchChange" color="#FF3F42" v-model="formData.defaultAddr" :checked="formData.defaultAddr" style="transform:scale(0.7)" /></view>
		</view>
		<view class="button red" @tap="submitForm">保存</view>
		<view class="button white" v-if="editId" @tap="isDialog = true">删除</view>
		
		<modal-dialog showText="确定要删除该地址吗？" :isShowDialog="isDialog" @cancel="isDialog = false" @confirm="confirmDelete"></modal-dialog>
	</view>
</template>

<script>
	import {mapState} from 'vuex';
	import {getArea} from '@/utils/utils.js';
	import modalDialog from '@/components/modalDialog.vue';
	
	export default {
		components:{
			modalDialog
		},
		data() {
			return {
				editId: null, // 编辑的id
				isDialog: false, // 是否显示删除弹窗
				regionValue: [], // 省市区值
				streetList: [],
				streetValue: '',
				formData: { // 表单数据
					name: '',
					phone: '',
					province: '',
					city: '',
					area: '',
					street: '',
					address: '',
					houseNo: '',
					defaultAddr: false,
				},
				canClickSave: true, // 能否点击提交
			}
		},
		computed:{
			...mapState(['userInfo', 'isLogin', 'userId'])
		},
		onLoad({id, addressData}) {
			this.editId = id;
			if(id) {
				uni.setNavigationBarTitle({
				　　title: '编辑收货地址'
				})
				this.getAddressData();
			}
			if(addressData) {
				addressData = JSON.parse(addressData);
				this.formData = {
					name: addressData.name,
					phone: addressData.phone,
					province: addressData.province,
					city: addressData.city,
					area: addressData.area,
					address: addressData.address,
					houseNo: addressData.houseNo,
					defaultAddr: addressData.defaultAddr,
				}
				this.regionValue = [addressData.province, addressData.city, addressData.area];
				this.getStreetList();
			}
		},
		methods: {
			// 获取地址信息
			getAddressData() {
				this.$axios({
					url: '/user/address/detail',
					method: 'get',
					params: {
						userAddressId: this.editId
					}
				}).then(res => {
					this.formData = {
						name: res.data.name,
						phone: res.data.phone,
						province: res.data.province,
						city: res.data.city,
						area: res.data.area,
						address: res.data.address,
						houseNo: res.data.houseNo,
						defaultAddr: res.data.defaultAddr,
					}
					this.regionValue = [res.data.province, res.data.city, res.data.area];
					this.getStreetList(res.data.street);
				})
			},
			
			
			// 地图选点
			getLocation() {
				let that = this;
				uni.chooseLocation({
				    success: function (res) {
				        console.log(res);
						let SSQ_value = getArea(res.address);
						if(!SSQ_value.Province) {
							SSQ_value.Province = SSQ_value.City;
						}
						that.formData.province = SSQ_value.Province;
						that.formData.city = SSQ_value.City;
						that.formData.area = SSQ_value.Country;
						let regionValue = [];
						regionValue.push(SSQ_value.Province);
						regionValue.push(SSQ_value.City);
						regionValue.push(SSQ_value.Country);
						that.regionValue = regionValue;
						that.formData.address = res.address.slice(res.address.indexOf(SSQ_value.Country) + SSQ_value.Country.length) + res.name;
						that.getStreetList();
						that.streetValue = '';
						that.formData.street = '';
				    },
					fail: function(res) {
						uni.getSetting({
							success: function(res) {
								if (!res.authSetting['scope.userLocation']) {
									uni.showModal({
										title: '是否授权当前位置',
										content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
										success(tip) {
											if (tip.confirm) {
												uni.openSetting({
													success: function(data) {
														if (data.authSetting["scope.userLocation"] === true) {
															that.$successToast('授权成功');
															setTimeout(() => {
																that.getLocation();
															}, 1000)
														}
													}
												})
											}
										}
									})
								}
							}
						})
					}
				});
			},
			
			// 切换省市区
			onRegionChange(e) {
				console.log(e.detail);
				this.regionValue = e.detail.value;
				this.formData.province = this.regionValue[0];
				this.formData.city = this.regionValue[1];
				this.formData.area = this.regionValue[2];
				this.getStreetList();
				this.streetValue = '';
			},
			
			// 获取街道列表
			getStreetList(street) {
				this.$axios({
					url: '/common/street',
					method: 'get',
					params: {
						province: this.regionValue[0],
						city: this.regionValue[1],
						area: this.regionValue[2],
					}
				}).then(res => {
					this.streetList = res.data;
					if(street) {
						let index = this.findElem(this.streetList, 'name', street);
						this.streetValue = index;
						this.formData.street = street;
					}
				})
			},
			
			// 切换街道
			onStreetChange(e) {
				console.log(e.detail.value);
				this.streetValue = e.detail.value;
				this.formData.street = this.streetList[this.streetValue].name;
			},
			
			findElem(array, attr, val) {
			    for (var i = 0; i < array.length; i++) {
			        if (array[i][attr] == val) {
			            return i; //返回当前索引值
			        }
			    }
			    return -1;
			},
			
			switchChange(e) {
				console.log(e.detail.value);
				this.formData.defaultAddr = e.detail.value;
			},
			
			// 验证数据
			vailateData() {
				if(!this.formData.name) {
					this.$toast('请填写姓名');
					return false;
				}
				if(!this.formData.phone) {
					this.$toast('请填写手机号码');
					return false;
				}
				if(!(/^1[3456789]\d{9}$/.test(this.formData.phone))) {
					this.$toast('请填写正确的手机号码');
					return false;
				}
				if(!this.formData.province) {
					this.$toast('请选择所在地区');
					return false;
				}
				if(!this.formData.street) {
					this.$toast('请选择所在街道');
					return false;
				}
				if(!this.formData.address) {
					this.$toast('请填写收货地址');
					return false;
				}
				return true;
			},
			
			// 提交表单
			submitForm() {
				if (!this.canClickSave) return false;
				this.canClickSave = false;
				setTimeout(() => { this.canClickSave = true }, 3000)
				if(!this.vailateData())return;
				
				let params = this.formData;
				params.userId = this.userId;
				let url = '';
				if(this.editId) {
					params.userAddressId = this.editId;
					url = '/user/address/update';
				}else {
					url = '/user/address/save';
				}
				this.$axios({
					url: url,
					type: 'application/json',
					params,
					isLoading: 1,
				}).then(res => {
					this.$successToast(this.editId? '编辑成功':'添加成功');
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1000)
				})
			},
			
			// 删除
			confirmDelete() {
				this.$axios({
					url: '/user/address/del',
					params: {
						userAddressId: this.editId
					},
					isLoading: 1,
				}).then(res => {
					this.isDialog = false;
					this.$successToast('删除成功');
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1000)
				})
			}
		}
	}
</script>

<style lang="scss">
	.app-container {
		background: #F4F2F2;
		padding: 0 30rpx;
		padding-top: 20rpx;
		box-sizing: border-box;
		.row {
			background: #FFFFFF;
			margin-bottom: 20rpx;
			min-height: 88rpx;
			border-radius: 20rpx;
			padding: 0 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.title {
				font-size: 28rpx;
				color: #333333;
			}
			.right {
				width: 480rpx;
				input {
					font-size: 28rpx;
				}
				.picker {
					display: flex;
					align-items: center;
					justify-content: space-between;
					image {
						width: 16rpx;
						height: 28rpx;
					}
				}
			}
			.textarea {
				display: flex;
				justify-content: space-between;
				align-items: center;
				textarea {
					padding: 10rpx 0;
				}
				.r {
					display: flex;
					align-items: center;
					flex-shrink: 0;
					font-size: 24rpx;
					color: #666666;
					margin-left: 15rpx;
					image {
						width: 28rpx;
						height: 36rpx;
						margin-right: 16rpx;
					}
				}
			}
			.default {
				display: flex;
				justify-content: flex-end;
				switch {
					margin-right: -20rpx;
				}
			}
		}
		.button {
			width: 100%;
			height: 72rpx;
			border-radius: 72rpx;
			text-align: center;
			line-height: 72rpx;
			&.red {
				background: #FF3F42;
				color: #FFFFFF;
				margin-top: 120rpx;
			}
			&.white {
				background: #FFFFFF;
				color: #333333;
				margin-top: 20rpx;
			}
		}
	}
</style>
