<template>
	<view class="address-list-container">

		<view class="address-list">
			<view v-if="addressList.length > 0">
				<block v-for="(address, index) in addressList" :key="index">
					<view class="address-item" @tap="handleAddressTap(address)">
						<view class="address-header">
							<text class="name">{{ truncateName(address.name) }}</text>
							<text class="phone">{{ address.phone }}</text>
						</view>
						<text class="address-detail">{{ address.address }}</text>
						<view class="address-footer">
							<text class="default-tag"
								:class="{ 'active': address.isDefault, 'inactive': !address.isDefault }">默认</text>
							<view class="action-buttons">
								<view class="edit-btn" @tap="editAddress(address.id)">编辑</view>
								<view class="delete-btn" @tap="confirmDelete(index)">删除</view>
							</view>
						</view>
					</view>
				</block>
			</view>
			<view v-else class="empty-address">
				<text>暂无收货地址</text>
			</view>
		</view>

		<view class="add-address-btn" @tap="addAddress">添加地址</view>

		<!-- 删除确认弹窗 -->
		<view v-if="showDeleteConfirm" class="modal-overlay" @tap="cancelDelete">
			<view class="modal-container" @tap.stop>
				<view class="modal-title">确认删除</view>
				<view class="modal-content">确定要删除该收货地址吗？</view>
				<view class="modal-buttons">
					<view class="modal-cancel" @tap="cancelDelete">取消</view>
					<view class="modal-confirm" @tap="deleteAddress">删除</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getAddressList, deleteAddress, updateAddress } from '@/api/address.js';

