<template>
	<view class="collect-page">


		<!-- 搜索栏 -->
		<view class="search-section">
			<view class="search-container">
				<u-search v-model="searchKeyword" placeholder="搜索收藏的商品" :showAction="true" actionText="搜索"
					@search="handleSearch" @custom="handleSearch" :clearabled="true" @clear="handleClear"></u-search>
			</view>
			<!-- 批量操作栏 -->
			<view v-if="collectList.length > 0" class="batch-actions">
				<view class="batch-info">
					<text class="batch-text">共 {{ collectList.length }} 件收藏商品</text>
				</view>
				<view class="batch-buttons">
					<view class="batch-btn" @click="selectAll">
						<text class="batch-btn-text">{{ isAllSelected ? '取消全选' : '全选' }}</text>
					</view>
					<view v-if="selectedItems.length > 0" class="batch-btn delete-btn" @click="batchCancelCollect">
						<text class="batch-btn-text">取消收藏({{ selectedItems.length }})</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 商品列表 -->
		<scroll-view class="product-list" scroll-y @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
			<!-- 商品卡片 -->
			<view v-if="collectList.length > 0" class="product-container">
				<view v-for="(item, index) in collectList" :key="item.id" class="product-card"
					@click="goToDetail(item.id)">
					<!-- 选择框 -->
					<view class="select-checkbox" :class="{ 'selected': selectedItems.includes(item.id) }"
						@click.stop="toggleSelect(item.id)">
						<view v-if="selectedItems.includes(item.id)" class="checkmark">✓</view>
					</view>

					<!-- 商品图片 -->
					<view class="product-image-container">
						<image :src="item.images" mode="aspectFill" class="product-image" @error="handleImageError">
						</image>
						<!-- 取消收藏按钮 -->
						<view class="collect-btn" @click.stop="cancelCollect(item, index)">
							<u-icon name="heart-fill" size="24" color="#FF4B4B"></u-icon>
						</view>
					</view>

					<!-- 商品信息 -->
					<view class="product-info">
						<view class="product-name">{{ item.name }}</view>
						<view class="product-desc" v-if="item.description">{{ item.description }}</view>

						<!-- 商品评分和销量 -->
						<view class="product-meta">
							<view class="rating-section" v-if="item.productAvg">
								<u-rate :value="item.productAvg" readonly allowHalf size="12"
									activeColor="#FFD700"></u-rate>
								<text class="rating-text">{{ item.productAvg }}</text>
							</view>
							<view class="sales-info">
								<text class="sales-text">已售{{ item.salesTotal || 0 }}件</text>
							</view>
						</view>

						<!-- 价格区域 -->
						<view class="price-section">
							<view class="price-info">
								<text class="price-symbol">¥</text>
								<text class="price-value">{{ item.price }}</text>
								<text class="original-price"
									v-if="item.originalPrice && item.originalPrice > item.price">
									¥{{ item.originalPrice }}
								</text>
							</view>
							<view class="action-buttons">
								<view class="buy-btn" @click.stop="goToDetail(item.id)">
									<text class="buy-text">立即购买</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-else-if="!isLoading" class="empty-state">
				<u-empty mode="favor" icon="/static/images/empty.png" text="暂无收藏商品">
					<view class="empty-tips">
						<text class="tips-text">快去收藏喜欢的商品吧</text>
						<view class="go-shop-btn" @click="goToShop">
							<text class="btn-text">去逛逛</text>
						</view>
					</view>
				</u-empty>
			</view>

			<!-- 网络错误状态 -->
			<view v-else-if="networkError" class="error-state">
				<u-empty mode="wifi" icon="/static/images/empty.png" text="网络连接失败">
					<view class="error-tips">
						<text class="error-text">请检查网络连接后重试</text>
						<view class="retry-btn" @click="retryLoad">
							<text class="retry-text">重新加载</text>
						</view>
					</view>
				</u-empty>
			</view>

			<!-- 加载状态 -->
			<view v-if="isLoading && collectList.length === 0" class="loading-state">
				<u-loading-icon mode="spinner" size="28"></u-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 加载更多状态 -->
			<view v-if="collectList.length > 0" class="load-more-state">
				<view v-if="isLoading" class="loading-more">
					<u-loading-icon mode="spinner" size="20"></u-loading-icon>
					<text class="loading-more-text">加载中...</text>
				</view>
				<view v-else-if="!hasMore" class="no-more">
					<text class="no-more-text">—— 已加载全部收藏 ——</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		productCollectList,
		productClearCollect
	} from '@/config/api.js';

	export default {
		data() {
			return {
				bgColor: '#ffffff',
				collectList: [], // 收藏商品列表
				searchKeyword: '', // 搜索关键词
				isLoading: false, // 是否正在加载
				isRefreshing: false, // 是否正在刷新
				hasMore: true, // 是否还有更多数据
				selectedItems: [], // 选中的商品ID列表
				networkError: false, // 网络错误状态
				params: {
					current: 1, // 当前页码
					size: 10, // 每页数量
					name: '' // 商品名称搜索
				}
			}
		},
		onLoad() {
			uni.showLoading({
				title: '加载中...'
			})
			this.getCollectList().finally(() => {
				uni.hideLoading()
			})
		},
		onShow() {
			// 页面显示时刷新数据
			this.refreshData()
		},
		onShareAppMessage() {
			return {
				title: '我的收藏',
				path: '/packageUser/pages/collect/index'
			}
		},
		onShareTimeline() {
			return {
				title: '我的收藏'
			}
		},
		computed: {
			// 是否全选
			isAllSelected() {
				return this.collectList.length > 0 && this.selectedItems.length === this.collectList.length
			}
		},
		methods: {
			// 获取收藏列表
			async getCollectList(isLoadMore = false) {
				if (this.isLoading) return

				this.isLoading = true
				this.networkError = false

				try {
					// 根据API定义，productCollectList是POST请求，需要传递参数
					const params = {
						current: this.params.current,
						size: this.params.size,
						name: this.params.name
					}

					const res = await productCollectList(params)

					if (res.code === 200) {
						// 处理返回的数据结构
						let newList = []
						if (res.data && res.data.records) {
							// 分页数据结构
							newList = res.data.records
						} else if (Array.isArray(res.data)) {
							// 直接数组结构
							newList = res.data
						} else if (res.data && Array.isArray(res.data.list)) {
							// 其他可能的数据结构
							newList = res.data.list
						}

						// 确保newList是数组
						if (!Array.isArray(newList)) {
							newList = []
						}

						if (isLoadMore) {
							this.collectList = [...this.collectList, ...newList]
						} else {
							this.collectList = newList
						}

						// 判断是否还有更多数据
						this.hasMore = newList.length === this.params.size
					} else {
						uni.showToast({
							title: res.msg || '获取收藏列表失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取收藏列表失败:', error)
					this.networkError = true
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
					this.isRefreshing = false
				}
			},

			// 搜索处理
			handleSearch() {
				this.params.name = this.searchKeyword
				this.params.current = 1
				this.hasMore = true
				this.selectedItems = [] // 清空选中状态
				this.getCollectList()
			},

			// 清除搜索
			handleClear() {
				this.searchKeyword = ''
				this.params.name = ''
				this.params.current = 1
				this.hasMore = true
				this.selectedItems = [] // 清空选中状态
				this.getCollectList()
			},

			// 取消收藏
			async cancelCollect(item, index) {
				uni.showModal({
					title: '提示',
					content: '确定要取消收藏这个商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const params = {
									productId: item.id
								}

								const result = await productClearCollect(params)

								if (result.code === 200) {
									// 从列表中移除
									this.collectList.splice(index, 1)

									uni.showToast({
										title: '已取消收藏',
										icon: 'success'
									})

									// 如果列表为空，刷新数据
									if (this.collectList.length === 0) {
										this.refreshData()
									}
								} else {
									uni.showToast({
										title: result.msg || '取消收藏失败',
										icon: 'none'
									})
								}
							} catch (error) {
								console.error('取消收藏失败:', error)
								uni.showToast({
									title: '网络错误，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			// 加载更多
			loadMore() {
				if (this.isLoading || !this.hasMore) return

				this.params.current++
				this.getCollectList(true)
			},

			// 下拉刷新
			async onRefresh() {
				this.isRefreshing = true
				this.params.current = 1
				this.hasMore = true
				await this.getCollectList()
			},

			// 刷新数据
			refreshData() {
				this.params.current = 1
				this.hasMore = true
				this.selectedItems = [] // 清空选中状态
				this.getCollectList()
			},

			// 跳转到商品详情
			goToDetail(productId) {
				uni.navigateTo({
					url: `/packageShop/pages/detail/index?id=${productId}`
				})
			},

			// 跳转到商城
			goToShop() {
				uni.switchTab({
					url: '/pages/shop/product-type-list'
				})
			},

			// 图片加载错误处理
			handleImageError() {
				// 可以设置默认图片
				console.log('图片加载失败')
			},

			// 重试加载
			retryLoad() {
				this.networkError = false
				this.refreshData()
			},

			// 切换选择状态
			toggleSelect(productId) {
				const index = this.selectedItems.indexOf(productId)
				if (index > -1) {
					this.selectedItems.splice(index, 1)
				} else {
					this.selectedItems.push(productId)
				}
			},

			// 全选/取消全选
			selectAll() {
				if (this.isAllSelected) {
					this.selectedItems = []
				} else {
					this.selectedItems = this.collectList.map(item => item.id)
				}
			},

			// 批量取消收藏
			async batchCancelCollect() {
				if (this.selectedItems.length === 0) {
					uni.showToast({
						title: '请选择要取消收藏的商品',
						icon: 'none'
					})
					return
				}

				uni.showModal({
					title: '提示',
					content: `确定要取消收藏选中的 ${this.selectedItems.length} 件商品吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '处理中...'
								})

								// 逐个取消收藏
								const promises = this.selectedItems.map(productId => {
									return productClearCollect({
										productId
									})
								})

								await Promise.all(promises)

								// 从列表中移除选中的商品
								this.collectList = this.collectList.filter(item =>
									!this.selectedItems.includes(item.id)
								)

								// 清空选中列表
								this.selectedItems = []

								uni.hideLoading()
								uni.showToast({
									title: '批量取消收藏成功',
									icon: 'success'
								})

								// 如果列表为空，刷新数据
								if (this.collectList.length === 0) {
									this.refreshData()
								}
							} catch (error) {
								uni.hideLoading()
								console.error('批量取消收藏失败:', error)
								uni.showToast({
									title: '批量操作失败，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.collect-page {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.search-section {
		padding: 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.search-container {
		background-color: #f8f8f8;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.batch-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-top: 1rpx solid #eee;
		margin-top: 20rpx;
	}

	.batch-info {
		flex: 1;
	}

	.batch-text {
		font-size: 26rpx;
		color: #666;
	}

	.batch-buttons {
		display: flex;
		gap: 20rpx;
	}

	.batch-btn {
		padding: 12rpx 24rpx;
		border-radius: 20rpx;
		background-color: #f0f0f0;
		transition: all 0.3s ease;
	}

	.batch-btn:active {
		transform: scale(0.95);
	}

	.batch-btn-text {
		font-size: 24rpx;
		color: #333;
	}

	.delete-btn {
		background-color: #FFE6E6;
	}

	.delete-btn .batch-btn-text {
		color: #FF4B4B;
	}

	.product-list {
		flex: 1;
		height: calc(100vh - 200rpx);
	}

	.product-container {
		padding: 20rpx;
	}

	.product-card {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		position: relative;
	}

	/* 移除商品卡片的选中状态样式，只保留选择框的选中状态 */

	.select-checkbox {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		z-index: 10;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		backdrop-filter: blur(10rpx);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
		border: 2rpx solid #ccc;
	}

	.select-checkbox:active {
		transform: scale(0.9);
	}

	.select-checkbox.selected {
		border-color: #FF4B4B;
		background-color: #FF4B4B;
	}

	.checkmark {
		color: #fff;
		font-size: 20rpx;
		font-weight: bold;
		line-height: 1;
	}

	.product-card:active {
		transform: scale(0.98);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.product-image-container {
		position: relative;
		width: 100%;
		height: 400rpx;
		overflow: hidden;
	}

	.product-image {
		width: 100%;
		height: 100%;
		transition: transform 0.3s ease;
	}

	.product-card:active .product-image {
		transform: scale(1.05);
	}

	.collect-btn {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		width: 60rpx;
		height: 60rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		backdrop-filter: blur(10rpx);
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.collect-btn:active {
		transform: scale(0.9);
		background-color: rgba(255, 255, 255, 1);
	}

	.product-info {
		padding: 24rpx;
	}

	.product-name {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
		line-height: 1.4;
		margin-bottom: 12rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.product-desc {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 16rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		line-height: 1.4;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.product-meta {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.rating-section {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.rating-text {
		font-size: 22rpx;
		color: #666;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.sales-info {
		text-align: right;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.sales-text {
		font-size: 22rpx;
		color: #999;
		white-space: nowrap;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.price-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.price-info {
		display: flex;
		align-items: baseline;
		gap: 4rpx;
	}

	.price-symbol {
		font-size: 24rpx;
		color: #FF4B4B;
		font-weight: 600;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.price-value {
		font-size: 36rpx;
		color: #FF4B4B;
		font-weight: 700;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.original-price {
		font-size: 24rpx;
		color: #999;
		text-decoration: line-through;
		margin-left: 8rpx;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.action-buttons {
		display: flex;
		gap: 12rpx;
	}

	.buy-btn {
		background: linear-gradient(135deg, #FF4B4B 0%, #FF6B6B 100%);
		border-radius: 20rpx;
		padding: 12rpx 24rpx;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 80rpx;
		height: 60rpx;
	}

	.buy-btn:active {
		transform: scale(0.95);
		background: linear-gradient(135deg, #E63939 0%, #E65959 100%);
	}

	.buy-text {
		color: #fff;
		font-size: 24rpx;
		font-weight: 600;
		white-space: nowrap;
		writing-mode: horizontal-tb;
		text-orientation: mixed;
	}

	.empty-state {
		padding: 100rpx 40rpx;
		text-align: center;
	}

	.empty-tips {
		margin-top: 30rpx;
	}

	.tips-text {
		font-size: 28rpx;
		color: #999;
		display: block;
		margin-bottom: 30rpx;
	}

	.go-shop-btn {
		background: linear-gradient(135deg, #FF4B4B 0%, #FF6B6B 100%);
		border-radius: 25rpx;
		padding: 16rpx 40rpx;
		display: inline-block;
		transition: all 0.3s ease;
	}

	.go-shop-btn:active {
		transform: scale(0.95);
	}

	.btn-text {
		color: #fff;
		font-size: 28rpx;
		font-weight: 600;
	}

	.error-state {
		padding: 100rpx 40rpx;
		text-align: center;
	}

	.error-tips {
		margin-top: 30rpx;
	}

	.error-text {
		font-size: 28rpx;
		color: #999;
		display: block;
		margin-bottom: 30rpx;
	}

	.retry-btn {
		background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
		border-radius: 25rpx;
		padding: 16rpx 40rpx;
		display: inline-block;
		transition: all 0.3s ease;
	}

	.retry-btn:active {
		transform: scale(0.95);
	}

	.retry-text {
		color: #fff;
		font-size: 28rpx;
		font-weight: 600;
	}

	.loading-state {
		padding: 100rpx 40rpx;
		text-align: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #999;
	}

	.load-more-state {
		padding: 40rpx 20rpx;
		text-align: center;
	}

	.loading-more {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
	}

	.loading-more-text {
		font-size: 24rpx;
		color: #999;
	}

	.no-more {
		text-align: center;
	}

	.no-more-text {
		font-size: 24rpx;
		color: #999;
		position: relative;
	}

	.no-more-text::before,
	.no-more-text::after {
		content: '';
		position: absolute;
		top: 50%;
		width: 60rpx;
		height: 1rpx;
		background-color: #ddd;
	}

	.no-more-text::before {
		left: -80rpx;
	}

	.no-more-text::after {
		right: -80rpx;
	}
</style>