<template>
	<view class="address-page">
		
		<!-- 搜索框（原生 input 实现，兼容微信小程序） -->
		<view class="search-section">
			<view class="search-box">
				<!-- 搜索图标 -->
				<view class="search-icon">
					<u-icon name="search" size="22" color="#999"></u-icon>
				</view>
				<!-- 输入框 -->
				<input 
					class="search-input" 
					type="text" 
					v-model="searchKeyword" 
					placeholder="请输入姓名/手机号/地址"
					placeholder-class="placeholder-style"
					confirm-type="search"
					@confirm="handleSearch"
				/>
				<!-- 自定义清除按钮 -->
				<view v-if="searchKeyword" class="search-clear" @click.stop="handleClear">
					<u-icon name="close-circle" size="22" color="#999"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 地址列表 -->
		<view class="address-list">
			<!-- 地址项组件 -->
			<address-item v-if="addressList.length > 0" v-for="(item, index) in addressList" :key="item.id"
				:address="item" :is-default="item.isDefault" @set-default="handleSetDefault(index)"
				@edit="handleEdit(index)" @delete="handleDelete(index)" @click="onSelectAddress(item)" />

			<!-- 空状态 -->
			<view class="empty-state" v-if="addressList.length === 0 && !loadState">
				<u-icon class="empty-icon" name="list" size="60" color="#ccc"></u-icon>
				<text class="empty-text">暂无数据</text>
			</view>

			<!-- 加载状态提示 -->
			<view class="load-more-status" v-if="loadState">
				<text>加载中...</text>
			</view>

			<view class="load-more-status" v-if="loadFinished && addressList.length !== 0">
				<text>没有更多数据了</text>
			</view>
		</view>

		<!-- 添加新地址按钮 -->
		<view class="add-btn-container">
			<button class="add-btn" @click="handleAddAddress">
				<text class="add-btn-text">添加新地址</text>
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom
	} from '@dcloudio/uni-app'
	import AddressItem from '@/components/AddressItem.vue'
	import {
		listBook,
		delBook,
		updateBook
	} from '../../api/address'

	const searchKeyword = ref('')
	const pageNum = ref(1)
	const pageSize = ref(10)
	const recordTotal = ref(0)
	const loadState = ref(false)
	const loadFinished = ref(false)

	// 模拟地址数据
	const addressList = ref([])
	const pages = ref(0) // 总页数

	// 当前要操作的地址索引
	const currentIndex = ref(-1)

	const addType = ref('')

	onLoad((option) => {
		addType.value = option.addType
	})

	onShow(() => {
		pageNum.value = 1
		getAddressList()
	})

	// 下拉刷新
	onPullDownRefresh(() => {
		pageNum.value = 1
		getAddressList()
	})

	// 触底加载更多
	onReachBottom(() => {
		if (pageNum.value < pages.value) {
			pageNum.value++;
			getAddressList()
		}
	})

	const onSelectAddress = (address) => {
		console.log('-------address---', address)
		if (!addType.value) {
			return
		}
		uni.$emit('addressSelected', {
			type: addType.value, // 'sender' 或 'receiver'
			address // 选中的地址对象
		})
		uni.navigateBack() // 返回上一页
	}

	// 设置默认地址
	const handleSetDefault = async (index) => {
		const currentAddress = addressList.value[index];
		// 如果已经是默认地址，则无需操作
		if (currentAddress.defaultFlag === 1) {
			uni.showToast({
				title: '已是默认地址',
				icon: 'none'
			});
			return;
		}

		uni.showLoading({
			title: '设置中...',
			mask: true
		});

		try {
			// 调用接口设置为默认地址（后端应自动处理其他地址的非默认状态）
			const res = await updateBook({
				...currentAddress,
				defaultFlag: 1
			});

			if (res.code === 200) {
				// 更新本地数据：将所有地址的 defaultFlag 设为 0，再将当前项设为 1
				addressList.value.forEach(item => item.defaultFlag = 0);
				currentAddress.defaultFlag = 1;

				uni.showToast({
					title: '设置成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: res.msg || '设置失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
			console.error('设置默认地址失败', error);
		} finally {
			uni.hideLoading();
		}
	}

	// 编辑地址
	const handleEdit = (index) => {
		// 跳转到编辑页面
		uni.navigateTo({
			url: '/pages/address/edit?id=' + addressList.value[index].addressId
		})
	}

	// 删除地址
	const handleDelete = (index) => {
		currentIndex.value = index
		uni.showModal({
			title: '确认删除',
			content: '是否确认删除这个地址',
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({
						title: '删除中...',
						mask: true
					});
					try {
						const delRes = await delBook(addressList.value[index].addressId)
						if (delRes.code == 200) {
							// 移除本地数据
							addressList.value.splice(currentIndex.value, 1)
							currentIndex.value = -1

							// 如果删除的是默认地址，且列表不为空，可考虑自动将第一个地址设为默认（根据业务需求可选）
							// 此处不做自动处理，由用户手动设置

							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
						} else {
							uni.showToast({
								title: delRes.msg || '删除失败',
								icon: 'none'
							})
						}
					} catch (error) {
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					} finally {
						uni.hideLoading()
					}
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	// 添加新地址
	const handleAddAddress = () => {
		uni.navigateTo({
			url: '/pages/address/edit'
		})
	}

	// 搜索（点击键盘搜索或清除后调用）
	const handleSearch = () => {
		pageNum.value = 1
		getAddressList()
	}

	// 清除按钮点击
	const handleClear = () => {
		searchKeyword.value = ''
		handleSearch()
	}

	const loadMore = () => {
		pageNum.value++
		getAddressList(true)
	}

	// 获取地址列表
	const getAddressList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			searchKeyword:searchKeyword.value
		}

		uni.showLoading({
			mask: true
		})
		listBook(params).then(res => {
			uni.hideLoading()
			uni.stopPullDownRefresh()

			if (res.code === 200) {
				const list = res.rows || []
				addressList.value = pageNum.value == 1 ? list : [...addressList.value, ...list]
				pages.value = Math.ceil(res.total / pageSize.value) || 0
			}
		}, err => {
			uni.hideLoading()
			uni.stopPullDownRefresh()
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		})
	}
</script>

<style scoped lang="less">
	.address-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #F5F7FA;
	}

	.search-section {
		background-color: #fff;
		padding: 16rpx;
		margin-left: 14rpx;
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #F5F7FA;
		border-radius: 36rpx;
		padding: 0 20rpx;
		height: 72rpx; /* 与 u-search 高度一致 */
	}

	.search-icon {
		margin-right: 16rpx;
		display: flex;
		align-items: center;
	}

	.search-input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
		color: #333;
		background-color: transparent;
		border: none;
		outline: none;
	}

	.placeholder-style {
		color: #999;
		font-size: 28rpx;
	}

	.search-clear {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 16rpx;
		padding: 8rpx;
		
		&:active {
			opacity: 0.6;
		}
	}


	.address-list {
		padding: 20rpx 30rpx 152rpx;
		box-sizing: border-box;
	}

	.load-more-status {
		text-align: center;
		padding: 20rpx;
		font-size: 24rpx;
		color: #999;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 40rpx;
		color: #999999;
	}

	.empty-text {
		margin-top: 20rpx;
		font-size: 28rpx;
	}

	.add-btn-container {
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		padding: 32rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		box-sizing: border-box;
	}

	.add-btn {
		height: 88rpx;
		background: #1B64F0;
		border-radius: 44rpx;
		border: none;
	}

	.add-btn-text {
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;
		height: 88rpx;
		line-height: 88rpx;
	}

	/* 按钮激活效果 */
	.add-btn:active {
		opacity: 0.8;
	}
</style>