<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<text class="header-title">分类</text>
			<view class="placeholder"></view>
		</view>
		
		<!-- 分隔线 -->
		<view class="divider"></view>
		
		<!-- 分类列表 -->
		<scroll-view class="scroll-content" scroll-y>
			<!-- 加载中 -->
			<view class="loading-container" v-if="isLoading">
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 分类列表 -->
			<view class="category-grid" v-else-if="categoryList.length > 0">
				<view 
					class="category-card" 
					v-for="(category, index) in categoryList" 
					:key="category.id"
					@click="goToCategoryBooks(category)"
					:class="{ 'card-pressed': pressedIndex === index }"
					@touchstart="handleTouchStart(index)"
					@touchend="handleTouchEnd"
				>
					<image 
						class="category-cover" 
						:src="category.cover" 
						mode="aspectFill"
						:lazy-load="true"
						@error="handleImageError(index)"
					></image>
					<view class="category-info">
						<text class="category-title">{{ category.name }}</text>
						<text class="category-count">{{ category.count }}本书</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-container" v-else>
				<text class="empty-text">暂无分类数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { getAllCategories } from '../../utils/api.js'
	
	export default {
		data() {
			return {
				pressedIndex: -1,
				categoryList: [],
				isLoading: false
			}
		},
		onLoad() {
			// 页面加载时获取分类数据
			this.loadCategories();
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			handleTouchStart(index) {
				this.pressedIndex = index;
			},
			handleTouchEnd() {
				setTimeout(() => {
					this.pressedIndex = -1;
				}, 150);
			},
			goToCategoryBooks(category) {
				// 根据分类名称判断跳转类型
				const categoryName = category.name;
				
				// 特殊分类：跳转到对应的特殊页面
				if (categoryName === '全部分类') {
					uni.navigateTo({
						url: '/pages/more-books/more-books?type=all'
					});
				} else if (categoryName === '排行榜') {
					uni.navigateTo({
						url: '/pages/more-books/more-books?type=ranking'
					});
				} else if (categoryName === '热门书籍') {
					uni.navigateTo({
						url: '/pages/more-books/more-books?type=popular'
					});
				} else if (categoryName === '新书榜') {
					uni.navigateTo({
						url: '/pages/more-books/more-books?type=new'
					});
				} else if (categoryName === 'VIP书籍') {
					uni.navigateTo({
						url: '/pages/more-books/more-books?type=vip'
					});
				} else {
					// 普通分类：跳转到该分类的书籍列表页面
					uni.navigateTo({
						url: `/pages/more-books/more-books?type=category&categoryId=${category.id}&categoryName=${encodeURIComponent(category.name)}`
					});
				}
			},
			handleImageError(index) {
				// 图片加载失败时使用备用图片
				if (this.categoryList[index]) {
					this.categoryList[index].cover = `https://picsum.photos/seed/fallback${index}/200/300`;
				}
			},
			loadCategories() {
				console.log('开始加载分类列表...');
				this.isLoading = true;
				
				getAllCategories()
					.then((res) => {
						console.log('分类列表API响应:', res);
						this.isLoading = false;
						
						if (res && res.code === 200) {
							if (res.data && Array.isArray(res.data)) {
								// 处理数据格式
								this.categoryList = res.data.map((category) => {
									return {
										id: category.id,
										name: category.name || '未知分类',
										count: category.bookCount || 0,
										cover: category.cover || `https://picsum.photos/seed/category${category.id}/200/300`,
										icon: category.icon,
										color: category.color
									};
								});
								console.log('分类列表加载成功，共', this.categoryList.length, '个分类');
							} else {
								console.warn('分类列表数据为空或格式不正确:', res.data);
								this.categoryList = [];
								uni.showToast({
									title: '暂无分类数据',
									icon: 'none',
									duration: 2000
								});
							}
						} else {
							console.warn('分类列表API返回错误:', res);
							this.categoryList = [];
							uni.showToast({
								title: res.message || '获取分类列表失败',
								icon: 'none',
								duration: 2000
							});
						}
					})
					.catch((err) => {
						this.isLoading = false;
						console.error('获取分类列表失败:', err);
						this.categoryList = [];
						uni.showToast({
							title: err.message || '网络请求失败，请检查后端服务',
							icon: 'none',
							duration: 3000
						});
					});
			}
		}
	}
</script>

<style scoped>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
	}
	
	/* 顶部导航栏 */
	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		position: relative;
	}
	
	.back-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.back-icon {
		font-size: 40rpx;
		color: #000000;
		font-weight: bold;
	}
	
	.header-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #000000;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}
	
	.placeholder {
		width: 60rpx;
	}
	
	/* 分隔线 */
	.divider {
		width: 100%;
		height: 1rpx;
		background-color: #E5E5E5;
	}
	
	/* 滚动内容 */
	.scroll-content {
		flex: 1;
		width: 100%;
		height: 0;
		overflow: hidden;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}
	
	/* 分类网格 */
	.category-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
	
	/* 分类卡片 */
	.category-card {
		width: calc(50% - 10rpx);
		height: 200rpx;
		background-color: #F5F5F5;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		padding: 20rpx;
		box-sizing: border-box;
		transition: all 0.15s ease;
		overflow: hidden;
		position: relative;
	}
	
	.category-card:active,
	.category-card.card-pressed {
		transform: scale(0.98);
		background-color: #EEEEEE;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}
	
	/* 分类封面 */
	.category-cover {
		width: 100rpx;
		height: 140rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
		background-color: #E0E0E0;
	}
	
	/* 分类信息 */
	.category-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		min-width: 0;
	}
	
	.category-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #000000;
		margin-bottom: 12rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.category-count {
		font-size: 24rpx;
		color: #999999;
	}
	
	/* 加载中 */
	.loading-container {
		width: 100%;
		height: 400rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #999999;
	}
	
	/* 空状态 */
	.empty-container {
		width: 100%;
		height: 400rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
</style>
