<!-- 足迹页面 -->
<template>
	<view class="footprint-page">
		<view class="footprint-header">
			<view v-if="footprints.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="footprint-content" :scroll-y="true" @scrolltolower="loadMore">
			<view v-if="footprints.length === 0 && !isLoading" class="empty-footprints">
				<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 v-for="(group, index) in groupedFootprints" :key="index" class="date-group">
				<view class="group-header">
					<text class="group-date">{{ group.dateLabel }}</text>
					<text v-if="isEditMode" class="group-select" @click="toggleGroupSelect(index)">
						{{ isGroupSelected(index) ? '取消全选' : '全选' }}
					</text>
				</view>
				
				<view class="group-items">
					<view v-for="item in group.items" :key="item.id" class="footprint-item">
						<view v-if="isEditMode" class="item-selector" @click="toggleSelect(item)">
							<view :class="['select-icon', { selected: item.selected === true }]">
								<text v-if="item.selected === true" class="icon-text">✓</text>
							</view>
						</view>
						<view class="item-content" @click="viewProduct(item)">
							<image class="product-image" :src="item.image" mode="aspectFill" />
							<text class="product-name" :lines="2">{{ item.name }}</text>
							<view class="product-bottom">
								<text class="product-price">¥{{ item.price }}</text>
								<view class="product-add-btn" @click.stop="addToCart(item)">
									<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="!hasMore && footprints.length > 0" class="no-more">
				<text class="no-more-text">没有更多了</text>
			</view>
		</scroll-view>

		<view v-if="isEditMode && footprints.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 FootprintType = {
	id: string
	name: string
	price: number
	original_price: number
	image: string
	sales: number
	shopId: string
	shopName: string
	viewTime: number
	selected: boolean
	merchant_id: string
}

type FootprintGroup = {
	dateLabel: string
	dateKey: string
	items: FootprintType[]
}

type FootprintSaveType = {
	id: string
	name: string
	price: number
	original_price: number
	image: string
	sales: number
	shopId: string
	shopName: string
	viewTime: number
}

const footprints = ref<FootprintType[]>([])
const isEditMode = ref<boolean>(false)
const isLoading = ref<boolean>(false)
const hasMore = ref<boolean>(false)

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

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

const formatGroupDate = (dateStr: string): string => {
	const date = new Date(dateStr)
	const today = new Date()
	const yesterday = new Date(today)
	yesterday.setDate(yesterday.getDate() - 1)
	
	if (date.toDateString() === today.toDateString()) {
		return '今天'
	} else if (date.toDateString() === yesterday.toDateString()) {
		return '昨天'
	} else {
		const month = date.getMonth() + 1
		const day = date.getDate()
		return `${month}月${day}日`
	}
}

const groupedFootprints = computed((): FootprintGroup[] => {
	const result: FootprintGroup[] = []
	
	for (let i = 0; i < footprints.value.length; i++) {
		const item = footprints.value[i]
		const dateKey = new Date(item.viewTime).toDateString()
		
		let foundGroup: FootprintGroup | null = null
		for (let j = 0; j < result.length; j++) {
			if (result[j].dateKey === dateKey) {
				foundGroup = result[j]
				break
			}
		}
		
		if (foundGroup != null) {
			foundGroup.items.push(item)
		} else {
			const newGroup: FootprintGroup = {
				dateLabel: formatGroupDate(dateKey),
				dateKey: dateKey,
				items: [item]
			} as FootprintGroup
			result.push(newGroup)
		}
	}
	
	return result
})

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

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

	uni.showModal({
		title: '清空足迹',
		content: '确定要清空所有浏览记录吗？',
		success: (res) => {
			if (res.confirm) {
				uni.showLoading({ title: '清空中...' })
				
				supabaseService.clearFootprints().then((success) => {
					uni.hideLoading()
					
					if (success) {
						footprints.value = []
						uni.removeStorageSync('footprints')
						
						uni.showToast({
							title: '已清空',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: '清空失败',
							icon: 'none'
						})
					}
				})
			}
		}
	})
}

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

const toggleGroupSelect = (groupIndex: number) => {
	const group = groupedFootprints.value[groupIndex]
	if (group == null) return
	
	const allSelected = group.items.every((item): Boolean => item.selected === true)
	const newSelectedState = !allSelected
	
	for (let i = 0; i < group.items.length; i++) {
		group.items[i].selected = newSelectedState
	}
	
	footprints.value = [...footprints.value]
}

const isGroupSelected = (groupIndex: number): boolean => {
	const group = groupedFootprints.value[groupIndex]
	if (group == null || group.items.length === 0) return false
	return group.items.every((item): Boolean => item.selected === true)
}

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

