system.controller("ReportVerifierController", ReportVerifierController);

function ReportVerifierController($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.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,
        });

        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() + '&ignore_localization=1';
                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)) {

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

                        const verifierData = reportDataByLocale.data[key];

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

                    }
                }
            }
            safeApply();
        });
    }

    $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();
}