<!-- 收藏页面 -->
<template>
	<view class="favorites-page">
		<view class="favorites-header">
			<view v-if="favorites.length > 0" class="header-actions">
				<text class="action-btn" @click="toggleEditMode">{{ isEditMode ? '完成' : '编辑' }}</text>
				<text class="action-btn" @click="clearAll">清空</text>
			</view>
		</view>

		<scroll-view class="favorites-content" :scroll-y="true">
			<view v-if="favorites.length === 0 && !isLoading" class="empty-favorites">
				<text class="empty-icon">❤️</text>
				<text class="empty-text">暂无收藏商品</text>
				<text class="empty-subtext">快去收藏喜欢的商品吧</text>
				<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
			</view>

			<view class="product-group">
				<view class="group-items">
					<view v-for="(product, index) in favorites" :key="index" class="product-item">
						<view v-if="isEditMode" class="item-selector" @click="toggleSelect(product)">
							<view :class="['select-icon', { selected: product.selected === true }]">
								<text v-if="product.selected === true" class="icon-text">✓</text>
							</view>
						</view>
						<view class="item-content" @click="viewProduct(product)">
							<image class="product-image" :src="product.main_image_url" mode="aspectFill" />
							<text class="product-name" :lines="2">{{ product.name }}</text>
							<view class="product-bottom">
								<text class="product-price">¥{{ product.price }}</text>
								<view v-if="!isEditMode" class="product-add-btn" @click.stop="addToCart(product)">
									<text class="add-icon">+</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view v-if="isLoading" class="loading-more">
				<text class="loading-text">加载中...</text>
			</view>
			<view v-if="!isLoading && favorites.length > 0" class="no-more">
				<text class="no-more-text">没有更多了</text>
			</view>
		</scroll-view>

		<view v-if="isEditMode && favorites.length > 0" class="edit-bar">
			<view class="select-all" @click="toggleSelectAll">
				<view :class="['all-select-icon', { selected: isAllSelected }]">
					<text v-if="isAllSelected" class="icon-text">✓</text>
				</view>
				<text class="select-all-text">全选</text>
			</view>
			<view class="delete-btn" @click="deleteSelected">
				<text class="delete-text">删除({{ selectedCount }})</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="uts">
import { ref, onMounted, computed } from 'vue'
import { supabaseService } from '@/utils/supabaseService.uts'

type FavoriteType = {
	id: string
	name: string
	price: number
	main_image_url: string
	merchant_id: string
	selected: boolean
}

const favorites = ref<FavoriteType[]>([])
const isEditMode = ref<boolean>(false)
const isLoading = ref<boolean>(false)

const selectedCount = computed((): number => {
	return favorites.value.filter((item): Boolean => item.selected === true).length
})

const isAllSelected = computed((): boolean => {
	return favorites.value.length > 0 && favorites.value.every((item): Boolean => item.selected === true)
})

const loadFavorites = async () => {
	isLoading.value = true
	try {
		const res = await supabaseService.getFavorites()
		console.log('收藏数据加载完成，数量:', res.length)
		
		const productList: FavoriteType[] = []
		for (let i = 0; i < res.length; i++) {
			const item = res[i]
			let prod: any | null = null
			let itemObj: UTSJSONObject | null = null
			
			if (item instanceof UTSJSONObject) {
				itemObj = item as UTSJSONObject
				prod = itemObj.get('ml_products')
			} else {
				itemObj = JSON.parse(JSON.stringify(item)) as UTSJSONObject
				prod = itemObj.get('ml_products')
			}
			
			let image = '/static/default-product.png'
			let id = ''
			let name = '未知商品'
			let price = 0
			let merchantId = ''
			
			if (prod != null) {
				let prodObj: UTSJSONObject
				if (prod instanceof UTSJSONObject) {
					prodObj = prod as UTSJSONObject
				} else {
					prodObj = JSON.parse(JSON.stringify(prod)) as UTSJSONObject
				}
				
				id = prodObj.getString('id') ?? ''
				name = prodObj.getString('name') ?? '未知商品'
				price = prodObj.getNumber('base_price') ?? 0
				image = prodObj.getString('main_image_url') ?? image
				merchantId = prodObj.getString('merchant_id') ?? ''
				
				if (image === '/static/default-product.png') {
					const imgUrls = prodObj.getString('image_urls')
					if (imgUrls != null) {
						try {
							const arr = JSON.parse(imgUrls)
							if (Array.isArray(arr) && arr.length > 0) {
								image = arr[0] as string
							}
						} catch(e) {}
					}
				}
			} else {
				if (itemObj != null) {
					id = itemObj.getString('target_id') ?? ''
				}
			}

			const product: FavoriteType = {
				id: id,
				name: name,
				price: price,
				main_image_url: image,
				merchant_id: merchantId,
				selected: false
			}
			productList.push(product)
		}
		favorites.value = productList
		console.log('收藏列表更新完成，数量:', favorites.value.length)
	} catch (e) {
		console.error('加载收藏失败', e)
	} finally {
		isLoading.value = false
	}
}

