<!-- 足迹页面 -->
<template>
	<view class="footprint-page">
		<!-- 顶部栏 -->
		<view class="footprint-header">
			<view class="header-title">
				<text class="title-text">我的足迹</text>
			</view>
			<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 @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, date) in groupedFootprints" :key="date" class="date-group">
				<view class="group-header">
					<text class="group-date">{{ formatGroupDate(date) }}</text>
					<text v-if="isEditMode" class="group-select" @click="toggleGroupSelect(date)">
						{{ isGroupSelected(date) ? '取消全选' : '全选' }}
					</text>
				</view>
				
				<view class="group-items">
					<view v-for="item in group" :key="item.id" class="footprint-item">
						<view v-if="isEditMode" class="item-selector" @click="toggleSelect(item)">
							<view :class="['select-icon', { selected: item.selected }]">
								<text v-if="item.selected" class="icon-text">✓</text>
							</view>
						</view>
						<view class="item-content" @click="viewProduct(item)">
							<image class="product-image" :src="item.image" />
							<view class="product-info">
								<text class="product-name">{{ item.name }}</text>
								<view class="product-price-row">
									<text class="current-price">¥{{ item.price }}</text>
									<text v-if="item.original_price && item.original_price > item.price" 
												class="original-price">¥{{ item.original_price }}</text>
								</view>
								<view class="product-meta">
									<text class="sales-text">已售{{ item.sales }}</text>
									<text class="time-text">{{ formatTime(item.viewTime) }}</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'

type FootprintType = {
	id: string
	name: string
	price: number
	original_price?: number
	image: string
	sales: number
	shopId: string
	shopName: string
	viewTime: number
	selected?: boolean
}

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

// 计算属性
const selectedCount = computed(() => {
	return footprints.value.filter(item => item.selected).length
})

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

const groupedFootprints = computed(() => {
	const groups: Record<string, FootprintType[]> = {}
	
	footprints.value.forEach(item => {
		const date = new Date(item.viewTime).toDateString()
		if (!groups[date]) {
			groups[date] = []
		}
		groups[date].push(item)
	})
	
	return groups
})

// 生命周期
onMounted(() => {
	loadFootprints()
})

// 加载足迹数据
const loadFootprints = (loadMore: boolean = false) => {
	isLoading.value = true
	
	// 从本地存储获取足迹数据
	const storedFootprints = uni.getStorageSync('footprints')
	if (storedFootprints) {
		try {
			const data = JSON.parse(storedFootprints as string) as any[]
			footprints.value = data.map(item => ({
				...item,
				selected: false
			}))
		} catch (e) {
			console.error('Failed to parse footprints', e)
			footprints.value = []
		}
	} else {
		footprints.value = []
	}
	
	isLoading.value = false
	hasMore.value = false // 本地存储一次性加载完
}

// 格式化日期分组
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 formatTime = (timestamp: number): string => {
	const date = new Date(timestamp)
	const hours = date.getHours().toString().padStart(2, '0')
	const minutes = date.getMinutes().toString().padStart(2, '0')
	return `${hours}:${minutes}`
}

// 切换编辑模式
const toggleEditMode = () => {
	isEditMode.value = !isEditMode.value
	// 重置选择状态
	footprints.value.forEach(item => {
		item.selected = false
	})
}

// 清空所有足迹
const clearAll = () => {
	if (footprints.value.length === 0) return

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

// 切换选择状态
const toggleSelect = (item: FootprintType) => {
	item.selected = !item.selected
	footprints.value = [...footprints.value]
}

// 切换分组全选
const toggleGroupSelect = (dateStr: string) => {
	const group = groupedFootprints.value[dateStr]
	if (!group) return
	
	const isAllSelected = group.every(item => item.selected)
	const newSelectedState = !isAllSelected
	
	group.forEach(item => {
		item.selected = newSelectedState
	})
	
	footprints.value = [...footprints.value]
}

// 检查组是否全选
const isGroupSelected = (dateStr: string): boolean => {
	const group = groupedFootprints.value[dateStr]
	if (!group || group.length === 0) return false
	return group.every(item => item.selected)
}

// 全选/取消全选
const toggleSelectAll = () => {
	const newSelectedState = !isAllSelected.value
	footprints.value.forEach(item => {
		item.selected = newSelectedState
	})
	footprints.value = [...footprints.value]
}

// 删除选中项
const deleteSelected = () => {
	const selectedItems = footprints.value.filter(item => item.selected)
	if (selectedItems.length === 0) {
		uni.showToast({
			title: '请选择要删除的记录',
			icon: 'none'
		})
		return
	}

	uni.showModal({
		title: '确认删除',
		content: `确定要删除选中的${selectedItems.length}条记录吗？`,
		success: (res) => {
			if (res.confirm) {
				// 从列表中移除
				footprints.value = footprints.value.filter(item => !item.selected)
				
				// 保存回本地存储
				const dataToSave = footprints.value.map(item => {
					const { selected, ...rest } = item
					return rest
				})
				uni.setStorageSync('footprints', JSON.stringify(dataToSave))
				
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				
				// 如果删完了，退出编辑模式
				if (footprints.value.length === 0) {
					isEditMode.value = false
				}
			}
		}
	})
}

// 查看商品
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/mall/consumer/index'
	})
}
</script>

<style scoped>
.footprint-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

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

.header-title {
	flex: 1;
}

.title-text {
	font-size: 18px;
	font-weight: bold;
	color: #333333;
}

.header-actions {
	display: flex;
	gap: 20px;
}

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

.footprint-content {
	flex: 1;
}

.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 15px;
}

.group-header {
	padding: 15px 0;
	border-bottom: 1px solid #f5f5f5;
	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: 10px 0;
}

.footprint-item {
	display: flex;
	padding: 15px 0;
	border-bottom: 1px solid #f5f5f5;
}

.footprint-item:last-child {
	border-bottom: none;
}

.item-selector {
	width: 50px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.select-icon {
	width: 20px;
	height: 20px;
	border: 1px solid #cccccc;
	border-radius: 10px;
	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 {
	flex: 1;
	display: flex;
}

.product-image {
	width: 80px;
	height: 80px;
	border-radius: 5px;
	margin-right: 15px;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 14px;
	color: #333333;
	line-height: 1.4;
	margin-bottom: 10px;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.product-price-row {
	display: flex;
	align-items: baseline;
	margin-bottom: 10px;
}

.current-price {
	font-size: 16px;
	color: #ff4757;
	font-weight: bold;
	margin-right: 10px;
}

.original-price {
	font-size: 12px;
	color: #999999;
	text-decoration: line-through;
}

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

.sales-text {
	font-size: 12px;
	color: #999999;
}

.time-text {
	font-size: 12px;
	color: #666666;
}

.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>