(function () {
    global.dashModule
        .controller('ordersController', ['$scope', '$rootScope', '$http', '$compile', '$translate', '$', 'dataTableHelper', 'utilsService', 'ORDER_STATUSES_ICONS', 'ORDER_STATUSES', ordersController])
        .directive('orders', [ordersDirective]);
    function ordersDirective() {
        return {
            restrict: 'E',
            templateUrl: 'orders/html/ordersTemplate'
        };
    }

    function ordersController($scope, $rootScope, $http, $compile, $translate, $, dataTableHelper, utilsService, ORDER_STATUSES_ICONS, ORDER_STATUSES) {
        const translationPath = 'orders.tables.headers.';
        $scope.subModule = global.getParameterByName('subModule') || 'ongoing_orders';
        $scope.setSubModule = setSubModule;
        $scope.isSubmoduleVisible = isSubmoduleVisible;
        $scope.getOngoingOrders = getOngoingOrders;
        $scope.getOrdersHistory = getOrdersHistory;
        $scope.brokers = [];
        addUrlListener();
        function addUrlListener() {
            window.addEventListener('popstate', function (e) {
                $scope.$evalAsync($scope => {
                    $scope.subModule = e.state ? e.state.subModule : 'ongoing_orders';
                });
            }, false);
        }
        function setSubModule($event) {
            $scope.subModule = $event.currentTarget.attributes.subModule.value;
            history.pushState({
                subModule: $scope.subModule
            }, null, '?subModule=' + $scope.subModule);
        }
        function isSubmoduleVisible(subModule) {
            return subModule === $scope.subModule;
        }
        function getOngoingOrders() {
            $http({
                method: 'POST',
                url: 'orders/api/getOngoingOrdersHeaders',
            }).then(showOngoingOrders, utilsService.onHttpError);
        }
        function showOngoingOrders(response) {
            if (response.data.brokers && response.data.brokers.length > 0) {
                $scope.brokers = response.data.brokers;
            }
            if (response.data.headers.length > 0) {
                const params = {
                    selector: '#ongoing-orders',
                    url: 'orders/api/getOngoingOrders',
                    hasDetails: true,
                    extraTableOptions: {
                        responsive: false,
                        order: [
                            [1, 'asc']
                        ]
                    }
                };
                dataTableHelper.generateColumns(response.data.headers, translationPath, dataTableHelper.showTable, params, formatOrderColumn)
                    .then((table) => {
                        addDetailsEvent(table, params.selector);
                        addAssignBrokerDirectives();
                    });
            }
        }
        function addAssignBrokerDirectives() {
            $('#ongoing-orders tbody').off('click', '.assign-icon');
            $('#ongoing-orders tbody').on('click', '.assign-icon', function () {
                const assignSelector = $(this).parent().find('.assign-broker');
                if (assignSelector.length) {
                    assignSelector.remove();
                } else {
                    const parent = $(this).parent();
                    const idOrder = parent.attr('id-order');
                    const directiveHtml = '<assign-broker id="assign-broker-' + idOrder + '" class="assign-broker" ng-controller="assignBrokerCtrl"></assign-broker>';
                    const scope = $rootScope.$new();
                    scope.brokers = $scope.brokers;
                    scope.idOrder = idOrder;
                    scope.onUpdate = getOngoingOrders;
                    const comp = $compile($(directiveHtml))(scope);
                    parent.append(comp);
                }
            });
        }
        function getOrdersHistory() {
            $http({
                method: 'POST',
                url: 'orders/api/getOrdersHistoryHeaders',
            }).then(showOrdersHistory, utilsService.onHttpError);
        }
        function showOrdersHistory(response) {
            if (response.data.length > 0) {
                const params = {
                    selector: '#orders-history',
                    url: 'orders/api/getOrdersHistory',
                    hasDetails: true,
                    extraTableOptions: {
                        responsive: false,
                        order: [
                            [1, 'asc']
                        ]
                    }
                };
                dataTableHelper.generateColumns(response.data, translationPath, dataTableHelper.showTable, params, formatOrderColumn)
                    .then((table) => {
                        addDetailsEvent(table, params.selector);
                    });
            }
        }
        function addDetailsEvent(table, containerSelector) {
            $(containerSelector + ' tbody').off('click', 'td.info-control');
            $(containerSelector + ' tbody').on('click', 'td.info-control', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);
                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    const directiveHtml = '<orders-details ng-controller="ordersDetailsCtrl"></orders-details>';
                    const scope = $rootScope.$new();
                    scope.data = row.data();
                    const layerSelector = 'details-layer-' + scope.data.id;
                    row.child('<div id="' + layerSelector + '"></div>').show();
                    const comp = $compile($(directiveHtml))(scope);
                    $('#' + layerSelector).append(comp);
                    tr.addClass('shown');
                }
            });
        }
        function formatOrderColumn(value, translations) {
            const columnObj = {
                data: value,
                title: translations[translationPath + value]
            };
            const renders = getOrderRenders();
            columnObj.visible = isColumnVisible(value);
            if (typeof renders[value] !== 'undefined') {
                columnObj.render = renders[value];
            }
            return columnObj;
        }
        function isColumnVisible(value) {
            const notVisibleFields = [
                'id',
                'idCustomer',
                'idCommercialLead',
                'idCommercialLeadUser',
                'idCustomerInstance',
                'deliveryAddress',
                'customerPhone',
                'customerMail',
                'commercialLeadPhone',
                'commercialLeadMail'
            ];
            return notVisibleFields.indexOf(value) === -1;
        }
        function getOrderRenders() {
            return {
                orderNumber: ordersNumberRenderer,
                status: ordersStatusRenderer,
                orderItems: orderItemsRender,
                step: orderStepRender,
                assignedTo: assignedToRender
            };
            function ordersNumberRenderer(data, type, row) {
                return '<a href="orders?subModule=orders_steps&idOrder=' + row.id + '&orderNumber=' + row.orderNumber + '">' + data + '</a>';
            }
            function ordersStatusRenderer(data) {
                const status = ORDER_STATUSES[data] || data;
                return '<div class="order-status-' + data + '"><span class="' + ORDER_STATUSES_ICONS[data] + '"></span> ' + status + '</div>';
            }
            function orderItemsRender(data, type, row) {
                let html = '';
                row.packages.forEach((pacakgeObj) => {
                    html += '<div class="order-item">';
                    html += pacakgeObj.units + ' x ' + pacakgeObj.packageName;
                    html += typeof pacakgeObj.shortDesc !== 'undefined' ? ' ( ' + pacakgeObj.shortDesc + ' )' : '';
                    html += ' <span class="order-status-' + pacakgeObj.status + ' ' + ORDER_STATUSES_ICONS[pacakgeObj.status] + '"></span>';
                    html += '</div>';
                });
                return html;
            }
            function orderStepRender(data) {
                return data.replace(/,/g, '<br/>');
            }
            function assignedToRender(data, type, row) {
                const newData = data === '' ? $translate.instant('orders.tables.extra.NOT_ASSIGNED') : data;
                let html = '<div class="assign-broker-layer" id-order="' + row.id + '">';
                html += '<div class="assigned-broker">' + newData + '</div>';
                html += '<div class="assign-icon glyphicon glyphicon-pencil"></div>';
                html += '</div>';
                return html;
            }
        }
    }
})();