module.exports = Self => {
    Self.remoteMethod('getWasteByWorker', {
        description: 'Returns the details of losses by worker',
        accessType: 'READ',
        accepts: [],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/getWasteByWorker`,
            verb: 'GET'
        }
    });

    Self.getWasteByWorker = async options => {
        const myOptions = {};

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        const date = Date.vnNew();
        date.setHours(0, 0, 0, 0);
        const wastes = await Self.rawSql(`
            SELECT *, 100 * dwindle / total percentage
                FROM (
                    SELECT u.name buyer,
                            it.name family,
                            w.itemFk,
                            SUM(w.saleTotal) total,
                            SUM(
                                w.saleExternalWaste +
                                w.saleFaultWaste +
                                w.saleContainerWaste +
                                w.saleBreakWaste +
                                w.saleOtherWaste
                            ) dwindle
                        FROM bs.waste w
                            JOIN account.user u ON u.id = w.buyerFk
                            JOIN vn.itemType it ON it.id = w.itemTypeFk
                        WHERE year = YEAR(TIMESTAMPADD(WEEK, -1, ?))
                            AND week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1)
                        GROUP BY buyerFk, itemTypeFk
                    ) sub
                    ORDER BY percentage DESC
        `, [date, date], myOptions);

        const wastesTotal = await Self.rawSql(`
            SELECT *, 100 * dwindle / total percentage
                FROM (
                    SELECT u.name buyer,
                            SUM(w.saleTotal) total,
                            SUM(
                                w.saleExternalWaste +
                                w.saleFaultWaste +
                                w.saleContainerWaste +
                                w.saleBreakWaste +
                                w.saleOtherWaste
                            ) dwindle
                        FROM bs.waste w
                            JOIN account.user u ON u.id = w.buyerFk
                        WHERE w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?))
                            AND w.week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1)
                        GROUP BY w.buyerFk
                    ) sub
                    ORDER BY percentage DESC
        `, [date, date], myOptions);

        const details = [];

        for (let waste of wastes) {
            const buyerName = waste.buyer;

            let buyerDetail = details.find(waste => {
                return waste.buyer == buyerName;
            });

            if (!buyerDetail) {
                buyerDetail = {
                    buyer: buyerName,
                    lines: []
                };
                details.push(buyerDetail);
            }

            buyerDetail.lines.push(waste);
        }

        for (let waste of details) {
            let buyerTotal = wastesTotal.find(totals => {
                return waste.buyer == totals.buyer;
            });

            Object.assign(waste, buyerTotal);
        }

        return details;
    };
};