<template>
	<view class="address-popup-box" :class="{'address-popup-box--page': pageMode}">
		<view v-if="!hideHeader" :style="headerStyle" :class="{'address-header-page': pageMode}">
			<uni-icons v-if="pageMode" type="left" size="24" @tap="$emit('close')" class="address-back-icon"
				:style="backIconStyle"></uni-icons>
			<text class="address-header-title">收货地址</text>
			<uni-icons v-if="!pageMode" type="closeempty" size="24" @tap="$emit('close')" style="position:absolute;right:30rpx;top:36rpx;"></uni-icons>
		</view>
		<view style="padding-bottom: 140rpx;">
			<view v-for="(item, index) in addressList" :key="index" @tap="selectAddress(item)"
				class="address-item">
				<view class="address-info">
					<view class="address-title-row">
						<text v-if="item.isDefault == 1" class="address-default-tag">默认</text>
						<text class="address-title">{{item.areaName || ''}}{{item.floor ? item.floor + '层' : ''}}{{item.roomNum || ''}}</text>
					</view>
					<view style="color: #777;">
						{{item.receiverName}} {{item.receiverPhone}}
					</view>
				</view>
				<view class="address-actions">
					<view @tap.stop="openEdit(item)"
						style="width: 88rpx;height: 50rpx;line-height: 50rpx;text-align: center;border: 1px solid #777;border-radius: 50rpx;color: #777;">
						编辑
					</view>
					<view @tap.stop="deleteAddress(item.id)"
						style="width: 88rpx;height: 50rpx;line-height: 50rpx;text-align: center;border: 1px solid #e43d33;border-radius: 50rpx;color: #e43d33;">
						删除
					</view>
				</view>
			</view>
			
			<view v-if="addressList.length === 0" style="text-align: center;color: #999;margin-top: 100rpx;">
				暂无收货地址
			</view>
		</view>
		<view class="bottom-btn" @tap="openAdd">
			新增地址
		</view>
		<!-- 新增地址弹出层 -->
		<uni-popup ref="addBookPopup" background-color="#fff">
			<view class="book-popup-content">
				<view style="height: 80rpx;line-height: 80rpx;font-size: 36rpx;font-weight: 700;text-align: center;">
					{{addressForm.id ? '编辑地址' : '填写地址'}}
				</view>
				<view class="area-select" @tap="openAreaPopup">
					<text v-if="areaTitleInput">{{areaTitleInput}}</text>
					<text v-else class="area-select__placeholder">请搜索选择楼座区域</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
				<view style="margin-bottom: 20rpx;display: flex;padding: 20rpx;background: rgba(247, 248, 248, 0.6);border-radius: 20rpx;">
					<input type="number" v-model="addressForm.floor" @input="onFloorInput" placeholder="请填写所在楼层(仅限整数)" style="width: 100%;" />
				</view>
				<view style="margin-bottom: 20rpx;display: flex;padding: 20rpx;background: rgba(247, 248, 248, 0.6);border-radius: 20rpx;">
					<input type="text" maxlength="30" v-model="addressForm.roomNum" @input="onRoomNumInput" placeholder="请填写门牌号或所在机构科室" style="width: 100%;" />
				</view>
				<view style="margin-bottom: 20rpx;display: flex;padding: 20rpx;background: rgba(247, 248, 248, 0.6);border-radius: 20rpx;">
					<input type="text" maxlength="20" v-model="addressForm.receiverName" @input="onReceiverNameInput" placeholder="收货人名字" style="width: 100%;" />
				</view>
				<view style="margin-bottom: 20rpx;display: flex;padding: 20rpx;background: rgba(247, 248, 248, 0.6);border-radius: 20rpx;">
					<input type="number" maxlength="11" v-model="addressForm.receiverPhone" @input="onReceiverPhoneInput" placeholder="联系电话" style="width: 100%;" />
				</view>
				<view style="margin-bottom: 20rpx;display: flex;padding: 20rpx;justify-content: space-between;align-items: center;">
					<text>设为默认地址</text>
					<switch :checked="addressForm.isDefault === 1" @change="e => addressForm.isDefault = e.detail.value ? 1 : 0" color="#a6ffea" />
				</view>
				<view class="bottom-btn" @tap="submitAddress" style="position: relative; margin-top: 40rpx;">
					确认
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="areaPopup" type="center" background-color="#fff">
			<view class="area-popup-content">
				<view class="area-popup-title">
					<text>选择楼座区域</text>
					<uni-icons type="closeempty" size="22" color="#333" @tap="closeAreaPopup"></uni-icons>
				</view>
				<view class="area-search-box">
					<input
						class="area-search-input"
						type="text"
						v-model="areaSearchInput"
						placeholder="请输入楼座名称搜索"
						placeholder-class="area-search-placeholder"
						confirm-type="search"
						:cursor-spacing="160"
					/>
				</view>
				<scroll-view scroll-y class="area-result-list">
					<view v-if="filteredAreaTitleList.length === 0" class="area-result-empty">
						未找到匹配的楼座
					</view>
					<view
						v-for="(item, index) in filteredAreaTitleList"
						:key="index"
						class="area-result-item"
						@tap="selectAreaTitle(item)"
					>
						{{item}}
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		props: {
			pageMode: {
				type: Boolean,
				default: false
			},
			hideHeader: {
				type: Boolean,
				default: false
			},
			safeTop: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				addressList: [],
				areaList: [],
				areaTitleList: [],
				areaListLoaded: false,
				areaListLoading: false,
				areaTitleInput: '',
				areaSearchInput: '',
				addressForm: {
					id: '',
					areaId: '',
					areaName: '',
					floor: '',
					roomNum: '',
					receiverName: '',
					receiverPhone: '',
					isDefault: 0
				}
			}
		},
		created() {
			this.getAddressList();
		},
		computed: {
			headerStyle() {
				if (this.pageMode) {
					return {
						height: (this.safeTop + 58) + 'px',
						lineHeight: '44px',
						paddingTop: this.safeTop + 'px',
						fontSize: '36rpx',
						fontWeight: 700,
						textAlign: 'center',
						position: 'relative',
						boxSizing: 'border-box'
					}
				}
				return {
					height: '120rpx',
					lineHeight: '120rpx',
					fontSize: '36rpx',
					fontWeight: 700,
					textAlign: 'center',
					position: 'relative'
				}
			},
			backIconStyle() {
				return {
					position: 'absolute',
					left: '30rpx',
					top: (this.safeTop + 10) + 'px'
				}
			},
			filteredAreaTitleList() {
				const keyword = (this.areaSearchInput || '').toString();
				if (!keyword) return this.areaTitleList;
				return this.areaTitleList.filter(item => item.toString().indexOf(keyword) > -1);
			}
		},
		methods: {
			getAddressList() {
				let that = this;
				that.tui.request("/app/userAddress/list", "GET", {userId:uni.getStorageSync('id')}, false, true).then((res) => {
					if (res.code == 200) {
						that.addressList = res.result || [];
						that.syncCache();
					}
				}).catch(() => {});
			},
			syncCache() {
				let cached = uni.getStorageSync('selectedAddress');
				let nextSelect = null;
				if (this.addressList.length > 0) {
					if (cached && cached.id) {
						// Look for the cached address in the fresh list to obtain updated fields if any
						nextSelect = this.addressList.find(a => a.id === cached.id);
					}
					if (!nextSelect) {
						// If cached address was deleted or none existed, fallback to default or first
						nextSelect = this.addressList.find(a => a.isDefault == 1) || this.addressList[0];
					}
				}
				if (nextSelect) {
					uni.setStorageSync('selectedAddress', nextSelect);
					this.$emit('syncAddress', nextSelect);
				} else {
					uni.removeStorageSync('selectedAddress');
					this.$emit('syncAddress', null);
				}
			},
			getAreaList() {
				if (this.areaListLoaded || this.areaListLoading) return Promise.resolve(this.areaList);
				this.areaListLoading = true;
				let that = this;
				return that.tui.request("/app/shopArea/getByParentId/"+JSON.parse(uni.getStorageSync('area')).id, "GET", {}, false, true).then((res) => {
					if (res.code == 200 && res.result) {
						that.$emit('shopAreaList',res.result)
						that.areaList = res.result;
						that.areaTitleList = res.result.map(item => item.title);
						that.areaListLoaded = true;
					}
					return that.areaList;
				}).catch(() => {}).finally(() => {
					that.areaListLoading = false;
				});
			},
			selectAddress(item) {
				this.$emit('selectAddress', item);
			},
			openAdd() {
				this.addressForm = {
					id: '',
					areaId: '',
					areaName: '',
					floor: '',
					roomNum: '',
					receiverName: '',
					receiverPhone: '',
					isDefault: 0
				};
				this.areaTitleInput = '';
				this.areaSearchInput = '';
				this.getAreaList();
				this.$refs.addBookPopup.open('bottom');
			},
			openEdit(item) {
				this.addressForm = {
					id: item.id,
					areaId: item.areaId,
					areaName: item.areaName || '',
					floor: item.floor || '',
					roomNum: item.roomNum,
					receiverName: item.receiverName,
					receiverPhone: item.receiverPhone,
					isDefault: item.isDefault || 0
				};
				this.getAreaList();
				let match = this.areaList.find(a => a.id === item.areaId);
				this.areaTitleInput = match ? match.title : (item.areaName || '');
				this.areaSearchInput = '';
				this.$refs.addBookPopup.open('bottom');
			},
			openAreaPopup() {
				this.areaSearchInput = this.areaTitleInput;
				this.getAreaList();
				this.$refs.areaPopup.open();
			},
			closeAreaPopup() {
				this.$refs.areaPopup.close();
			},
			selectAreaTitle(title) {
				this.areaTitleInput = title;
				this.areaSearchInput = title;
				this.closeAreaPopup();
			},
			onFloorInput(e) {
				const value = (e.detail.value || '').toString();
				const hasMinus = value.charAt(0) === '-';
				let nextValue = value.replace(/[^\d-]/g, '').replace(/-/g, '');
				if (hasMinus) nextValue = '-' + nextValue;
				this.addressForm.floor = nextValue;
				return nextValue;
			},
			onRoomNumInput(e) {
				const nextValue = (e.detail.value || '').toString().slice(0, 30);
				this.addressForm.roomNum = nextValue;
				return nextValue;
			},
			onReceiverNameInput(e) {
				const nextValue = (e.detail.value || '').toString().slice(0, 20);
				this.addressForm.receiverName = nextValue;
				return nextValue;
			},
			onReceiverPhoneInput(e) {
				const nextValue = (e.detail.value || '').toString().replace(/\D/g, '').slice(0, 11);
				this.addressForm.receiverPhone = nextValue;
				return nextValue;
			},
			submitAddress() {
				if(this.areaTitleInput) {
					let match = this.areaList.find(a => a.title === this.areaTitleInput);
					if (match) {
						this.addressForm.areaId = match.id;
						this.addressForm.areaName = match.title;
					} else {
						return this.tui.toast('请搜索并选择有效的楼座');
					}
				}
				if(!this.addressForm.areaId) return this.tui.toast('请搜索并选择楼座');
				this.addressForm.floor = (this.addressForm.floor || '').toString();
				this.addressForm.roomNum = (this.addressForm.roomNum || '').toString().trim();
				this.addressForm.receiverName = (this.addressForm.receiverName || '').toString().trim();
				this.addressForm.receiverPhone = (this.addressForm.receiverPhone || '').toString().replace(/\D/g, '');
				if(!this.addressForm.floor) return this.tui.toast('请填写所在楼层，楼层必须为整数数字');
				if(!/^-?\d+$/.test(this.addressForm.floor)) return this.tui.toast('楼层必须为整数');
				if(!this.addressForm.roomNum) return this.tui.toast('请填写详细地址门牌号最多30字');
				if(this.addressForm.roomNum.length > 30) return this.tui.toast('详细地址最多30字');
				if(!this.addressForm.receiverName) return this.tui.toast('请填写收件人最多20字');
				if(this.addressForm.receiverName.length > 20) return this.tui.toast('收货人名字最多20字');
				if(!this.addressForm.receiverPhone) return this.tui.toast('请输入有效的11位手机号码');
				if(!/^1[3-9]\d{9}$/.test(this.addressForm.receiverPhone)) return this.tui.toast('请输入有效的11位手机号码');
				
				let url = this.addressForm.id ? "/app/userAddress/edit" : "/app/userAddress/save";
				let that = this;
				this.addressForm.userId = uni.getStorageSync('id')
				that.tui.request(url, "POST", this.addressForm, false, true).then((res) => {
					if (res.code == 200) {
						that.tui.toast("保存成功",1000);
						that.$refs.addBookPopup.close();
						that.getAddressList();
					} else {
						that.tui.toast(res.message,1000);
					}
				}).catch(() => {});
			},
			deleteAddress(id) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确定要删除该地址吗？',
					success: function (res) {
						if (res.confirm) {
							that.tui.request("/app/userAddress/delById", "POST", {id: id}, false, true).then((res) => {
								if (res.code == 200) {
									that.tui.toast("删除成功",1000);
									that.getAddressList();
								} else {
									that.tui.toast(res.message,1000);
								}
							}).catch(() => {});
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address-popup-box {
		height: 1200rpx;
	}

	.address-popup-box--page {
		min-height: 100vh;
		height: auto;
		box-sizing: border-box;
	}

	.address-header-page {
		display: flex;
		align-items: flex-start;
		justify-content: center;
	}

	.address-header-page .address-header-title {
		display: block;
		width: 100%;
		height: 44px;
		line-height: 44px;
		text-align: center;
	}

	.address-back-icon {
		z-index: 2;
	}

	.address-item {
		margin-bottom: 20rpx;
		display: flex;
		align-items: flex-start;
		padding: 20rpx 40rpx 40rpx;
		background: rgba(247, 248, 248, 0.6);
		border-radius: 20rpx;
	}

	.address-info {
		flex: 1;
		min-width: 0;
		padding-right: 20rpx;
	}

	.address-title-row {
		min-height: 70rpx;
		display: flex;
		align-items: flex-start;
		padding-top: 10rpx;
	}

	.address-default-tag {
		flex-shrink: 0;
		margin-top: 8rpx;
		margin-right: 10rpx;
		padding: 4rpx 12rpx;
		border-radius: 8rpx;
		background: red;
		color: #fff;
		font-size: 20rpx;
		line-height: 1;
	}

	.address-title {
		flex: 1;
		min-width: 0;
		font-size: 30rpx;
		font-weight: 700;
		line-height: 42rpx;
		word-break: break-all;
		overflow-wrap: break-word;
	}

	.address-actions {
		flex-shrink: 0;
		display: flex;
		align-items: center;
		gap: 20rpx;
		padding-top: 25rpx;
	}

	.bottom-btn {
		width: 90%;
		height: 100rpx;
		background: linear-gradient(90deg, #e3ff96, #a6ffea);
		font-size: 26rpx;
		font-weight: 700;
		line-height: 100rpx;
		text-align: center;
		border-radius: 100rpx;
		margin: 20rpx auto;
		position: fixed;
		bottom: 20rpx;
		box-sizing: border-box;
		z-index: 20;
	}

	.address-popup-box--page>.bottom-btn {
		left: 5%;
	}
	.book-popup-content{
		height: auto;
		padding-top: 40rpx;
	}

	.area-select {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background: rgba(247, 248, 248, 0.6);
		border-radius: 20rpx;
		font-size: 28rpx;
		color: #333;
	}

	.area-select__placeholder {
		color: #999;
	}

	.area-popup-content {
		width: 640rpx;
		max-height: 820rpx;
		box-sizing: border-box;
		padding: 30rpx;
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
	}

	.area-popup-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 24rpx;
		font-size: 34rpx;
		font-weight: 700;
		color: #333;
	}

	.area-search-box {
		margin-bottom: 20rpx;
		padding: 18rpx 22rpx;
		background: rgba(247, 248, 248, 0.9);
		border-radius: 16rpx;
	}

	.area-search-input {
		width: 100%;
		height: 44rpx;
		line-height: 44rpx;
		font-size: 28rpx;
	}

	.area-search-placeholder {
		color: #999;
	}

	.area-result-list {
		height: 560rpx;
	}

	.area-result-empty,
	.area-result-item {
		min-height: 84rpx;
		line-height: 84rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		color: #333;
		background: #fff;
		border-bottom: 1rpx solid #f2f2f2;
	}

	.area-result-empty {
		color: #999;
		text-align: center;
	}
	
</style>