<template>
	<view>
		<u-navbar title="我的收货地址" :rightText="deleteState ? '删除' : ''" autoBack placeholder
			@rightClick="rightClick"></u-navbar>
		<view class="card_form">
			<x-form ref="personage" :list="list" :model="model" :rules="rules" btnTitle="保存地址" @confirm="confirm"
				@clientele="clientele"></x-form>
		</view>
		<u-modal width="450rpx" :show="show" showCancelButton :content='title' @cancel="show = false"
			@confirm="expurgate"></u-modal>
	</view>
</template>

<script>
	import {
		urbanArea
	} from '@/static/js/districtCode.js'
	export default {
		data() {
			return {
				show: false,
				title: '地址删除后无法恢复是否删除地址？',
				areaData: urbanArea(), //原始数据
				deleteState: false,
				list: [{
					field: 'name',
					label: '姓名',
					placeholder: '请输入姓名',
					type: 'input',
					required: true,
				}, {
					field: 'phone',
					label: '手机号码',
					placeholder: '请输入手机号码',
					type: 'input',
					required: true,
					genre: 'number',
				}, {
					field: 'region',
					label: '所在城市/地区',
					placeholder: '请选择所在城市/地区',
					type: 'cascader',
					required: true,
				}, {
					field: 'address',
					label: '详细地址',
					placeholder: '请输入详细地址',
					type: 'input',
					required: true,
				}, {
					field: 'isDefault',
					label: '设置默认地址',
					type: 'default',
				}],
				model: {
					name: '',
					phone: '',
					region: '',
					address: '',
					isDefault: false,
				},
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					},
					'phone': {
						type: 'string',
						required: true,
						message: '请输入手机号码',
						trigger: ['blur', 'change']
					},
					'region': {
						type: 'string',
						required: true,
						message: '请选择所在城市/地区',
						trigger: ['blur', 'change']
					},
					'address': {
						type: 'string',
						required: true,
						message: '请输入详细地址',
						trigger: ['blur', 'change']
					},
				},
				regionCode: [],
				addressId: '',
			}
		},
		onLoad(value) {
			// console.log(value, 24)
			if (value.revamp == 'true') {
				this.deleteState = true
				this.getListDetails(value.id)
				this.addressId = value.id
			} else {
				this.deleteState = false
			}
		},
		methods: {
			confirm(value) {
				this.regionCode = value.value
				this.model.city = this.regionCode[0].value
				this.model.area = this.regionCode[1].value
				let arr1 = []
				let arr2 = []
				this.regionCode.forEach(item => {
					arr1.push(item.value)
					arr2.push(item.label)
				})
				this.model.hr = arr1.join('/')
				this.model.region = arr2.join('/')
			},
			async clientele() {
				// console.log(this.model, 234)
				if (!this.deleteState) {
					// 添加
					const param = {
						...this.model
					}
					delete param.region
					let arr = await this.longitudeLatitude(param)
					var propertyName = arr.location.split(",")
					param.lng = Number(propertyName[0])
					param.lat = Number(propertyName[1])
					this.$api.post('/api/applet/address', param).then(res => {
						if (res.code == 200) {
							uni.navigateBack({
								delta: 1
							});
						}
					})
				} else {
					// 修改
					const param = {
						id: Number(this.addressId),
						...this.model
					}
					delete param.region
					delete param.hr
					let arr = await this.longitudeLatitude(param)
					var propertyName = arr.location.split(",")
					param.lng = Number(propertyName[0])
					param.lat = Number(propertyName[1])
					this.$api.put('/api/applet/address', param).then(res => {
						if (res.code == 200) {
							uni.navigateBack({
								delta: 1
							});
						}
					})
				}
			},
			// modal删除弹窗
			rightClick() {
				this.show = true
			},
			// 删除
			expurgate() {
				this.$api.delete('/api/applet/address', {
					id: Number(this.addressId),
				}).then(res => {
					if (res.code == 200) {
						uni.navigateBack({
							delta: 1
						});
					}
				})
			},
			getListDetails(id) {
				const arr = this.$cache.getCache('addressInfo')
				this.model.name = arr.name
				this.model.phone = arr.phone
				this.model.address = arr.address
				this.model.isDefault = arr.isDefault
				this.model.city = arr.city
				this.model.area = arr.area
				var city = this.cityScreening(arr.city, this.areaData)
				var area = this.cityScreening(arr.area, this.areaData)
				this.model.region = city + '/' + area
			},
			// 获取经纬度
			longitudeLatitude(value) {
				var cityArr = urbanArea()
				var city = this.cityScreening(value.city, cityArr)
				var area = this.cityScreening(value.area, cityArr)
				return new Promise((resolve, inject) => {
					uni.request({
						url: 'https://restapi.amap.com/v3/geocode/geo', // 你的API接口地址
						method: 'GET', // 请求方法，可选'GET'，'POST'等
						data: {
							key: 'fcddcc366fd5bd355e35f01b7cce82ef',
							address: city + area + value.address,
						},
						success: (res) => {
							resolve(res.data.geocodes[0])
						},
						fail: (err) => {
							this.confirmLoading = false
							// console.log('请求失败：', err); // 请求失败的回调函数
						}
					});
				})
			},
			// 城市筛选
			cityScreening(value, list) {
				function getChildById(parentArray, id) {
					for (let i = 0; i < parentArray.length; i++) {
						if (parentArray[i].value === id) { // 如果当前元素的ID与目标ID相等，则返回该元素
							return parentArray[i];
						} else if (parentArray[i].children && Array.isArray(parentArray[i]
								.children)) { // 判断当前元素是否有子节点且类型为数组
							const result = getChildById(parentArray[i].children, id); // 对子节点进行递归调用
							if (result !== null) { // 若子节点存在结果，则返回该结果
								return result;
							}
						}
					}
					return null; // 没有找到符合条件的元素时返回null
				}
				var name = getChildById(list, value)
				if (name != null) {
					return name.label
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-modal__content__text {
		text-align: center;
	}

	.card_form {
		margin: 10rpx 40rpx;
	}
</style>