(function () {
    'use strict';

    angular
        .module('editorRotas')
        .directive('tableGrid', tableGrid);

    tableGrid.$inject = ['$timeout', 'gridService', '__env'];

    function tableGrid($timeout, gridService, __env) {
        var directive = {
            restrict: 'E',
            replace: true,
            templateUrl: __env.appPath + 'scripts/components/table-grid/table-grid.directive.html',
            scope: false,
            link: link
        };

        function link(scope, element) {
            function random(min, max) {
                return Math.floor(Math.random() * (max - min)) + min;
            }

            scope.orderByField = 'MacroSetor';
            scope.vm.revertSort = false;

            scope.columns = [
                { name: 'Macro Setor', sort: 'MacroSetor' },
                { name: 'Setor', sort: 'Setor' },
                { name: 'Descrição', sort: 'Descricao' },
                { name: 'Rota', sort: 'Rota' },
                { name: 'Nº de Pacmans ', sort: 'QtdPacmans' },
                { name: 'Km Total', sort: '_KmTotal' },
                { name: 'Km Coleta', sort: '_KmColeta' },
                { name: 'Km Deslocamento', sort: '_KmDeslocamento' },
                { name: 'Km Coleta Manual', sort: '_KmManual' },
                { name: 'Efic. no setor', sort: 'EficienciaSetor' },
                { name: 'Efic. da Operação', sort: 'EficienciaOperacao' },
                { name: 'Etapa', sort: 'Etapa' },
                { name: 'Data de Ativação', sort: 'DataAtivacaoTicks' },
                { name: 'Status', sort: 'StatusDescricao' }
            ];

            scope.vm.resultGrid = [];
            scope.vm.dataGrid = [];
            let currentIndex = 0;

            scrollGrid();

            //Fazer a ordenação asc e desc!!!!!!
            scope.SortColumn = (item) => {
                $("footer:visible .loading-inlog-modulo").fadeIn();
                scope.vm.revertSort = !scope.vm.revertSort;
                scope.orderByField = item.sort;
                scope.vm.colunaOrdenada = item.sort;
                scope.vm.takeGrid = scope.vm.configuracoesGerais.PaginacaoGrid * 2;
                scope.vm.skipGrid = 0;

                scope.vm.objTakeSkipGrid = {
                    Take: scope.vm.takeGrid,
                    Skip: scope.vm.skipGrid,
                    ColOrdenada: scope.vm.colunaOrdenada,
                    RevertSort: scope.vm.revertSort
                }

                gridService
                    .ConsultaGrid(scope.vm.objTakeSkipGrid)
                    .then(successConsultaGrid)
                    .catch(errorRequest);

                currentIndex = 0;
            };

            function successConsultaGrid(result) {
                scope.vm.dataGrid = result.data.Grid.Data.slice(0, scope.vm.takeGrid / 2);
                scope.vm.resultGridPendente = result.data.Grid.Data.slice(scope.vm.takeGrid / 2, scope.vm.takeGrid);
                scope.ordenou = true;

                $("footer:visible .loading-inlog-modulo").fadeOut();
            }

            function errorRequest(error) {
                if (error.statusText) ngNotify.set(error.statusText, { type: 'error', sticky: true, button: true });
                debugger;
                console.error(error);
            }

            scope.loadMoreRecords = () => {
                if (scope.vm.resultGrid) {
                    var stock;
                    var i = 0;
                    while (i < scope.vm.configuracoesGerais.PaginacaoGrid && currentIndex < scope.vm.resultGrid.length) {
                        stock = scope.vm.resultGrid[currentIndex];
                        currentIndex++;
                        scope.vm.dataGrid.push(stock);
                        i++;
                    }
                }
            };

            scope.toggleGrid = () => {
                if (event.target.tagName === 'BUTTON') return;

                var $mapContainer = $('.middle-container');
                element.toggleClass('closed').removeAttr('style');
                $mapContainer.toggleClass('view-data-grid').removeAttr('style');
                element.find('.grid').floatThead('reflow');
                //Timeout adicionado pois o mapa precisa de um tempo para conseguir fazer o resize no click da grid.
                setTimeout(() => { scope.Mapa.Resize(); }, 300);
            };

            scope.onEnd = () => {
                $timeout(() => {
                    var $table = element.find('.grid');
                    $table.floatThead({
                        scrollContainer: ($table) => { return $table.closest('.scroll-table'); }
                    });
                    element.find('.grid').floatThead('reflow');
                }, 1);
            };

            function scrollGrid() {
                $(".scroll-table").on('scroll', evt => {
                    if (scope.ordenou) scope.ordenou = false;
                    else if (scope.vm.dataGrid.length == scope.vm.dataGrid[0].totalNumGrid) return;
                    else if (($(evt.target).scrollTop() + $(evt.target).height()) == $(".scroll-table").prop("scrollHeight")) {
                        scope.vm.dataGrid = scope.vm.dataGrid.concat(scope.vm.resultGridPendente);

                        if (scope.vm.skipGrid < scope.vm.quantidadeTotal) {
                            $("footer:visible .loading-inlog-modulo").fadeIn();
                            scope.vm.skipGrid += scope.vm.takeGrid;
                            scope.vm.takeGrid = scope.vm.configuracoesGerais.PaginacaoGrid;

                            scope.vm.consultaGrid();
                        }
                        if (scope.vm.resultGridPendente.length > 0)
                            scope.$apply();

                        scope.vm.resultGridPendente = [];
                    }
                })
            }
        }
        return directive;
    }

    angular
        .module('editorRotas')
        .directive('repeatEnd', repeatEnd);

    function repeatEnd() {
        var directive = {
            restrict: 'A',
            link: (scope, element, attrs) => {
                if (scope.$last) scope.$eval(attrs.repeatEnd);
            }
        };
        return directive;
    }


})();
