<template>
	<view class="wrap">
		<w-navbar :title="title"></w-navbar>
		<view class="top">
			<view class="item">
				<view class="left">收货人</view>
				<input :disabled="nameStatus" v-model="name" type="text" placeholder-class="line" placeholder="请填写收货人姓名" />
			</view>
			<view class="item">
				<view class="left">电话号码</view>
				<input :disabled="mobileStatus" v-model="mobile" type="text" @blur="verifyMobile" placeholder-class="line" placeholder="请填写收货人手机号" />
			</view>

			<view class="item">
				<view class="left">所在地区</view>
				<input @tap="showRegionPicker" disabled v-model="formatRegion" type="text" placeholder-class="line" placeholder="省市区县、乡镇等" />
				<u-icon @click="autoLocation" class="right" name="map" label="定位" label-size="24" label-color="#2272FF" />
			</view>
			<u-field
				class="item-address"
				v-model="address"
				label="详细地址"
				label-width="160"
				placeholder="街道、楼牌等"
				placeholder-style="color:#c0c4cc;"
				type="textarea"
				:auto-height="false"
				:border-bottom="false"
			></u-field>
		</view>
		<view class="bottom">
			<button class="btn, bottom-btn" v-if="siteType=='select'" @click="$u.throttle(commitSite, 500)"><text class="button-text">保存</text></button>
			<button class="btn, bottom-btn" v-else @click="show = true"><text class="button-text">保存</text></button>
		</view>
		<u-picker mode="region" v-model="showPicker" :default-region="region" @confirm="confirmRegion" />
		<u-popup border-radius="12" width="690" height="520" v-model="show" mode="center">
			<view class="save-pop">
				<view class="header">确认保存信息</view>
				<view class="content"><view class="tips">您填写的信息尚未保存，是否保存</view></view>
			</view>
			<view class="pop-bottom">
				<button class="plain" @click="show = false" shape="circle" :plain="true">不保存</button>
				<u-button :custom-style="submitBtn" shape="circle" @click="submitForm" :disabled="disabledSubmit">保存</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
/**
 * addSite 新增地址|修改地址|选择地址（返回选择地址信息）
 * @description 编辑地址共通页
 * @property {String} type 编辑类型（默认为修改，add--新增、edit--修改、select--选择）
 * @property {String} info 地址信息（json字符串：包含地址信息）
 */
