// app/static/js/book_ranking.js
document.addEventListener('DOMContentLoaded', function() {
    const timeRangeSelect = document.getElementById('time-range');
    const limitSelect = document.getElementById('limit-count');
    let rankingChart = null;

    // 初始加载
    loadRankingData();

    // 添加事件监听器
    timeRangeSelect.addEventListener('change', loadRankingData);
    limitSelect.addEventListener('change', loadRankingData);

    function loadRankingData() {
        const timeRange = timeRangeSelect.value;
        const limit = limitSelect.value;

        // 显示加载状态
        document.getElementById('ranking-table-body').innerHTML = `
            <tr class="loading-row">
                <td colspan="5"><div class="loading-animation"><span>正在打开书页</span><span class="dot-animation">...</span></div></td>
            </tr>
        `;

        // 调用API获取数据
        fetch(`/statistics/api/book-ranking?time_range=${timeRange}&limit=${limit}`)
            .then(response => response.json())
            .then(data => {
                // 更新表格
                updateRankingTable(data);
                // 更新图表
                updateRankingChart(data);
            })
            .catch(error => {
                console.error('加载排行数据失败:', error);
                document.getElementById('ranking-table-body').innerHTML = `
                    <tr class="error-row">
                        <td colspan="5">加载数据失败，请稍后重试</td>
                    </tr>
                `;
            });
    }

    function updateRankingTable(data) {
        const tableBody = document.getElementById('ranking-table-body');

        if (data.length === 0) {
            tableBody.innerHTML = `
                <tr class="no-data-row">
                    <td colspan="5">暂无数据</td>
                </tr>
            `;
            return;
        }

        let tableHtml = '';

        data.forEach((book, index) => {
            // 给每个单元格添加适当的类名以匹配CSS
            tableHtml += `
                <tr>
                    <td class="rank">${index + 1}</td>
                    <td class="book-cover">
                        <img src="${book.cover_url || '/static/images/book-placeholder.jpg'}" alt="${book.title}">
                    </td>
                    <td class="book-title-cell"><span class="book-title">${book.title}</span></td>
                    <td class="author">${book.author}</td>
                    <td><span class="borrow-count">${book.borrow_count}</span></td>
                </tr>
            `;
        });

        tableBody.innerHTML = tableHtml;
    }

    function updateRankingChart(data) {
        // 销毁旧图表
        if (rankingChart) {
            rankingChart.destroy();
        }

        if (data.length === 0) {
            return;
        }

        // 准备图表数据
        const labels = data.map(book => book.title);
        const borrowCounts = data.map(book => book.borrow_count);

        // 创建图表
        const ctx = document.getElementById('ranking-chart').getContext('2d');
        rankingChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '借阅次数',
                    data: borrowCounts,
                    backgroundColor: 'rgba(183, 110, 121, 0.6)', // 玫瑰金色调
                    borderColor: 'rgba(140, 45, 90, 1)', // 浆果红
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '借阅次数',
                            font: {
                                family: "'Open Sans', sans-serif",
                                size: 13
                            },
                            color: '#5D5053'
                        },
                        ticks: {
                            color: '#8A797C',
                            font: {
                                family: "'Open Sans', sans-serif"
                            }
                        },
                        grid: {
                            color: 'rgba(211, 211, 211, 0.3)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '图书',
                            font: {
                                family: "'Open Sans', sans-serif",
                                size: 13
                            },
                            color: '#5D5053'
                        },
                        ticks: {
                            color: '#8A797C',
                            font: {
                                family: "'Open Sans', sans-serif"
                            }
                        },
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '热门图书借阅排行',
                        font: {
                            family: "'Playfair Display', serif",
                            size: 16,
                            weight: 'bold'
                        },
                        color: '#B76E79'
                    }
                }
            }
        });
    }
});
