<template>
    <div class="category-container">
        <!-- 分类标题区 -->
        <div class="category-header">
            <div class="category-title">
                <h1>{{ categoryName }}</h1>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- 左侧分类导航 -->
            <div class="category-sidebar" v-if="!hasRouteId">
                <ul class="category-nav">
                    <li v-for="(name, id) in categoryMap" :key="id" :class="{ active: id === currentCategoryId }"
                        @click="switchCategory(id)">
                        {{ name }}
                    </li>
                </ul>
            </div>

            <!-- 右侧书籍列表 -->
            <div class="book-content" :class="{ 'full-width': hasRouteId }">
                <!-- 加载状态 -->
                <div v-if="loading" class="loading-container">
                    <el-skeleton :rows="8" animated />
                </div>
                
                <!-- 书籍列表 -->
                <div v-else-if="books.length > 0" class="book-list-container">
                    <div v-for="(book, index) in books" :key="index" class="book-item">
                        <book-card :book="book" />
                    </div>
                </div>

                <!-- 空状态 -->
                <div v-else class="empty-state">
                    <div class="empty-icon">
                        <svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect x="15" y="20" width="50" height="40" rx="4" stroke="#E5E5E5" stroke-width="2" fill="none"/>
                            <rect x="20" y="25" width="40" height="2" rx="1" fill="#E5E5E5"/>
                            <rect x="20" y="30" width="25" height="2" rx="1" fill="#E5E5E5"/>
                            <rect x="20" y="35" width="30" height="2" rx="1" fill="#E5E5E5"/>
                            <rect x="20" y="40" width="20" height="2" rx="1" fill="#E5E5E5"/>
                            <rect x="20" y="45" width="35" height="2" rx="1" fill="#E5E5E5"/>
                            <rect x="20" y="50" width="22" height="2" rx="1" fill="#E5E5E5"/>
                        </svg>
                    </div>
                    <p class="empty-title">暂无书籍</p>
                    <p class="empty-desc">该分类下暂时没有可阅读的书籍</p>
                </div>

                <!-- 分页 -->
                <div v-if="!loading && books.length > 0" class="pagination-container">
                    <el-pagination v-model:current-page="currentPage" 
                    background
                    :page-size="pageSize" :total="total"
                        layout="prev, pager, next" @current-change="handlePageChange" />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useMainStore } from '@/store';
import { homeApi } from '@/api/modules.js';
import BookCard from '@/components/common/BookCard.vue';

export default {
    name: 'CategoryView',
    components: {
        BookCard
    },
    setup() {
        const route = useRoute();
        const router = useRouter();
        const store = useMainStore();
        
        const categoryId = computed(() => route.params.id);
        const currentCategoryId = ref(categoryId.value || '1');

        // 计算是否有路由ID参数
        const hasRouteId = computed(() => !!categoryId.value);

        // 分页相关
        const currentPage = ref(1);
        const pageSize = ref(20);
        const total = ref(0);
        const loading = ref(false);

        // 响应式数据
        const books = ref([]);

        // 获取分类列表
        const categoryMap = computed(() => {
            const map = {};
            store.allCategories.forEach(category => {
                map[category.id] = category.title;
            });
            return map;
        });

        // 计算当前分类名称
        const categoryName = computed(() => {
            const category = store.allCategories.find(cat => cat.id === currentCategoryId.value);
            return category?.title || '分类';
        });

        // 获取书籍列表
        const fetchBooks = async () => {
            loading.value = true;
            try {
                // 这里可以根据需要调用不同的API
                // 暂时使用推荐列表API作为示例，实际应该有分类专用的API
                const response = await homeApi.getRecommendList({
                    pageNo: currentPage.value,
                    pageSize: pageSize.value,
                    shopClass: currentCategoryId.value
                });
                if (response.success && response.result) {
                    books.value = response.result.records
                    total.value = response.result.total;
                }
            } catch (error) {
                console.error('获取书籍列表失败:', error);
                books.value = [];
            } finally {
                loading.value = false;
            }
        };

        // 切换分类
        const switchCategory = (id) => {
            currentCategoryId.value = id;
            currentPage.value = 1;
            fetchBooks();
        };

        const handlePageChange = (page) => {
            currentPage.value = page;
            fetchBooks();
        };

        // 监听分类ID变化
        watch(
            () => route.params.id,
            (newId) => {
                if (newId) {
                    currentCategoryId.value = newId;
                    currentPage.value = 1;
                    fetchBooks();
                }
            },
            { immediate: false }
        );

        onMounted(async () => {
            // 确保分类数据已加载
            await store.fetchCategories();
            
            if (categoryId.value) {
                currentCategoryId.value = categoryId.value;
            }

            if(currentCategoryId.value == 1){
                currentCategoryId.value = store.allCategories[0].id;
            }
            
            // 获取书籍列表
            fetchBooks();
        });

        return {
            categoryName,
            categoryMap,
            books,
            loading,
            currentPage,
            pageSize,
            total,
            handlePageChange,
            currentCategoryId,
            switchCategory,
            hasRouteId
        };
    }
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as vars;

.category-container {
    width: 100%;
    background-color: #fff;
}

.category-header {
    margin-bottom: 20px;
    padding: 20px;
    border-bottom: 2px solid vars.$primary-color;

    .category-title {
        padding: 10px 0;

        h1 {
            font-size: 20px;
            font-weight: bold;
            color: vars.$primary-color;
            position: relative;
            padding-left: 15px;

            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 4px;
                height: 18px;
                background-color: vars.$primary-color;
            }
        }
    }
}

.content-wrapper {
    display: flex;
    gap: 20px;
}

// 左侧分类导航
.category-sidebar {
    width: 120px;
    flex-shrink: 0;
    background-color: #f8f8f8;
    border-radius: 4px;

    .category-nav {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
            padding: 12px 15px;
            font-size: 14px;
            cursor: pointer;
            border-left: 3px solid transparent;
            transition: all 0.3s;

            &:hover {
                background-color: #f0f0f0;
                color: vars.$primary-color;
            }

            &.active {
                background-color: #e8f1ff;
                color: vars.$primary-color;
                border-left-color: vars.$primary-color;
                font-weight: bold;
            }
        }
    }
}

// 右侧内容区
.book-content {
    flex: 1;
    min-width: 0;
    padding: 20px;

    &.full-width {
        width: 100%;
    }

    .loading-container {
        padding: 20px 0;
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 80px 20px;
        text-align: center;

        .empty-icon {
            margin-bottom: 20px;
            opacity: 0.6;
        }

        .empty-title {
            font-size: 18px;
            font-weight: 500;
            color: #666;
            margin: 0 0 10px 0;
        }

        .empty-desc {
            font-size: 14px;
            color: #999;
            margin: 0;
            line-height: 1.5;
        }
    }
}

.book-list-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 30px;

    @media screen and (max-width: vars.$md) {
        grid-template-columns: 1fr;
    }
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px 0;
}
</style>
