(function () {
    "use strict";

    angular.module('pos').controller('relatorioVendaPorVendedorController', controller);
    controller.$inject = ['$scope', '$window', '$state', '$timeout', 'relatorioService'];



  


    function controller($scope, $window, $state, $timeout, relatorioService) {
        $scope.$parent.initializeLayout('Relatório');

        //imprime o relatório
        $scope.printPdf = function (showDetails) {
            $timeout(function () {
                window.print();
            }, 2000);
        };

        $scope.exibeTrocas = false;
        $scope.state = {
            tickets: {
                chart: { data: [], carregando: false, vazio: true },
                report: { data: [], carregando: false, vazio: true },
                filtro: {},
            },
            carregando: 0,
            showData: [],
            init: true,
            restricoes: false,
        }

        $scope.initialize = function () {
            setRestricoesRelatorio();
            $scope.setTerminal();
            $scope.clearFilter();

        };

        var setRestricoesRelatorio = function () {
            var state = $state.current.name;

            if (state == "state-venda-por-vendedor")
                $scope.state.restricoes = true;
        }

        $scope.historyBack = function () {
            $window.history.back();
        };

        $scope.setTerminal = function () {
            $scope.state.tickets.filtro.codigoTerminal = $scope.$parent.config.Terminal.Codigo;
        };

        $scope.changeStatus = function (i) {
            $scope.state.showData[i] = !$scope.state.showData[i];
            $scope.state.init = false;
        }

        $scope.chartTicketByVendedor = function () {
            $scope.state.carregando += 1;
            $scope.state.tickets.chart.carregando = true;
            $scope.state.tickets.chart.vazio = false;
            $scope.state.tickets.filtro.troca = $scope.exibeTrocas;
            relatorioService
                .chartTicketByVendedor($scope.state.tickets.filtro)
                .then(
                    function (response) {
                        $scope.state.carregando -= 1;
                        if (response.Status < 0) {
                            $scope.$parent.toastr.error(response.Message, 'Carregando gráfico');
                            console.error(response.Exception);
                        }
                        else {
                            angular.copy(angular.fromJson(response.Data), $scope.state.tickets.chart.data);
                            $scope.state.tickets.chart.vazio = $scope.$parent.tools.buildChart('#chart-ticket', '', response.Data, true);
                        }
                        $scope.state.tickets.chart.carregando = false;
                    },
                    function (error) {
                        $scope.state.carregando -= 1;
                        $scope.$parent.toastr.error('Ao carregar o gráfico.', 'Comunicação com o servidor');
                        console.error(error);
                        $scope.state.tickets.chart.carregando = false;
                    }
                );
        };
        $scope.getTicketByVendedor = function () {
            $scope.state.carregando += 1;
            $scope.state.tickets.report.carregando = true;
            $scope.state.tickets.report.vazio = false;

            $scope.state.tickets.filtro.troca = $scope.exibeTrocas;

            relatorioService
                .getVendas($scope.state.tickets.filtro)
                .then(
                    function (response) {
                        $scope.state.carregando -= 1;
                        if (response.Status < 0) {
                            $scope.$parent.toastr.error(response.Message, 'Serviço');
                            console.error(response.Exception);
                        }
                        else {
                            angular.copy(angular.fromJson(response.Data), $scope.state.tickets.report.data);
                            $scope.state.tickets.report.vazio = (!response.Data || response.Data.length == 0);
                        }
                        $scope.state.tickets.report.carregando = false;
                    },
                    function (error) {
                        $scope.state.carregando -= 1;
                        $scope.$parent.toastr.error('Ao carregar o gráfico.', 'Comunicação com o servidor');
                        console.error(error);
                        $scope.state.tickets.report.carregando = false;
                    }
                );
        };
        $scope.getSum = function (data) {
            if (!data)
                return 0;

            var sum = 0;
            for (var i = 0; i < data.length; i++)
                sum += data[i].Total;
            return sum;
        }

        $scope.toggleFilter = function () {
            $scope.state.tickets.filtro.ativo = !$scope.state.tickets.filtro.ativo;
        };
        $scope.clearFilter = function () {
            $scope.state.tickets.filtro = {
                emissao: {
                    de: new Date((new Date()).setHours(0, 0, 0, 0)),
                    ate: null
                },
                codigoTerminal: '',
                periodoFechamento: '',
                codigoVendedor: '',
                ativo: false,
            }
            $scope.refresh();
        };

        $scope.refresh = function () {
            if ($scope.state.restricoes && (!validaData($scope.state.tickets.filtro.emissao.de) || !validaData($scope.state.tickets.filtro.emissao.ate))) {
                $scope.$parent.toastr.error('Escolha um intervalo de datas que não exceda os últimos 30 dias.');
                return;
            }

            $scope.state.tickets.filtro.restricoes = $scope.state.restricoes;
            //if ($scope.state.tickets.filtro.emissao.de) {
                
            //    var emissaoDe = $scope.state.tickets.filtro.emissao.de;
            //    var emissaoDeNoTime = getDateWithoutTime(emissaoDe);
            //    if( emissaoDeNoTime != 'Invalid Date'){
            //        $scope.state.tickets.filtro.emissao.de = emissaoDeNoTime;
            //    }   
            //    else {
            //        $scope.state.tickets.filtro.emissao.de = emissaoDe;
            //    }
            //}

            //if ($scope.state.tickets.filtro.emissao.ate) {
                
            //    var emissaoAte = $scope.state.tickets.filtro.emissao.ate;
            //    var emissaoAteNoTime = getDateWithoutTime(emissaoAte);
            //    if (emissaoAteNoTime != 'invalid Date') {
            //        $scope.state.tickets.filtro.emissao.ate = emissaoAteNoTime;
            //    }
            //    else {
            //        $scope.state.tickets.filtro.emissao.ate = emissaoAte;
            //    }
            //}

            $scope.chartTicketByVendedor();
            $scope.getTicketByVendedor();
            $scope.state.showData = [];
            $scope.state.init = true;
        };

        function getDateWithoutTime(date) {
            
            var dateObj = new Date(date);
            var dateWithoutTime = dateObj.toLocaleDateString();

            return dateWithoutTime;
        }

        var validaData = function (data) {
            if (!data)
                return true;
            var hoje = new Date((new Date()).setHours(0, 0, 0, 0));
            var dias = dateDiferencaEmDias(data, hoje);
            return dias <= 30;
        }

        var dateDiferencaEmDias = function (a, b) {
            // Descartando timezone e horário de verão
            var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
            var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

            return Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24));
        }

        $scope.initialize();

    }

})();