export default {
	data() {
		return {
			addressList: [],
			showDeleteConfirm: false,
			currentDeleteIndex: -1,
			isLoading: false,
			isSubmitting: false, // 用于防连点
			fromSettlement: false // 是否从结算页面跳转过来
		};
	},
	onLoad(options) {
		// 检查是否从结算页面跳转过来
		this.fromSettlement = options.from === 'settlement';
		console.log('是否从结算页面跳转过来:', this.fromSettlement);
		this.fetchAddressList();
	},
	onShow() {
		// 每次页面显示时刷新地址列表，避免重复请求
		if (!this.isLoading) {
			this.fetchAddressList();
		}
	},
	methods: {
		// 处理地址点击
		handleAddressTap(address) {
			if (this.fromSettlement) {
				// 如果从结算页面过来，直接返回选中的地址信息
				this.returnToSettlement(address);
			}
		},

		// 返回结算页面并传递选中的地址信息
		returnToSettlement(selectedAddress) {
			// 创建要传递的地址数据对象
			const addressData = {
				id: selectedAddress.id,
				name: selectedAddress.name,
				mobile: selectedAddress.phone || selectedAddress.mobile,
				province: selectedAddress.province,
				city: selectedAddress.city,
				area: selectedAddress.area,
				town: selectedAddress.town,
				detail: selectedAddress.detail || selectedAddress.address,
				current: selectedAddress.isDefault || false
			};

			// 使用uni-app的全局状态来存储选中的地址
			// 这是一种更可靠的数据传递方式
			uni.setStorageSync('selectedAddressForSettlement', addressData);
			
			console.log('存储选中的地址信息:', addressData);

			// 返回上一页（结算页面）
			uni.navigateBack({
				delta: 1,
				complete: () => {
					this.isSubmitting = false;
				}
			});
		},
		// 获取地址列表
		async fetchAddressList() {
			this.isLoading = true;
			try {
				const response = await getAddressList();
				console.log('地址列表接口返回:', response);

				if (response.ok && response.success && response.data) {
					// 处理API返回的地址数据，并倒序排列
					this.addressList = response.data.map(address => ({
						id: address.id,
						name: address.name,
						phone: address.mobile,
						email: address.email,
						province: address.province,
						city: address.city,
						area: address.area,
						town: address.town,
						detail: address.detail,
						postalCode: address.postalCode,
						floorNo: address.floorNo,
						isDefault: address.current,
						// 构建完整地址字符串
						address: this.buildFullAddress(address)
					})).reverse(); // 倒序排列，最新的地址在前面

					console.log('处理后的地址列表（倒序）:', this.addressList);
				} else {
					uni.showToast({
						title: response.msg || '获取地址列表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取地址列表失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		// 构建完整地址字符串
		buildFullAddress(address) {
			const parts = [];
			if (address.province) parts.push(address.province);
			if (address.city) parts.push(address.city);
			if (address.area) parts.push(address.area);
			if (address.town) parts.push(address.town);
			if (address.detail) parts.push(address.detail);
			if (address.floorNo) parts.push(address.floorNo);
			return parts.join('');
		},

		// 编辑地址
		editAddress(id) {
			// 防连点检查
			if (this.isSubmitting) return;
			this.isSubmitting = true;
			uni.navigateTo({
				url: `/v3/addressList/addressEdit?id=${id}`,
				complete: () => {
					// 页面跳转完成后重置防连点状态
					this.isSubmitting = false;
				}
			});
		},

		// 添加地址
		addAddress() {
			// 防连点检查
			if (this.isSubmitting) return;
			
			// 检查地址数量限制
			if (this.addressList.length >= 20) {
				uni.showToast({
					title: '地址添加已经达到上限啦～',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			this.isSubmitting = true;
			uni.navigateTo({
				url: '/v3/addressList/addressEdit',
				complete: () => {
					// 页面跳转完成后重置防连点状态
					this.isSubmitting = false;
				}
			});
		},

		// 确认删除
		confirmDelete(index) {
			// 防连点检查
			if (this.isSubmitting) return;
			this.currentDeleteIndex = index;
			this.showDeleteConfirm = true;
		},

		// 取消删除
		cancelDelete() {
			this.showDeleteConfirm = false;
			this.currentDeleteIndex = -1;
		},

		// 删除地址
		async deleteAddress() {
			// 防连点检查
			if (this.isSubmitting || this.currentDeleteIndex < 0) return;
			this.isSubmitting = true;
			this.isLoading = true;
			
			const address = this.addressList[this.currentDeleteIndex];
			try {
				const response = await deleteAddress({ id: address.id });
				console.log('删除地址接口返回:', response);

				if (response.ok && response.success) {
					this.addressList.splice(this.currentDeleteIndex, 1);
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: response.msg || '删除失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('删除地址失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.showDeleteConfirm = false;
				this.currentDeleteIndex = -1;
				this.isLoading = false;
				this.isSubmitting = false;
			}
		},

		// 截断姓名显示
		truncateName(name) {
			if (!name) return '';
			if (name.length <= 8) return name;
			return name.substring(0, 8) + '...';
		}
	}
};
</script>

<style scoped>
.address-list-container {
	/* 为fixed头部留出空间 */
	padding-bottom: 150rpx;
}





.address-list {
	padding: 30rpx;
}

.address-item {
	padding: 30rpx 0;
	margin-bottom: 0;
}

.address-header {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.name {
	font-size: 32rpx;
	font-weight: bold;
	margin-right: 20rpx;
}

.phone {
	font-size: 32rpx;
	color: #666666;
}



.address-detail {
	display: block;
	font-size: 30rpx;
	color: #333333;
	line-height: 44rpx;
	margin-bottom: 20rpx;
}

.address-footer {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.default-tag {
	/* 小按钮-深 可点击 - 默认标签状态 */
	/* Auto layout */
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;

	/* 宽高设置 */
	width: 106rpx;
	height: 38rpx;

	/* 背景和圆角 */
	background: #D3A458;
	border-radius: 36rpx;

	/* 字体样式 */
	font-family: 'PingFang SC';
	font-style: normal;
	font-weight: 500;
	font-size: 24rpx;
	/* 12px */
	line-height: 38rpx;
	color: #FFFFFF;

	/* 布局 */
	flex: none;
	order: 0;
	flex-grow: 0;
	padding: 0;
	gap: 0;
}

.default-tag.inactive {
	/* 非默认状态 - 置灰 */
	background: #E5E5E5;
	color: #999999;
}

.action-buttons {
	display: flex;
	align-items: center;
}

.edit-btn {
	/* 小按钮-深 不可点击 */
	box-sizing: border-box;
	/* Auto layout */
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;

	/* 宽高设置 */
	width: 106rpx;
	height: 38rpx;

	/* 边框和圆角 */
	border: 1px solid #A8A8A8;
	border-radius: 36rpx;

	/* 字体样式 */
	font-family: 'PingFang SC';
	font-style: normal;
	font-weight: 500;
	font-size: 24rpx;
	/* 12px */
	line-height: 38rpx;
	color: #A8A8A8;

	/* 布局 */
	flex: none;
	order: 0;
	flex-grow: 0;
	margin-right: 20rpx;
	padding: 0;
	gap: 0;
}

.delete-btn {
	/* 小按钮-深 */
	box-sizing: border-box;
	/* Auto layout */
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;

	/* 宽高设置 */
	width: 106rpx;
	height: 38rpx;

	/* 边框和圆角 */
	border: 1px solid #E34D59;
	border-radius: 36rpx;
	background-color: transparent;

	/* 字体样式 */
	font-family: 'PingFang SC';
	font-style: normal;
	font-weight: 500;
	font-size: 24rpx;
	/* 12px */
	line-height: 38rpx;
	color: #E34D59;

	/* 布局 */
	flex: none;
	order: 0;
	flex-grow: 0;
	padding: 0;
	gap: 0;
}

.empty-address {
	text-align: center;
	padding: 100rpx 0;
	color: #999999;
	font-size: 32rpx;
}

.add-address-btn {
	/* 小按钮-深 可点击 */
	/* Auto layout */
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	gap: 20rpx;

	position: fixed;
	width: 680rpx;
	height: 100rpx;
	right: 34rpx;
	top: calc(50% - 100rpx/2 + 610rpx);

	background: #D3A458;
	border-radius: 66rpx;

	/* 小按钮 */
	font-family: 'PingFang SC';
	font-style: normal;
	font-weight: 500;
	font-size: 36rpx;
	line-height: 50rpx;
	color: #FFFFFF;

	/* Inside auto layout */
	flex: none;
	order: 0;
	flex-grow: 0;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 200;
}

.modal-container {
	width: 600rpx;
	background-color: #ffffff;
	border-radius: 20rpx;
	overflow: hidden;
}

.modal-title {
	text-align: center;
	font-size: 34rpx;
	font-weight: bold;
	padding: 30rpx;
	border-bottom: 1rpx solid #e0e0e0;
}

.modal-content {
	text-align: center;
	font-size: 32rpx;
	color: #333333;
	padding: 40rpx 30rpx;
}

.modal-buttons {
	display: flex;
	border-top: 1rpx solid #e0e0e0;
}

.modal-cancel,
.modal-confirm {
	flex: 1;
	text-align: center;
	padding: 30rpx;
	font-size: 32rpx;
}

.modal-cancel {
	color: #666666;
	border-right: 1rpx solid #e0e0e0;
}

.modal-confirm {
	color: #ff4444;
}
</style>