let r = require('libs/bmap-wx.min.js');
let h = new r.BMapWX({
	ak: process.uniEnv.bmapAK,
});
export default {
	data() {
		return {
			title: '修改地址',
			siteInfo: null,
			siteType: 'edit',
			show: false,
			location: '',
			address: '',
			type: '充电桩安装',
			id: null,
			name: '',
			mobile: '',
			nameStatus: true,
			mobileStatus: true,
			settled: null,
			adcode: '',
			regionObj: [],
			region: [],
			showPicker: false,
			loading: true
		};
	},
	computed: {
		formatRegion() {
			return this.region.join(' ');
		},
		submitBtn() {
			return {
				color: '#FFFFFF',
				backgroundColor: '#2272FF'
			};
		}
	},
	onLoad(e) {
		getApp().trackPage('我的收获地址修改页');
		if (!this.vuex_token) {
			this.$u.route({ url: 'pages/login/index' });
		}
		if (e) {
			if (e.type === 'add') {
				this.title = '新增地址';
				this.siteType = 'add';
			} else if (e.type === 'select') {
				this.title = '收货地址';
				this.siteType = 'select';
			} else if (e.type == 'edit') {
				this.title = '修改地址';
				this.siteType = 'edit';
			}
			
			if(e.id) {
				this.id = decodeURIComponent(e.id);
			}

			if(e.name) {
				this.name = decodeURIComponent(e.name);
			}
			if(e.mobile) {
				this.mobile = decodeURIComponent(e.mobile);
			}
			if(e.region) {
				let regionStr = decodeURIComponent(e.region);
				this.region = regionStr.split('-')
			}
			if(e.address) {
				let address = decodeURIComponent(e.address);
				let region = this.region.join('')
				if(this.$u.test.contains(address, region)) {
					this.address = address.replace(region, '')
				} else {
					this.address = address
				}
			}
		}
	},
	onShow() {
		this.getData();
	},
	methods: {
		getData() {
			if (this.siteType == 'add' || this.siteType == 'select') {
				this.nameStatus = false;
				this.mobileStatus = false;
			} else if (this.siteType == 'edit') {
				if (this.$u.test.isEmpty(this.name) 
				|| this.$u.test.isEmpty(this.mobile)) {
					const callback = (vm, res) => {
						this.settled = res.record;
						this.name = this.settled.id_card_name;
						this.mobile = this.settled.mobile;
					};
					if (this.vuex_settled && this.vuex_settled.record) {
						callback(this, this.vuex_settled);
					} else {
						getApp().getBaseInfo(this, callback);
					}
				}
				
				if (this.$u.test.isEmpty(this.region)
				|| this.$u.test.isEmpty(this.address)) {
					
				}
			}
		},
		loadMineAddress() {
			this.$u.api.getSiteAddress().then((res) => {
				if(res.code == 200 && res.data) {
					this.region = [
						res.data.provinceName, 
						res.data.cityName, 
						res.data.districtName
					]
					let address = res.data.address
					const regionStr = this.region.join('')
					if(this.$u.test.contains(address, regionStr)) {
						this.address = address.replace(regionStr, '')
					} else {
						this.address = address
					}
				}
			})
		},
		showRegionPicker() {
			this.showPicker = true;
		},
		confirmRegion(params) {
			this.regionObj = params;
			this.region = [params.province.label, params.city.label, params.area.label];
		},
		/**
		 * 百度定位
		 * @param {Object} long
		 * @param {Object} lat
		 */
		regeocoding(lat, long) {
			if (lat && long) {
				h.regeocoding({
					location: lat + ',' + long,
					success: data => {
						this.location = data.wxMarkerData[0];
						let regeocod = data.originalData.result.addressComponent;
						this.adcode = regeocod.adcode;
						this.region = [regeocod.province, regeocod.city, regeocod.district];
						let region = this.region.join('');
						if (this.$u.test.contains(this.address, region)) {
							this.address = this.address.replace(region, '');
						}
					}
				});
			}
		},
		geocoding() {
			if (this.address) {
				let t = {
					success: res => {
						let e = res.wxMarkerData[0];
						if (e.longitude && e.latitude) {
							this.regeocoding(e.latitude, e.longitude);
						}
					}
				};
				t.address = this.address;
				h.geocoding(t);
			}
		},

		/**
		 * 自动定位
		 */
		autoLocation() {
			let that = this;
			uni.chooseLocation({
				success: res => {
					this.address = res.address + res.name;
					this.regeocoding(res.latitude, res.longitude);
				}
			});
		},

		verifyMobile() {
			if(this.$u.test.isEmpty(this.mobile)) {
				this.$u.toast('电话号码不能为空')
				return false
			} else if(!this.$u.test.mobile(this.mobile)) {
				this.$u.toast('电话号码格式错误')
				return false
			}
			return true
		},
		validateForm() {
			if(this.$u.test.isEmpty(this.name)) {
				this.$u.toast('收货人姓名不能为空')
				return false
			}
			if(!this.verifyMobile()) {
				return false
			}
			if(this.$u.test.isEmpty(this.region)) {
				this.$u.toast('所在地区不能为空')
				return false
			}
			if(this.$u.test.isEmpty(this.address)) {
				this.$u.toast('详细地址不能为空')
				return false
			}
			return true
		},
		async submitForm() {
			if(!this.validateForm()) {
				return false
			}
			if (this.siteType === 'select') {
				this.commitSite()
			} else {
				if (this.$u.test.isEmpty(this.siteInfo)) {
					let params = {
						updateFlag: true,
						provinceName: this.region[0],
						cityName: this.region[1],
						districtName: this.region[2],
						address: this.address
					};
					let res = await this.$u.api.updateAddress(params);
					if (res && res.code == 200) {
						this.$u.route({ type: 'back' });
						this.show = false
					}
				} else {
					
				}
			}
		},
		async commitSite() {
			if(!this.validateForm()) {
				return false
			}
			let params = {
				mobile: this.mobile,
				name: this.name,
				provinceName: this.region[0],
				cityName: this.region[1],
				districtName: this.region[2],
				address: this.address
			};
			if (this.id) params.id = this.id
			let res = await this.$u.api.saveMyAddress(params);
			if (res && res.code == 200) {
				let pages = getCurrentPages()
				let prevPage = pages[pages.length - 2]
				if (prevPage.route === 'pages/parts/application') {
					let address = this.region.join("") + this.address
					let site = {
						name: this.name,
						mobile: this.mobile,
						address: address,
						region: this.region,
						id: this.id
					}
					prevPage.$vm.updateSite(site)
				}
				this.show = false
				this.$u.route({ type: 'back' });
			}
		}
	}
};
</script>

