system.controller("ReportProductVerifierController", ReportProductVerifierController);

function ReportProductVerifierController($scope, $http, $rootScope, Upload, $window) {

    this.__proto__ = new BaseController($scope, $http, $rootScope, Upload);

    const inproductStatus = ['DELIVERING', 'FINISHED', 'ISSUED', 'READY_TO_SHIP'];
    const safeApply = () => {
        if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
            $scope.$apply();
        }
    }

    $scope.reportVerifiers = {};
    $scope.verifierDetail = {};
    $scope.locates = dashboardLocalization;
    $scope.selectedVerifier = null;
    $scope.dateRange = 1;

    $scope.stateValues = {
        total_waiting_kpi: 0,
        total_pending_kpi: 0,
        total_inproduction_kpi: 0,
        countRows: 0,
    };

    $scope.initialize = function () {

        $("#date-from").datepicker({
            dateFormat: "yy-mm-dd",
        }).datepicker("setDate", "-1d");

        $("#date-to").datepicker({
            dateFormat: "yy-mm-dd",
        }).datepicker("setDate", "-1d");

        $scope.fetchVerifiers();
        $scope.feedReport();
    };

    $scope.feedReport = function () 
    {
        let dateFrom = $("#date-from").val();
        let dateTo = $("#date-to").val();

        dateFrom = new Date(dateFrom);
        dateFrom.setHours(0, 0, 0, 0);
        dateTo = new Date(dateTo)
        dateTo.setHours(23, 59, 59, 0);

        const timeDifference = dateTo - dateFrom;
        const daysDifference = timeDifference / (1000 * 60 * 60 * 24);

        $scope.dateRange = Math.round(daysDifference);

        dateFrom = dateFrom.getTime() / 1000;
        dateTo = dateTo.getTime() / 1000;

        $scope.reportVerifiers = {};

        const params = new URLSearchParams({
            verifier_email: $scope.selectedVerifier,
            dateFrom,
            dateTo,
            ignore_localization: 1
        });

        $scope.sortVerifier = {};

        const promises = [];
        for (let key in $scope.locates) 
        {
            let locateItem = $scope.locates[key];
            promises.push(new Promise (function (resolve) 
            {
                const locale = locateItem.locale;
                let endPoint = '/print-suppliers/report/get-report-verifiers?' + params.toString();
                if (locale != 'us') {
                    endPoint = '/' + locale + endPoint;
                }

                $http.get(endPoint).then(function (response) {
                    resolve({ locale: locale, data: response.data});
                }, function (error) {
                    resolve({ locale: locale, data: []});
                });
            }));
        }

        Promise.all(promises).then((values) => {

            for (let i = 0; i < values.length; i++) { // thị trường
                const reportDataByLocale = values[i];
                for (const key in reportDataByLocale.data) { 
                    if (Object.hasOwnProperty.call(reportDataByLocale.data, key)) {

                        const locale = reportDataByLocale.locale;

                        if (typeof $scope.reportVerifiers[key] == 'undefined') {
                            $scope.reportVerifiers[key] = {};
                        }

                        if (typeof $scope.reportVerifiers[key][locale] == 'undefined') {
                            $scope.reportVerifiers[key][locale] = {
                                total_kpi: 0,
                                inproduction_kpi: 0,
                                waiting_kpi: 0
                            };
                        }

                        const verifierData = reportDataByLocale.data[key];

                        if (typeof $scope.sortVerifier[key] == 'undefined') {
                            $scope.sortVerifier[key] = 0;
                        }

                        for (const status in verifierData) {
                            if (Object.hasOwnProperty.call(verifierData, status)) {
                                const kpi = verifierData[status];
                                if (inproductStatus.includes(status)) {
                                    $scope.reportVerifiers[key][locale].inproduction_kpi = kpi;
                                }
                                if (status == 'IS_TICKET') {
                                    $scope.reportVerifiers[key][locale].pending_kpi = kpi;
                                    $scope.sortVerifier[key] += kpi;
                                }
                                if (status == 'PROCESSING') {
                                    $scope.reportVerifiers[key][locale].waiting_kpi = kpi;
                                }
                                $scope.reportVerifiers[key][locale].total_kpi = kpi;
                            }
                        }

                    }
                }
            }

            const rows = [];
            let rowId = 0;

            for (const key in $scope.reportVerifiers) {
                if (Object.hasOwnProperty.call($scope.reportVerifiers, key)) {
                    const verifier = $scope.reportVerifiers[key];
                    let rowsPosition = 0;
                    for (const locale in verifier) {
                        if (Object.hasOwnProperty.call(verifier, locale)) {
                            const verifierItem = verifier[locale];

                            let email = key;
                            let rowspan = 0;
                            if (rowsPosition != 0) {
                                email = '';
                            } else {
                                rowspan = Object.keys(verifier).length;
                                rowId ++;
                            }

                            rows.push({
                                locale,
                                email: email,
                                total_kpi: verifierItem.total_kpi,
                                inproduction_kpi: verifierItem.inproduction_kpi,
                                waiting_kpi: verifierItem.waiting_kpi,
                                pending_kpi: verifierItem.pending_kpi,
                                rowspan: rowspan,
                                rowsPosition,
                                rowId,
                                sort: $scope.sortVerifier[key]
                            });

                            $scope.stateValues.total_inproduction_kpi += verifierItem.inproduction_kpi;
                            $scope.stateValues.total_waiting_kpi += verifierItem.waiting_kpi;
                            $scope.stateValues.total_pending_kpi += verifierItem.pending_kpi;
                            $scope.stateValues.countRows ++;
                            
                        }

                        rowsPosition ++;
                    }

                    rows.sort((a, b) => b.sort - a.sort);

                    $scope.reportRows = rows;
                }
            }

            safeApply();

        });
    }

    $scope.getReactColor = (value, type) => {

        let mirrorValue = 0;

        switch (type) {
            case 'waiting':
                mirrorValue = $scope.stateValues.total_waiting_kpi;
                break;
            case 'pending':
                mirrorValue = $scope.stateValues.total_pending_kpi;
                break;
            case 'inproduction':
                mirrorValue = $scope.stateValues.total_inproduction_kpi;
                break;
        }

        if ($scope.stateValues.countRows && mirrorValue) 
        {
            const avg = mirrorValue / $scope.stateValues.countRows;

            if (value < 50) return '#24da00'; // xanh

            if (value < 100) return '#333';

            if (value > avg && value < avg + (avg * 0.5)) return '#ff9d2e';

            if (value > avg + (avg * 0.5)) return '#ff0000'; // đỏ
        }

        return '#000';
    }

    $scope.getObjectLength = (obj) => {
        return Object.keys(obj).length;
    }

    $scope.fetchVerifiers = () => 
    {
        const promises = [];

        const url = $scope.buildUrl('/central/order/verifier/get');
        const urlObject = new URL(url);

        const hostParts = urlObject.host.split('.');
        hostParts[0] = 'central';

        urlObject.host = hostParts.join('.');

        promises.push(new Promise((resolve, reject) => 
        {
            const endPoint = 'https://central.api.printerval.com/central/order/verifier/get'
            // const endPoint = urlObject.toString();
            $http.get(endPoint, {}).then(function (response) {
                resolve({ data: response.data.result});
            }, function (error) {
                resolve({ data: []});
            });
        }));

        const urlConfig = $scope.buildUrl('/central/verifier-config');
        const urlObjectConfig = new URL(urlConfig);

        const hostPartsConfig = urlObjectConfig.host.split('.');
        hostPartsConfig[0] = 'central';

        urlObjectConfig.host = hostPartsConfig.join('.');

        promises.push(new Promise((resolve, reject) => 
        {
            const endPoint = 'https://central.api.printerval.com/central/verifier-config'
            // const endPoint = urlObjectConfig.toString();
            $http.get(endPoint, {}).then(function (response) {
                resolve({ data: response.data});
            }, function (error) {
                resolve({ data: []});
            });
        }));

        Promise.all(promises).then(values => 
            {
            const verifiers = values[0].data;
            const verifierKPI = values[1].data;

            const verifierKPIMap = {};
            for (let i = 0; i < verifierKPI.length; i++) {
                const verifier = verifierKPI[i];
                verifierKPIMap[verifier.email] = verifier.kpi;
            }

            for (let i = 0; i < verifiers.length; i++) {
                const verifier = verifiers[i];
                const kpi = typeof verifierKPIMap[verifier.email] != 'undefined' ? verifierKPIMap[verifier.email] : 0;

                verifier.kpi = kpi;
                $scope.verifierDetail[verifier.email] = verifier;
            }

            safeApply();
        });

    }

    $scope.getVerifierDetail = (verifierId) => {
        if (typeof $scope.verifierDetail[verifierId] != 'undefined') {
            return $scope.verifierDetail[verifierId];
        }

        return {
            name: '...'
        }
    }


    $scope.initialize();
}