const toggleEditMode = () => {
	isEditMode.value = !isEditMode.value
	for (let i = 0; i < favorites.value.length; i++) {
		favorites.value[i].selected = false
	}
}

const clearAll = () => {
	if (favorites.value.length === 0) return

	uni.showModal({
		title: '清空收藏',
		content: '确定要清空所有收藏商品吗？',
		success: (res) => {
			if (res.confirm) {
				uni.showLoading({ title: '清空中...' })
				
				const productIds: string[] = []
				for (let i = 0; i < favorites.value.length; i++) {
					productIds.push(favorites.value[i].id)
				}
				
				let completed = 0
				
				for (let i = 0; i < productIds.length; i++) {
					supabaseService.toggleFavorite(productIds[i]).then(() => {
						completed++
						if (completed === productIds.length) {
							uni.hideLoading()
							favorites.value = []
							uni.showToast({
								title: '已清空',
								icon: 'success'
							})
						}
					}).catch(() => {
						completed++
						if (completed === productIds.length) {
							uni.hideLoading()
							loadFavorites()
							uni.showToast({
								title: '部分清空失败',
								icon: 'none'
							})
						}
					})
				}
			}
		}
	})
}

const toggleSelect = (item: FavoriteType) => {
	item.selected = !(item.selected === true)
	favorites.value = [...favorites.value]
}

const toggleSelectAll = () => {
	const newSelectedState = !isAllSelected.value
	for (let i = 0; i < favorites.value.length; i++) {
		favorites.value[i].selected = newSelectedState
	}
	favorites.value = [...favorites.value]
}

const deleteSelected = () => {
	const selectedItems = favorites.value.filter((item): Boolean => item.selected === true)
	if (selectedItems.length === 0) {
		uni.showToast({
			title: '请选择要删除的商品',
			icon: 'none'
		})
		return
	}

	uni.showModal({
		title: '删除收藏',
		content: `确定要删除选中的 ${selectedItems.length} 个商品吗？`,
		success: (res) => {
			if (res.confirm) {
				uni.showLoading({ title: '删除中...' })
				
				let completed = 0
				const total = selectedItems.length
				
				for (let i = 0; i < selectedItems.length; i++) {
					supabaseService.toggleFavorite(selectedItems[i].id).then(() => {
						completed++
						if (completed === total) {
							uni.hideLoading()
							loadFavorites()
							uni.showToast({
								title: '已删除',
								icon: 'success'
							})
						}
					}).catch(() => {
						completed++
						if (completed === total) {
							uni.hideLoading()
							loadFavorites()
							uni.showToast({
								title: '部分删除失败',
								icon: 'none'
							})
						}
					})
				}
			}
		}
	})
}

const viewProduct = (product: FavoriteType) => {
	if (isEditMode.value) {
		toggleSelect(product)
		return
	}
	uni.navigateTo({
		url: `/pages/mall/consumer/product-detail?id=${product.id}`
	})
}

const addToCart = async (product: FavoriteType) => {
	uni.showLoading({ title: '检查商品...' })
	try {
		const merchantId = product.merchant_id ?? ''
		
		const skus = await supabaseService.getProductSkus(product.id)
		uni.hideLoading()
		
		if (skus.length > 0) {
			uni.showToast({ title: '请选择规格', icon: 'none' })
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/mall/consumer/product-detail?id=' + product.id
				})
			}, 500)
		} else {
			uni.showLoading({ title: '添加中...' })
			const success = await supabaseService.addToCart(product.id, 1, '', merchantId)
			uni.hideLoading()
			if (success) {
				uni.showToast({ title: '已添加到购物车', icon: 'success' })
			} else {
				uni.showToast({ title: '添加失败', icon: 'none' })
			}
		}
	} catch (e) {
		console.error('添加到购物车异常', e)
		uni.hideLoading()
		uni.showToast({ title: '操作失败', icon: 'none' })
	}
}