<style lang="scss" scoped>
/deep/ .line {
	color: $u-light-color;
	font-size: 28rpx;
}
.wrap {
	background-color: #ffffff;
	width: 750rpx;
	height: 100vh;
	.top {
		background-color: #ffffff;
		padding: 10rpx 30rpx 0 30rpx;
		.item {
			display: flex;
			font-size: 28rpx;
			font-weight: 400;
			color: #333333;
			line-height: 88rpx;
			align-items: center;
			border-bottom: solid 2rpx #f4f5f7;
			.left {
				width: 160rpx;
				color: #999999;
			}
			input {
				text-align: left;
				flex: auto;
			}

			.textarea {
			}
			.right {
				margin-left: 30rpx;
				font-size: 30rpx;
				font-weight: 400;
				color: #2272ff;
			}
		}
		.item-address {
			height: 168rpx;
			width: auto;
			flex: auto;
			/deep/ .u-field {
				padding: 0;
				padding-top: 30rpx;
				border-bottom: solid 2rpx #f4f5f7;
				.u-label {
					color: #999999;
					line-height: normal;
				}
				.fild-body {
					font-size: 28rpx;
					font-weight: 400;
					color: #333333;
					textarea {
						line-height: normal;
						height: 98rpx;
					}
				}
				.fild-body > view {
					margin: 4rpx 8rpx 0 0 !important;
				}
				.right {
					margin-left: 30rpx;
					font-size: 30rpx;
					font-weight: 400;
					color: #2272ff;
					align-self: top;
				}
			}
		}
	}
	.bottom {
		margin-top: 160rpx;
		padding: 0 40rpx;
		background-color: #ffffff;
		font-size: 28rpx;
		.default {
			margin-top: 50rpx;
			display: flex;
			justify-content: space-between;
			border-bottom: solid 2rpx $u-border-color;
			line-height: 64rpx;
			.tips {
				font-size: 24rpx;
			}
			.right {
			}
		}
	}

	.save-pop {
		padding: 0 30rpx;
		.header {
			text-align: center;
			font-size: 40rpx;
			font-weight: bold;
			color: #333333;
			border-bottom: solid 2rpx #f4f5f7;
			line-height: 40rpx;
			padding: 60rpx 0 40rpx 0;
		}
		.content {
			margin-top: 80rpx;
			margin-bottom: 116rpx;
			.tips {
				text-align: center;
				font-size: 28rpx;
				font-weight: 400;
				color: #999999;
				line-height: 28rpx;
			}
		}
	}
	/deep/ .pop-bottom {
		padding: 0 16rpx;
		margin-top: 0;
		display: flex;
		justify-content: space-between;
		button {
			width: 300rpx;
			height: 104rpx;
			border-radius: 52rpx;
			padding: 0;
		}
		.plain {
			border: 2px solid #2272ff;
			color: #2272ff;
		}
		.solid {
			color: #ffffff;
			background-color: #2272ff;
		}
	}
}
.btn {
	padding: 30rpx;
	border-radius: 52rpx;
	line-height: 44rpx;
	font-size: 32rpx;
	text-align: center;
	background-color: #2272ff;
	color: #fff;
	&::after {
		content: '';
		height: 0;
		border: none;
	}
}
</style>
