// app/static/js/borrow_statistics.js
document.addEventListener('DOMContentLoaded', function() {
    const timeRangeSelect = document.getElementById('time-range');
    let trendChart = null;
    let categoryChart = null;

    // 初始加载
    loadBorrowTrend();
    loadCategoryDistribution();

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

    function loadBorrowTrend() {
        const timeRange = timeRangeSelect.value;

        // 调用API获取数据
        fetch(`/statistics/api/borrow-trend?time_range=${timeRange}`)
            .then(response => response.json())
            .then(data => {
                updateTrendChart(data);
                updateBorrowSummary(data);
            })
            .catch(error => {
                console.error('加载借阅趋势数据失败:', error);
            });
    }

    function loadCategoryDistribution() {
        // 调用API获取数据
        fetch('/statistics/api/category-distribution')
            .then(response => response.json())
            .then(data => {
                updateCategoryChart(data);
            })
            .catch(error => {
                console.error('加载分类分布数据失败:', error);
            });
    }

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

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

        // 准备图表数据
        const labels = data.map(item => item.date);
        const borrowData = data.map(item => item.borrow);
        const returnData = data.map(item => item.return);
        const overdueData = data.map(item => item.overdue);

        // 创建图表
        const ctx = document.getElementById('trend-chart').getContext('2d');
        trendChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: '借阅数',
                        data: borrowData,
                        borderColor: 'rgba(54, 162, 235, 1)',
                        backgroundColor: 'rgba(54, 162, 235, 0.1)',
                        tension: 0.1,
                        fill: true
                    },
                    {
                        label: '归还数',
                        data: returnData,
                        borderColor: 'rgba(75, 192, 192, 1)',
                        backgroundColor: 'rgba(75, 192, 192, 0.1)',
                        tension: 0.1,
                        fill: true
                    },
                    {
                        label: '逾期数',
                        data: overdueData,
                        borderColor: 'rgba(255, 99, 132, 1)',
                        backgroundColor: 'rgba(255, 99, 132, 0.1)',
                        tension: 0.1,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '数量'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '借阅与归还趋势'
                    }
                }
            }
        });
    }

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

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

        // 准备图表数据
        const labels = data.map(item => item.category);
        const counts = data.map(item => item.count);

        // 创建图表
        const ctx = document.getElementById('category-chart').getContext('2d');
        categoryChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    data: counts,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.7)',
                        'rgba(54, 162, 235, 0.7)',
                        'rgba(255, 206, 86, 0.7)',
                        'rgba(75, 192, 192, 0.7)',
                        'rgba(153, 102, 255, 0.7)',
                        'rgba(255, 159, 64, 0.7)',
                        'rgba(199, 199, 199, 0.7)',
                        'rgba(83, 102, 255, 0.7)',
                        'rgba(40, 159, 64, 0.7)',
                        'rgba(210, 199, 199, 0.7)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '分类借阅分布'
                    },
                    legend: {
                        position: 'right'
                    }
                }
            }
        });
    }

    function updateBorrowSummary(data) {
        if (!data || data.length === 0) {
            return;
        }

        // 计算总数和平均数
        let totalBorrows = 0;
        let totalReturns = 0;
        let totalOverdue = data[data.length - 1].overdue || 0;

        data.forEach(item => {
            totalBorrows += item.borrow;
            totalReturns += item.return;
        });

        const summary = document.getElementById('borrow-summary');
        summary.innerHTML = `
            <div class="stats-item">
                <div class="stats-value">${totalBorrows}</div>
                <div class="stats-title">总借阅</div>
            </div>
            <div class="stats-item">
                <div class="stats-value">${totalReturns}</div>
                <div class="stats-title">总归还</div>
            </div>
            <div class="stats-item">
                <div class="stats-value">${totalOverdue}</div>
                <div class="stats-title">当前逾期</div>
            </div>
            <div class="stats-item">
                <div class="stats-value">${Math.round((totalBorrows - totalReturns) - totalOverdue)}</div>
                <div class="stats-title">正常借出</div>
            </div>
        `;
    }
});