const deleteSelected = () => {
	const selectedItems = footprints.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: '删除中...' })
				
				// 收集要删除的商品ID
				const productIds: string[] = []
				for (let i = 0; i < selectedItems.length; i++) {
					productIds.push(selectedItems[i].id)
				}
				
				// 调用服务层批量删除
				supabaseService.deleteFootprints(productIds).then((success) => {
					uni.hideLoading()
					
					if (success) {
						// 从本地列表中移除
						footprints.value = footprints.value.filter((item): Boolean => item.selected !== true)
						
						// 更新本地缓存
						const dataToSave: FootprintSaveType[] = []
						for (let i = 0; i < footprints.value.length; i++) {
							const item = footprints.value[i]
							dataToSave.push({
								id: item.id,
								name: item.name,
								price: item.price,
								original_price: item.original_price,
								image: item.image,
								sales: item.sales,
								shopId: item.shopId,
								shopName: item.shopName,
								viewTime: item.viewTime
							} as FootprintSaveType)
						}
						uni.setStorageSync('footprints', JSON.stringify(dataToSave))
						
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						
						if (footprints.value.length === 0) {
							isEditMode.value = false
						}
					} else {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					}
				})
			}
		}
	})
}

const addToCart = async (item: FootprintType) => {
	uni.showLoading({ title: '检查商品...' })
	try {
		const productId = item.id
		const merchantId = item.merchant_id ?? item.shopId ?? ''
		
		// 检查商品是否有SKU
		const skus = await supabaseService.getProductSkus(productId)
		uni.hideLoading()
		
		if (skus.length > 0) {
			// 有规格，提示并跳转到商品详情页选择规格
			uni.showToast({
				title: '请选择规格',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/mall/consumer/product-detail?id=' + productId
				})
			}, 500)
		} else {
			// 无规格，直接加入购物车
			uni.showLoading({ title: '添加中...' })
			const success = await supabaseService.addToCart(productId, 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 viewProduct = (item: FootprintType) => {
	if (isEditMode.value) return
	
	uni.navigateTo({
		url: `/pages/mall/consumer/product-detail?productId=${item.id}&price=${item.price}&originalPrice=${item.original_price}`
	})
}

const loadMore = () => {
}

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

const parseFootprintItem = (item: any): FootprintType => {
	let itemObj: UTSJSONObject
	if (item instanceof UTSJSONObject) {
		itemObj = item as UTSJSONObject
	} else {
		itemObj = JSON.parse(JSON.stringify(item)) as UTSJSONObject
	}
	
	return {
		id: itemObj.getString('id') ?? '',
		name: itemObj.getString('name') ?? '',
		price: itemObj.getNumber('price') ?? 0,
		original_price: itemObj.getNumber('original_price') ?? 0,
		image: itemObj.getString('image') ?? '',
		sales: itemObj.getNumber('sales') ?? 0,
		shopId: itemObj.getString('shopId') ?? '',
		shopName: itemObj.getString('shopName') ?? '',
		viewTime: itemObj.getNumber('viewTime') ?? 0,
		selected: false,
		merchant_id: itemObj.getString('merchant_id') ?? ''
	} as FootprintType
}

const loadFootprints = async () => {
	isLoading.value = true
	
	try {
		const remoteData = await supabaseService.getFootprints()
		
		if (remoteData.length > 0) {
			console.log('获取到远程足迹数据:', remoteData.length)
			const newFootprints: FootprintType[] = []
			for (let i = 0; i < remoteData.length; i++) {
				newFootprints.push(parseFootprintItem(remoteData[i]))
			}
			footprints.value = newFootprints
			
			const dataToSave: FootprintSaveType[] = []
			for (let i = 0; i < footprints.value.length; i++) {
				const item = footprints.value[i]
				dataToSave.push({
					id: item.id,
					name: item.name,
					price: item.price,
					original_price: item.original_price,
					image: item.image,
					sales: item.sales,
					shopId: item.shopId,
					shopName: item.shopName,
					viewTime: item.viewTime
				} as FootprintSaveType)
			}
			uni.setStorageSync('footprints', JSON.stringify(dataToSave))
		} else {
			const storedFootprints = uni.getStorageSync('footprints')
			if (storedFootprints != null) {
				try {
					const data = JSON.parse(storedFootprints as string) as any[]
					const newFootprints: FootprintType[] = []
					for (let i = 0; i < data.length; i++) {
						newFootprints.push(parseFootprintItem(data[i]))
					}
					footprints.value = newFootprints
				} catch (e) {
					console.error('Failed to parse footprints', e)
					footprints.value = []
				}
			} else {
				footprints.value = []
			}
		}
	} catch (e) {
		console.error('加载足迹失败', e)
		const storedFootprints = uni.getStorageSync('footprints')
		if (storedFootprints != null) {
			try {
				const data = JSON.parse(storedFootprints as string) as any[]
				const newFootprints: FootprintType[] = []
				for (let i = 0; i < data.length; i++) {
					newFootprints.push(parseFootprintItem(data[i]))
				}
				footprints.value = newFootprints
			} catch (err) {
				footprints.value = []
			}
		}
	}
	
	isLoading.value = false
	hasMore.value = false
}

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

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

.footprint-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;
}

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

.empty-footprints {
	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;
}

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

.group-header {
	padding: 15px 5px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.group-date {
	font-size: 16px;
	font-weight: bold;
	color: #333333;
}

.group-select {
	color: #007aff;
	font-size: 14px;
}

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

.footprint-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) {
	.footprint-item {
		width: 32% !important;
	}
}

@media (min-width: 1024px) {
	.footprint-item {
		width: 16% !important;
	}
	
	.footprint-content, .footprint-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>

