system.controller("StuckAutoFFPortal", StuckAutoFFPortal);

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

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

    $scope.baseApiUrl = window.base_api_url;
    $scope.orderStuckDate = [];
    $scope.locale = 'us';
    $scope.stuckOrders = {};
    $scope.stuckOrderMeta = [];
    $scope.markets = window.markets;
    $scope.dateReport = [];
    $scope.mapPositionMarket = [];

    function init()
    {
        let date = new Date();
        for (let i = 0; i < 6; i++) {
            $scope.orderStuckDate.push(convertToComputerDate(date));
            date.setDate(date.getDate() - 1);
        }

        $scope.markets.hasOwnProperty('central');
        delete $scope.markets.central;

        $scope.marketLength = Object.keys($scope.markets).length;

        let marketRun = 0;
        for (let i = 1; i <= 2 * $scope.marketLength; i++) {
            $scope.mapPositionMarket[i - 1] = Object.keys($scope.markets)[marketRun];
            if (i % 2 === 0) {
                marketRun ++;
            }
        }

        $scope.generateStuckOrderReport();
    }

    $scope.generateStuckOrderReport = async function()
    {
        $scope.stuckOrders = await getStuckOrderBySelfService();
        $scope.dateReports = Object.keys($scope.stuckOrders.us);
        if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
            $scope.$apply();
        }

       /* for (let i = 0; i < this.orderStuckDate.length; i++) {
            $scope.stuckOrders[this.orderStuckDate[i]] = await getStuckOrders(this.orderStuckDate[i]);
        }*/
        /*
        * if (response.data.status === 'successful') {
                    $scope.stuckOrders = response.data.result;
                    $scope.stuckOrderMeta = response.data.meta;
                }
        * */
    }

    $scope.renderStuckCell = function(n, values)
    {
        if ((n - 1) % 2 === 0) { // order count
            return values.length;
        } else {
            /*let count = 0;
            for (let i = 0; i < values[$scope.mapPositionMarket[n - 1]].length; i++) {
                count += values[$scope.mapPositionMarket[n - 1]][i].items.length;
            }
            return count;*/
        }
    }

    $scope.range = function(min, max, step) {
        step = step || 1;
        const input = [];
        for (let i = min; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };

    $scope.countProduct = function(value)
    {
        let count = 0;
        for (let i = 0; i < value.length; i++) {
            count += parseInt(value[i].countProd);
        }
        return count;
    }

    function getStuckOrderBySelfService()
    {
        return new Promise(function(resolve) {
            
            const currentURL = window.location.href;

            const url = new URL(currentURL);
            const stopDate = url.searchParams.get("stop_date");

            let apiUrl = '/print-suppliers/portal/get-stuck-order?ignore_localization=1&auto_fulfill_only=1';

            if (stopDate) {
                apiUrl = '/print-suppliers/portal/get-stuck-order?ignore_localization=1&stop_date=' + stopDate;
            }

            $http.get(apiUrl).then(function (response) {
            // $http.get('http://printerval.test/modules/print-suppliers/json/get-stuck-order.json').then(function (response) {
                resolve(response.data.result);
            }, function (error) {
                resolve(null);
                console.warn(error);
            });
        });
    }

    function getStuckOrders(date)
    {
        let promises = [];
        for (const market in $scope.markets) {

            let url = makeStuckOrderUrl(market, date);
            let p = new Promise(function(resolve) {
                $http.get(url).then(function (response) {
                    resolve({
                        market,
                        data: response.data
                    });
                }, function (error) {
                    resolve(null);
                    console.warn(error);
                });
            })
            promises.push(p);

        }

        return new Promise(function(resolve) {
            Promise.all(promises).then(function (values) {
                let stuckOrders = {};
                for (let i = 0; i < values.length; i++) {
                    stuckOrders[values[i].market] = values[i].data.result;
                }
                resolve(stuckOrders);
            });
        })

    }

    function makeStuckOrderUrl(market, date)
    {
        const endpoint = '/v2/order';
        const data = {
            'sorts': '-created_at',
            'page_id': '0',
            'page_size': '-1',
            'fields': 'id,code,payment_type,shipping_type,created_at',
            'filters': `order.created_at=[${date} 00:00:00;${date} 23:59:59],order.status={PROCESSING},order.payment_status=paid`,
            'service_token': 'megaads@123'
        };
        const searchParams = new URLSearchParams(data);

        let url = new URL($scope.baseApiUrl);
        url = url.host.split('.');
        url[0] = market;
        url = url.join('.');

        // console.log('https://' + url + endpoint + '?' + decodeURIComponent(searchParams.toString()))
        // return 'https://' + market + '.api.printerval.com' + endpoint + '?' + decodeURIComponent(searchParams.toString());
        return 'https://' + url + endpoint + '?' + decodeURIComponent(searchParams.toString());
    }

    function convertToVnDate(date) {
        return moment(date).format('DD/MM/YYYY');
    }

    function convertToComputerDate(date) {
        // date = moment("date", "DD-MM-YYYY");
        return moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD');
    }

    init();

}