const Transaction = require('../models/Transaction');
const Group = require('../models/Group');

// @desc    获取统计数据
// @route   GET /api/statistics
// @access  Private/Admin
const getStatistics = async (req, res) => {
    try {
        // 获取最近7天的交易数据
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 7);

        const transactions = await Transaction.findAll(
            { startDate, endDate },
            1,
            1000
        );

        // 处理交易数据,按日期分组
        const transactionData = {};
        const labels = [];
        const data = [];

        // 初始化最近7天的数据
        for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            const dateStr = date.toISOString().split('T')[0];
            transactionData[dateStr] = 0;
            labels.push(dateStr);
        }

        // 统计每天的交易金额
        transactions.transactions.forEach(transaction => {
            const date = new Date(transaction.time).toISOString().split('T')[0];
            if (transactionData[date] !== undefined) {
                transactionData[date] += transaction.amount;
            }
        });

        // 转换为数组格式
        labels.forEach(label => {
            data.push(transactionData[label]);
        });

        // 获取群组统计数据
        const groups = await Group.findAll();
        const groupData = {
            labels: groups.map(group => group.groupName),
            data: groups.map(group => group.isActive ? 1 : 0)
        };

        res.json({
            transactions: {
                labels,
                data
            },
            groups: groupData
        });
    } catch (error) {
        console.error('获取统计数据失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    getStatistics
};