const goShopping = () => {
	uni.switchTab({
		url: '/pages/main/index'
	})
}

onMounted(() => {
	loadFavorites()
})
</script>

<style scoped>
.favorites-page {
	display: flex;
	flex-direction: column;
	flex: 1;
}

.favorites-header {
	background-color: #ffffff;
	padding: 15px;
	border-bottom: 1px solid #e5e5e5;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.header-actions {
	display: flex;
	flex-direction: row;
	flex: 1;
	justify-content: flex-end;
	align-items: center;
	padding-right: 0;
}

.action-btn {
	color: #007aff;
	font-size: 14px;
	padding: 5px;
	margin-left: 20px;
}

.favorites-content {
	flex: 1;
	height: 0px;
}

.empty-favorites {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px 20px;
	background-color: #ffffff;
}

.empty-icon {
	font-size: 80px;
	margin-bottom: 20px;
}

.empty-text {
	font-size: 16px;
	color: #666666;
	margin-bottom: 10px;
}

.empty-subtext {
	font-size: 14px;
	color: #999999;
	margin-bottom: 30px;
}

.go-shopping-btn {
	background-color: #007aff;
	color: #ffffff;
	padding: 10px 40px;
	border-radius: 25px;
	font-size: 14px;
	border: none;
}

.product-group {
	background-color: #ffffff;
	margin-bottom: 10px;
	padding: 0 10px;
}

.group-items {
	padding: 0;
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	justify-content: space-between;
}

.product-item {
	display: flex;
	flex-direction: column;
	background: #fff;
	border-radius: 8px;
	overflow: hidden;
	width: 48%;
	margin-bottom: 12px;
	position: relative;
}

.item-selector {
	position: absolute;
	top: 5px;
	right: 5px;
	z-index: 10;
	width: 30px;
	height: 30px;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.select-icon {
	width: 20px;
	height: 20px;
	border: 1px solid #cccccc;
	border-radius: 10px;
	background-color: rgba(255,255,255,0.5);
	display: flex;
	align-items: center;
	justify-content: center;
}

.select-icon.selected {
	background-color: #007aff;
	border-color: #007aff;
}

.icon-text {
	color: #ffffff;
	font-size: 12px;
}

.item-content {
	display: flex;
	flex-direction: column;
}

.product-image {
	width: 100%;
	height: 170px;
	border-radius: 8px;
	margin-bottom: 8px;
	background: #f5f5f5;
}

.product-name {
	font-size: 13px;
	color: #333;
	margin-bottom: 5px;
	line-height: 1.4;
	height: 36px;
	overflow: hidden;
	text-overflow: ellipsis;
	padding: 0 8px;
}

.product-bottom {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	padding: 0 8px 8px;
}

.product-price {
	font-size: 15px;
	color: #ff5000;
	font-weight: bold;
}

.product-add-btn {
	width: 24px;
	height: 24px;
	background-color: #ff5000;
	border-radius: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.add-icon {
	color: #fff;
	font-size: 16px;
	font-weight: bold;
}

@media (min-width: 768px) {
	.product-item {
		width: 32% !important;
	}
}

@media (min-width: 1024px) {
	.product-item {
		width: 16% !important;
	}
	
	.favorites-content, .favorites-header {
		max-width: 1200px;
		margin: 0 auto;
	}
}

.loading-more,
.no-more {
	padding: 20px;
	text-align: center;
	background-color: #ffffff;
}

.loading-text,
.no-more-text {
	color: #999999;
	font-size: 14px;
}

.edit-bar {
	background-color: #ffffff;
	border-top: 1px solid #e5e5e5;
	padding: 15px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.select-all {
	display: flex;
	align-items: center;
}

.all-select-icon {
	width: 20px;
	height: 20px;
	border: 1px solid #cccccc;
	border-radius: 10px;
	margin-right: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.all-select-icon.selected {
	background-color: #007aff;
	border-color: #007aff;
}

.select-all-text {
	font-size: 14px;
	color: #333333;
}

.delete-btn {
	background-color: #ff4757;
	padding: 10px 20px;
	border-radius: 15px;
}

.delete-text {
	color: #ffffff;
	font-size: 14px;
	font-weight: bold;
}
</style>
