<template>
	<view>
		<u-navbar title="订气" autoBack placeholder></u-navbar>
		<view class="card_shipping">
			<view class="space_between shipping_select frame" @click="selectShipping">
				<view class="shipping_title" v-if="!addInfo.id">选择收货地址</view>
				<view v-else>
					<view class="center_item">
						<view class="title_item">{{addInfo.name}}</view>
						<view class="title_item">{{hidePhone(addInfo.phone)}}</view>
					</view>
					<view class="title_address1">
						{{cityScreening(addInfo.city, areaData)}}{{cityScreening(addInfo.area, areaData)}}{{addInfo.address}}
					</view>
				</view>
				<view style="margin-right: 10rpx;">
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
		</view>
		<view class="card_form">
			<x-form ref="personage" :loading="loading" :list="list" :model="model" :rules="rules" @clientele="clientele"
				@confirmEnsure="confirmEnsure"></x-form>
		</view>
		<u-popup :show="receivingShow" closeable :round="10" mode="bottom" @close="close">
			<view class="card_addres">
				<view class="title_address">选择收货地址</view>
				<view class="card_add_booking" v-if="addressList.length > 0">
					<view class="card_address" v-for="(item,index) in addressList" :key="index"
						@click="selectBooking(item)">
						<view class="card_group"
							:style="{border:item.flag ? '2rpx solid #2b85e4' : '2rpx solid #e7e6e4'}">
							<view class="item_radio" v-if="item.flag"></view>
						</view>
						<view style="width: 100%;">
							<view class="center_item">
								<view class="title_item">{{item.name}}</view>
								<view class="phone_title">
									<view class="title_item">{{hidePhone(item.phone)}}</view>
									<view class="tag_phone" v-if="item.isDefault">默认</view>
								</view>
							</view>
							<view class="center_item address_item">
								<view class="title_address1">
									{{cityScreening(item.city, areaData)}}{{cityScreening(item.area, areaData)}}{{item.address}}
								</view>
								<view @click.stop="goAmend(item)"><u-icon name="edit-pen" size="30"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view style="margin-top: 30%;" v-else>
					<u-empty mode="address"></u-empty>
				</view>
				<view class="btn_add">
					<u-button type="primary" size="normal" text="新增收货地址" @click="rightClick"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		urbanArea
	} from '@/static/js/districtCode.js'
	export default {
		data() {
			return {
				areaData: urbanArea(), //原始数据
				list: [{
					field: 'commodity',
					label: '商品',
					placeholder: '请选择商品',
					type: 'select',
					required: true,
					options: [],
				}, {
					field: 'specification',
					label: '规格',
					placeholder: '请选择规格',
					type: 'select',
					required: true,
					options: [],
				}, {
					field: 'amount',
					label: '数量',
					placeholder: '请输入数量',
					type: 'input',
					required: true,
					genre: 'number',
				}, {
					field: 'remark',
					label: '备注',
					placeholder: '请输入备注',
					type: 'textarea',
				}],
				model: {
					commodity: '',
					specification: '',
					amount: '',
					remark: '',
					goodsId: null,
					specId: null,
				},
				rules: {
					'commodity': {
						type: 'string',
						required: true,
						message: '请选择商品',
						trigger: ['blur', 'change']
					},
					'specification': {
						type: 'string',
						required: true,
						message: '请选择规格',
						trigger: ['blur', 'change']
					},
					'amount': {
						type: 'number',
						required: true,
						message: '请输入数量',
						trigger: ['blur', 'change']
					},
				},
				receivingShow: false,
				addressList: [],
				value: '',
				addInfo: {},
				companyId: null,
				loading: false,
				revamp: '',
				operated: '',
				orderData: {},
			}
		},
		onLoad(value) {
			this.companyId = value.companyId
			this.revamp = value.revamp
			this.operated = value.revamp
			if (value.revamp == 'true') {
				this.getDataEcho()
			}
		},
		onShow() {
			this.getList()
		},
		mounted() {
			this.getGoodsList()
		},
		methods: {
			selectShipping() {
				this.receivingShow = true
			},
			close() {
				this.receivingShow = false
			},
			// 获取收货地址列表
			getList() {
				this.addInfo = {}
				this.$api.get('/api/applet/address').then(res => {
					if (res.code == 200) {
						this.addressList = res.data.list
						if (this.addressList.length > 0 && !this.revamp) {
							this.addressList.forEach(item => {
								if (item.isDefault) {
									item.flag = true
									this.addInfo = item
								} else {
									item.flag = false
									return
									this.addressList[0].flag = true
									this.addInfo = this.addressList[0]
								}
							})
						} else {
							this.operated = false
							this.addressList.forEach(item => {
								if (this.orderData.phone == item.phone) {
									item.flag = true
									this.addInfo = item
								} else {
									item.flag = false
								}
							})
						}
					}
				})
			},
			// 选择商品/规格
			confirmEnsure(value) {
				// console.log(value, 24)
				if (value.type == 'commodity') {
					this.model.goodsId = value.id
				} else if (value.type == 'specification') {
					this.model.specId = value.id
				}
			},
			// 订单数据回显
			getDataEcho() {
				const arr = this.$cache.getCache('orderList')
				this.orderData = arr
				// console.log(arr, 22)
				this.model.goodsId = arr.goodsId
				this.model.specId = arr.specId
				this.model.commodity = arr.goods.name
				this.model.specification = arr.spec.name
				this.model.amount = arr.quantity
				this.model.remark = arr.remark
			},
			// 订气
			clientele() {
				const params = {
					address: '',
					phone: this.addInfo.phone,
					storeId: Number(this.companyId),
					goodsId: this.model.goodsId,
					quantity: Number(this.model.amount),
					specId: this.model.specId,
					remark: this.model.remark,
					lng: this.addInfo.lng,
					lat: this.addInfo.lat,
					city: this.addInfo.city,
					area: this.addInfo.area,
					addressImg: this.addInfo.addressImg,
				}
				const cityty = this.cityScreening(this.addInfo.city, this.areaData)
				const areaty = this.cityScreening(this.addInfo.area, this.areaData)
				const addressty = cityty + areaty + this.addInfo.address
				params.address = addressty
				this.loading = true
				if (!this.revamp) {
					this.$api.post('/api/applet/order', params).then(res => {
						if (res.code == 200) {
							uni.navigateTo({
								url: '/pages/indexRouter'
							})
							uni.$emit('booking');
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
						this.loading = false
					})
				} else {
					params.id = this.orderData.id
					this.$api.put('/api/applet/order', params).then(res => {
						if (res.code == 200) {
							uni.navigateTo({
								url: '/pages/indexRouter'
							})
							uni.$emit('booking');
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						}
						this.loading = false
					})
				}
			},
			// 获取商品列表
			getGoodsList() {
				this.$api.get('/api/applet/goods', {
					storeId: this.companyId,
				}).then(res => {
					if (res.code == 200) {
						const arrList = res.data.list
						const dataList = [
							[]
						]
						arrList.forEach(item1 => {
							let arr = {
								label: item1.name,
								value: item1.id,
							}
							dataList[0].push(arr)
						})
						this.list.forEach(item => {
							if (item.field == 'commodity') {
								item.options = []
								item.options = dataList
							}
						})
						this.getCylinderSpec()
					}
				})
			},
			// 获取规格列表
			getCylinderSpec() {
				this.$api.get('/api/applet/gas-cylinder-spec', {
					storeId: this.companyId,
				}).then(res => {
					if (res.code == 200) {
						const arrList = res.data.list
						const dataList = [
							[]
						]
						arrList.forEach(item1 => {
							let arr = {
								label: item1.name,
								value: item1.id,
							}
							dataList[0].push(arr)
						})
						this.list.forEach(item => {
							if (item.field == 'specification') {
								item.options = []
								item.options = dataList
							}
						})
					}
				})
			},
			// 选择收货地址
			selectBooking(value) {
				this.addressList.forEach(item => {
					if (value.id == item.id) {
						this.addInfo = item
						this.receivingShow = false
						item.flag = true
					} else {
						item.flag = false
					}
				})
				this.$forceUpdate()
			},
			// 新增地址
			rightClick() {
				this.receivingShow = false
				uni.navigateTo({
					url: '/pages/mine/addAddress'
				});
			},
			// 修改地址
			goAmend(value) {
				this.receivingShow = false
				this.$cache.setCache('addressInfo', value)
				uni.navigateTo({
					url: '/pages/mine/addAddress?revamp=' + true + '&id=' + value.id
				});
			},
			// 城市筛选
			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
				}
			},
			hidePhone(phoneNumber) {
				if (phoneNumber) {
					function hidePhoneNumber(phoneNumber) {
						return phoneNumber.slice(0, 3) + '****' + phoneNumber.slice(-4);
					}
					const hiddenPhoneNumber = hidePhoneNumber(phoneNumber);
					return hiddenPhoneNumber
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.card_shipping {
		display: flex;
		width: 100%;
	}

	.shipping_select {
		display: flex;
		align-items: center;
		padding-left: 20rpx;
		margin: 20rpx 30rpx;
		width: 100%;
		height: 120rpx;
		border-radius: 6rpx;
		// border: 1rpx solid #e7e6e4;
	}

	// 伪元素1rpx边框
	.frame {
		position: relative; //重要
	}

	.frame::after {
		position: absolute;
		content: '';
		border: 2rpx solid #e7e6e4;
		border-radius: 16rpx;
		width: 200%;
		height: 200%;
		top: 0;
		left: 0;
		transform: scale(0.5);
		transform-origin: 0 0;
	}

	.shipping_title {
		font-size: 30rpx;
		font-weight: 600;
	}

	.card_form {
		margin: 10rpx 30rpx;
	}

	.card_add_booking {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.card_addres {
		height: 50vh;
	}

	.title_address {
		margin-top: 20rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: 600;
	}

	.card_address {
		display: flex;
		margin: 30rpx 20rpx 20rpx 20rpx;
		padding: 10rpx;
		border-bottom: 1rpx solid #e7e6e4;
	}


	.center_item {
		display: flex;
		align-items: center;
	}

	.title_item {
		font-size: 26rpx;
		color: #606266;
	}

	.phone_title {
		position: relative;
		margin-left: 30rpx;
	}

	.tag_phone {
		position: absolute;
		right: -53rpx;
		top: -14rpx;
		padding: 2rpx 4rpx;
		border: 1rpx solid #2b85e4;
		font-size: 20rpx;
		color: #2b85e4;
	}

	.title_address1 {
		font-size: 30rpx;
		color: #303133;
		font-weight: 600;
	}

	.address_item {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin-top: 6rpx;
	}

	.card_group {
		position: relative;
		flex: none;
		margin-right: 15rpx;
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
	}

	.item_radio {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		background-color: #2b85e4;
	}

	.btn_add {
		width: calc(100% - 40rpx);
		position: fixed;
		bottom: 0;
		padding: 20rpx;
		background-color: #fff;
	}
</style>