<template>
	<view class="main">
		<view class="one">
			<uni-forms ref="form" v-model="form" :rules="rules" label-width="auto">
				<uni-forms-item label="收货人" name="name">
					<input class="input" type="text" v-model="form.name" placeholder="请输入收货人" />
				</uni-forms-item>
				<uni-forms-item label="联系电话" name="phone">
					<input class="input" type="number" v-model="form.phone" placeholder="请输入联系电话" />
				</uni-forms-item>
				<uni-forms-item label="地图选点">
					<button type="default" size="mini" class="toLoacl" @click="toLocaltion()">地图选点</button>
				</uni-forms-item>
				<uni-forms-item label="所在省份" name="province">
					<picker class="picker" mode="selector" :range="provinceList" @change="proChange" range-key="name">
						<view>{{form.province||'请选择所在省份'}}</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="所在市" name="city">
					<picker class="picker" mode="selector" :range="cityList" @change="cityChange" range-key="name">
						<view>{{form.city||'请选择所在市'}}</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="所在区" name="area">
					<picker class="picker" mode="selector" :range="areaList" @change="areaChange">
						<view>{{form.area||'请选择所在区'}}</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="详细地址" name="address">
					<textarea class="input" v-model="form.address" placeholder="请输入详细地址" />
				</uni-forms-item>
				<uni-forms-item label="是否默认" name="is_default">
					<switch color="#FB1438" :checked="form.is_default=='1'?true:false" @change="defaChange" />
				</uni-forms-item>
			</uni-forms>
			<view class="btn">
				<button type="primary" size="mini" @click="onSubmit('form')">提交保存</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getAddress
	} from '@/common/tool.js';
	export default {
		data() {
			return {
				user: {},
				id: '',
				form: {},
				rules: {
					name: {
						rules: [ //
							{
								required: true,
								errorMessage: '请输入收货人',
							},
							{
								minLength: 2,
								errorMessage: '收货人名称长度至少在 {minLength} 个字符以上',
							}
						]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入联系电话',
							tel: true
						}]
					},
					province: {
						rules: [{
							required: true,
							errorMessage: '请选择所在省'
						}]
					},
					city: {
						rules: [{
							required: true,
							errorMessage: '请选择所在市'
						}]
					},
					area: {
						rules: [{
							required: false,
							errorMessage: '请选择所在区'
						}]
					},
					address: {
						rules: [{
							required: true,
							errorMessage: '请输入详细地址'
						}]
					},
				},
				provinceList: [ //所在省份
				],
				cityList: [ //所在市
				],
				areaList: [ //所在区
				],
				paltForm: ''
			};
		},
		onLoad: function(e) {
			const that = this;
			that.$set(that, `id`, e.id || '');
			if (e.id) {
				uni.setNavigationBarTitle({
					title: '修改地址'
				});
			}
			that.searchPor();
			that.watchLogin();
		},
		onShow: function() {
			const that = this;
			let config = that.$config;
			if (config) {
				// 账号平台
				that.$set(that, `paltForm`, config.system.uniPlatform)
			}
		},
		methods: {
			// 监听用户是否登录
			watchLogin() {
				const that = this;
				uni.getStorage({
					key: 'token',
					success: async function(res) {
						let user = that.$jwt(res.data);
						if (user) {
							that.$set(that, `user`, user);
							if (that.id) {
								let arr = await that.$api(`address/${that.id}`, 'GET')
								if (arr.errcode == '0') {
									let index = that.provinceList.findIndex((i) => i.name == arr.data
										.province);
									if (index) {
										that.proChange(parseFloat(index));
									}
									that.$set(that, `form`, arr.data)
								}
							} else {
								that.$set(that, `form`, {
									name: user.name || '',
									phone: user.phone || ''
								})
							}
						}

					},
					fail: function(err) {
						uni.navigateTo({
							url: '/pagesHome/login/index'
						})
					}
				})
			},
			// 查找省
			searchPor() {
				const that = this;
				let list = that.$config.china;
				that.$set(that, `provinceList`, list)
			},
			// 定位
			toLocaltion() {
				const that = this;
				uni.chooseLocation({
					success: function(res) {
						that.searchAddress(res);
					}
				})
			},
			// 解析位置详细信息
			searchAddress(e) {
				const that = this;
				that.$set(that.form, `address`, e.address);
				if (that.paltForm == 'app') {
					var point = new plus.maps.Point(e.longitude, e.latitude);
					plus.maps.Map.reverseGeocode(point, {}, function(event) {
						var address = event.address;
						var reg = /.+?(省|市|自治区|自治州|县|区)/g;
						let addressList = address.match(reg).toString().split(",");
						let province = addressList[0] || '';
						let city = addressList[1] || '';
						let area = addressList[2] || '';
						that.$set(that.form, `province`, province);
						that.$set(that.form, `city`, city);
						that.$set(that.form, `area`, area);
					})
				} else if (that.paltForm == 'mp-weixin') {
					getAddress(e.longitude, e.latitude).then((res) => {
						if (res.status == 0) {
							let province = res.result.address_component.province;
							let city = res.result.address_component.city;
							let area = res.result.address_component.district;
							that.$set(that.form, `province`, province);
							that.$set(that.form, `city`, city);
							that.$set(that.form, `area`, area);
						} else {
							uni.showToast({
								title: '解析位置失败，请重新选择!'
							});
						}
					})
				}
			},
			// 选择省份
			proChange(e) {
				const that = this;
				let index = 0;
				if (e && e.detail && e.detail.value) index = e.detail.value
				else index = e;
				let data = that.provinceList[index];
				if (data) {
					if (that.id) {
						that.$set(that.form, `city`, '');
						that.$set(that.form, `area`, '');
					}
					that.$set(that.form, `province`, data.name);
					that.$set(that, `cityList`, data.city)
				}
			},
			// 选择市
			cityChange(e) {
				const that = this;
				let data = that.cityList[e.detail.value];
				if (data) {
					if (that.id) {
						that.$set(that.form, `area`, '');
					}
					that.$set(that.form, `city`, data.name);
					that.$set(that, `areaList`, data.area);
				}
			},
			// 选择区
			areaChange(e) {
				const that = this;
				let data = that.areaList[e.detail.value];
				if (data) {
					that.$set(that.form, `area`, data)
				}
			},
			// 是否默认
			defaChange(e) {
				const that = this;
				let value = e.detail.value == true ? '1' : '0';
				that.$set(that.form, `is_default`, value)
			},
			// 提交保存
			onSubmit(ref) {
				const that = this;
				let id = that.id;
				let user = that.user;
				that.$refs[ref].validate().then(async params => {
					params.customer = user.id;
					let res;
					if (id) res = await that.$api(`address/${id}`, 'POST', params)
					else res = await that.$api(`address`, 'POST', params);
					if (res.errcode == '0') {
						uni.showToast({
							title: '维护信息成功',
							icon: 'none'
						})
						uni.navigateBack({
							delta: 1
						})
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.main {
		display: flex;
		flex-direction: column;

		.one {
			padding: 2vw;

			.toLoacl {
				margin: 1vw 0 0 0;
			}

			.input {
				width: 94%;
				padding: 2vw;
				border: 1px solid #3333;
				border-radius: 5px;
			}

			.picker {
				border: 1px solid #3333;
				border-radius: 5px;
				padding: 2vw;
			}

			.btn {
				text-align: center;

				button {
					width: 30%;
					font-size: 14px;
					background-color: var(--fFFColor);
				}
			}
		}
	}
</style>