<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">
						<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 } from '@/api/address.js';

export default {
	data() {
		return {
			addressList: [],
			showDeleteConfirm: false,
			currentDeleteIndex: -1,
			isLoading: false
		};
	},
	onLoad() {
		this.fetchAddressList();
	},
	onShow() {
		// 每次页面显示时刷新地址列表，避免重复请求
		if (!this.isLoading) {
			this.fetchAddressList();
		}
	},
	methods: {
		// 获取地址列表
		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) {
			uni.navigateTo({
				url: `/v3/addressList/addressEdit?id=${id}`
			});
		},

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

			uni.navigateTo({
				url: '/v3/addressList/addressEdit'
			});
		},

		// 确认删除
		confirmDelete(index) {
			this.currentDeleteIndex = index;
			this.showDeleteConfirm = true;
		},

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

		// 删除地址
		async deleteAddress() {
			if (this.currentDeleteIndex >= 0) {
				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'
					});
				}
			}
			this.showDeleteConfirm = false;
			this.currentDeleteIndex = -1;
		},

		// 截断姓名显示
		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>
