'use strict';

async function overSpeedList (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const { userId } = ctx.fs.api;
        const { limit } = ctx.query;

        const overSpeedRes = await models.Overspeed.findAll({
            attributes: ['id', 'licensePlate', 'overrunRate', 'deductPoints', 'fine', 'processingTime', 'testTime'],
            order: [['testTime', 'DESC']],
            limit: limit || 120,
            where: {
                processingTime: { $ne: null },
                testTime: { $ne: null },
            },
            order: [['testTime', 'DESC']],
        })

        const overSpeedProcessedCount = await models.Overspeed.count({
            where: {
                $and: [
                    { processingTime: { $ne: null } },
                    { processingTime: { $ne: '' } }
                ]
            }
        })

        ctx.status = 200
        ctx.body = {
            processed: overSpeedProcessedCount,
            overSpeedList: overSpeedRes,
        }
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

async function overSpeedProcessed (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const { userId } = ctx.fs.api;

        const overSpeedCountRes = await models.Overspeed.count({
            attributes: ['nameOfInspectionPoint'],
            group: ['nameOfInspectionPoint'],
        })
        const overSpeedCountProcessedRes = await models.Overspeed.count({
            attributes: ['nameOfInspectionPoint'],
            where: { processingTime: { $ne: null } },
            group: ['nameOfInspectionPoint'],
        })

        let data = []
        for (let c of overSpeedCountRes) {
            const corProcessed = overSpeedCountProcessedRes.find(d => d.nameOfInspectionPoint == c.nameOfInspectionPoint)
            if (corProcessed) {
                data.push({
                    name: c.nameOfInspectionPoint,
                    processed: corProcessed.count,
                    total: c.count,
                })
            }
        }

        ctx.status = 200
        ctx.body = data
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

module.exports = {
    overSpeedList,
    overSpeedProcessed
};