<template>
	<view>
		<view class="forms">
			<view class="form_group pt0">
				<view class="lable re">收件人</view>
				<input placeholder="请输入" v-model="item.name" />
			</view>
			<view class="form_group">
				<view class="lable re">联系电话</view>
				<input type="number" maxlength="11" placeholder="请输入" v-model="item.phone" />
			</view>
			<view class="form_group">
				<view class="lable re">省市区</view>
				<uni-data-picker :localdata="cityData" v-model="item.area" :map="{ text: 'name', value: 'name' }" popup-title="选择省市区" @change="change"></uni-data-picker>
			</view>
			<view class="form_group">
				<view class="lable re">详细地址</view>
				<textarea v-model="item.street" placeholder="请输入"></textarea>
			</view>
		</view>
		<view class="mfooter">
			<view class="flex">
				<view class="f" v-if="item.id">
					<button class="save btn" @click="del()">删除</button>
				</view>
				<view class="f">
					<button class="btn" @click="save()">保存</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import city from '../../../../../common/data.js';
export default {
	data() {
		return {
			cityData: city.data.data,
			item: {}
		};
	},
	onLoad(e) {
		if (e.id) {
			this.http.request({
				url: '/level-two-server/app/address/getById/' + e.id,
				success: res => {
					this.item = res.data.data;
					uni.setNavigationBarTitle({ title: '编辑地址' });
				}
			});
		}
	},
	methods: {
		change(e) {
			if (e.detail.value.length > 0) {
				this.item.province = e.detail.value[0].value; //省
				this.item.city = e.detail.value[1].value; //市
				this.item.area = e.detail.value[e.detail.value.length - 1].value; //区
			}
			this.$forceUpdate();
		},
		save() {
			let rule = [
				{ name: 'name', checkType: 'notnull', errorMsg: '请输入收件人姓名' },
				{ name: 'phone', checkType: 'notnull', errorMsg: '请输入联系电话' },
				{ name: 'phone', checkType: 'phoneno', errorMsg: '手机号格式不对' },
				{ name: 'area', checkType: 'notnull', errorMsg: '请选择省市区' },
				{ name: 'street', checkType: 'notnull', errorMsg: '请输入详细地址' }
			];
			if (!this.verify.check(this.item, rule)) {
				uni.showModal({ content: this.verify.error, showCancel: false });
				return false;
			}
			this.http.request({
				url: '/level-two-server/app/address/saveOrUpdate',
				method: 'POST',
				data: this.item,
				success: res => {
					uni.showToast({ title: '操作成功' });
					setTimeout(() => {
						uni.$emit('address');
						uni.navigateBack();
					}, 1000);
				}
			});
		},
		del(id) {
			uni.showModal({
				title: '提示',
				content: '确定删除该地址?',
				success: res => {
					if (res.confirm) {
						this.http.request({
							url: '/level-two-server/app/address/delete/' + this.item.id,
							success: res => {
								uni.showToast({ title: '删除成功' });
								setTimeout(() => {
									uni.$emit('address');
									uni.navigateBack();
								}, 1000);
							}
						});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
.btn {
	border-radius: 5px;
	width: 100%;
}
</style>
