<template>
	<!-- 新增地址 -->
	<view>
		<u-navbar :title="headline" autoBack placeholder></u-navbar>
		<x-form ref="recipients" :list="list" :model="recipientsModel" :rules="rules"></x-form>
		<view class="btn_print" @click="addAddress()">
			<u-button type="primary" text="确定"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		formRules,
		pickupRulesil
	} from "./waybill.js";
	export default {
		data() {
			return {
				headline: '地址簿',
				list: pickupRulesil(),
				recipientsModel: {
					name: '',
					phone: '',
					address: '',
				},
				rules: {
					name: {
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					},
					phone: [{
						required: true,
						message: '请输入电话',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '请输入正确手机号码',
						trigger: ['change', 'blur'],
					}],
					address: {
						required: true,
						message: '请输入地址',
						trigger: ['blur', 'change']
					},
				},
				valueNewly: '',
				operationType: 'sender',
			}
		},
		onUnload() {
			// console.log('页面销毁')
			uni.removeStorageSync('currentAddress')
		},
		onLoad(value) {
			this.valueNewly = value.newly
			this.operationType = value.type
			let address = uni.getStorageSync('currentAddress')
			if (address) {
				this.recipientsModel = address
			}
			if (value.newly == 'true') {
				if (value.type == 'sender') {
					this.headline = '新增寄件地址'
				} else if (value.type == 'consignee') {
					this.headline = '新增收件地址'
				}
			} else {
				if (value.type == 'sender') {
					this.headline = '编辑寄件地址'
				} else if (value.type == 'consignee') {
					this.headline = '编辑收件地址'
				}
			}
		},
		methods: {
			addAddress() {
				let params = {
					id: '',
					name: this.recipientsModel.name,
					phone: this.recipientsModel.phone,
					address: this.recipientsModel.address,
					addressType: this.operationType,
				}
				if (this.valueNewly == 'true') {
					// 新增
					delete params.id
					console.log(params, 22)
					this.$api.post('/api/address', params).then(res => {
						if (res.code == 200) {
							uni.showLoading({
								icon: 'success',
								title: '新增成功'
							});
							setTimeout(function() {
								uni.hideLoading();
								uni.navigateBack({
									delta: 1
								});
							}, 1000);
						}
					})
				} else {
					params.id = this.recipientsModel.id
					// 修改
					this.$api.put('/api/address', params).then(res => {
						if (res.code == 200) {
							uni.showLoading({
								icon: 'success',
								title: '修改成功'
							});
							setTimeout(function() {
								uni.hideLoading();
								uni.navigateBack({
									delta: 1
								});
							}, 1000);
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff !important;
	}
</style>