<template>
    <div class="ranking-container">
        <div class="content-wrapper">
            <!-- 左侧榜单导航 -->
            <div class="ranking-sidebar">
                <ul class="ranking-nav">
                    <li v-for="(item, id) in areaList" :key="id" :class="{ active: item.id == currentRankingType }"
                        @click="switchRankingType(item.id)">
                        {{ item.title }}
                    </li>
                </ul>
            </div>

            <!-- 右侧内容区 -->
            <div class="ranking-content">
                <!-- 顶部分类导航 -->
                <div class="category-tabs">
                    <ul class="category-nav">
                        <li 
                            :class="{ active: currentCategoryId === '' }"
                            @click="switchCategory('')"
                        >全部</li>
                        <li v-for="(name, id) in categoryMap" :key="id" :class="{ active: id == currentCategoryId }"
                            @click="switchCategory(id)">
                            {{ name }}
                        </li>
                    </ul>
                </div>

                <!-- 加载状态 -->
                <div v-if="loading" class="loading-container">
                    <el-skeleton :rows="10" animated />
                </div>

                <!-- 书籍列表 -->
                <div v-else class="book-list-container">
                    <div v-if="books.length === 0" class="empty-state">
                        <el-empty description="暂无数据" />
                    </div>
                    <div v-else>
                        <div v-for="(book, index) in books" :key="book.id || index" class="book-item">
                        <div class="rank-number" :class="{
                            'rank-first': index === 0,
                            'rank-second': index === 1,
                            'rank-third': index === 2
                            }">{{ (currentPage - 1) * pageSize + index + 1 }}</div>
                        <book-card :book="book" />
                        </div>
                    </div>
                </div>

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

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

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

        // 数据状态
        const books = ref([]);
        const loading = ref(false);

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

        // 从store获取分类数据
        const categoryMap = computed(() => {
            const map = {};
            store.allCategories.forEach(category => {
                map[category.id] = category.title;
            });
            if(!currentCategoryId.value && store.allCategories[0]){
                currentCategoryId.value = ''; // 默认选择"全部"
            }
            return map;
        });

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

        //获取区域
        const areaList = ref([]);
        const getAreaList = async () => {
            const response = await homeApi.getBookAreaList();
            areaList.value = response.result;
            currentRankingType.value = areaList.value[0].id;
        };

        // 获取排行榜数据
        const fetchRankingData = async () => {
            if (loading.value) return;
            
            loading.value = true;
            try {
                const params = {
                    pageNo: currentPage.value,
                    pageSize: pageSize.value,
                    shopClass: currentCategoryId.value || undefined, // 如果是"全部"则不传分类参数
                    shopCion: currentRankingType.value
                };

                let response = await homeApi.getRecommendList(params);

                if (response.code == 200 && response.result) {
                    // 处理分页数据
                    if (response.result.records) {
                        books.value = response.result.records;
                        total.value = response.result.total || 0;
                    } else if (Array.isArray(response.result)) {
                        books.value = response.result;
                        total.value = response.result.length;
                    } else {
                        books.value = [];
                        total.value = 0;
                    }
                } else {
                    books.value = [];
                    total.value = 0;
                    ElMessage.warning(response.message || '获取排行榜数据失败');
                }
            } catch (error) {
                console.error('获取排行榜数据失败:', error);
                books.value = [];
                total.value = 0;
                ElMessage.error('网络错误，请稍后重试');
            } finally {
                loading.value = false;
            }
        };

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

        // 切换榜单类型
        const switchRankingType = (id) => {
            if (currentRankingType.value === id) return;
            currentRankingType.value = id;
            currentPage.value = 1;
            fetchRankingData();
        };

        // 分页切换
        const handlePageChange = (page) => {
            currentPage.value = page;
            fetchRankingData();
        };

        // 监听路由参数变化
        watch(() => route.params.id, (newId) => {
            if (newId && newId !== currentCategoryId.value) {
                currentCategoryId.value = newId;
                currentPage.value = 1;
                fetchRankingData();
            }
        });

        // 初始化
        onMounted(async () => {
            // 确保分类数据已加载
            await store.fetchCategories();
            
            // 设置初始分类
            if (categoryId.value) {
                currentCategoryId.value = categoryId.value;
            }
            await getAreaList();
            
            // 获取排行榜数据
            await fetchRankingData();
        });

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

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

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

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

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

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

// 右侧内容区
.ranking-content {
    flex: 1;
    min-width: 0;
}

// 顶部分类导航
.category-tabs {
    width: 100%;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    padding: 0 20px;

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

        li {
            padding: 15px 20px;
            font-size: 16px;
            cursor: pointer;
            position: relative;
            transition: all 0.3s;

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

            &.active {
                color: vars.$primary-color;
                font-weight: bold;

                &::after {
                    content: '';
                    position: absolute;
                    bottom: 0;
                    left: 50%;
                    transform: translateX(-50%);
                    width: 30px;
                    height: 3px;
                    background-color: vars.$primary-color;
                }
            }
        }
    }
}

.loading-container {
    padding: 20px;
}

.empty-state {
    padding: 40px 20px;
    text-align: center;
}

.book-list-container {
    min-height: 400px;
    padding: 20px;
}

.book-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 15px;
    margin-bottom: 15px;
    position: relative;
}

.rank-number {
    width: 24px;
    height: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ddd;
    color: #fff;
    font-weight: bold;
    border-radius: 4px;
    margin-right: 15px;
    flex-shrink: 0;

    // 前三名特殊样式
    &.rank-first {
        background-color: #e74c3c;
    }

    &.rank-second {
        background-color: #f39c12;
    }

    &.rank-third {
        background-color: #2ecc71;
    }
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px 0;
    border-top: 1px solid #f0f0f0;
    margin-top: 20px;
}
</style>
