(function () {
    "use strict";

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

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

        $scope.printPdf = function (showDetails) {
            $timeout(function () {
                window.print();
            }, 2000);
        };

        $scope.Title = 'Relatório Notas de Contingenciamento'

        $scope.state = {
            filtro: {
                emissao: {},
                ativo: false
            },
            data: [],
            carregando: false,
            xml: {},
            filter: {},
            skip: 0,
            take: 20
        }
        $scope.auxiliar = {
            modalxml: false,
            modalDownload: false
        };

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

            return dateWithoutTime;
        }

        $scope.getMore = function () {
            $scope.state.skip += $scope.state.take;
            relatorioService
                .getAllNotaContingencia(null, null, $scope.state.skip, $scope.state.take)
                .then(
                    function (response) {
                        if (response.Status < 0) {
                            $scope.$parent.toastr.error(response.Message, 'Carregando');
                            console.error(response.Exception);
                        }
                        else {
                            $scope.state.data = $scope.state.data.concat(response.Data);
                        }
                    },
                    function (error) {
                        $scope.$parent.toastr.error('Ao carregar 2.', 'Comunicação com o servidor');
                        console.error(error);
                    }
                );
        };

        var getAll = function () {
            $scope.state.carregando = true;
            relatorioService
                .getAllNotaContingencia($scope.state.filtro.emissao.de, $scope.state.filtro.emissao.ate, $scope.state.skip, $scope.state.take)
                .then(
                    function (response) {
                        if (response.Status < 0) {
                            $scope.$parent.toastr.error(response.Message, 'Carregando');
                            console.error(response.Exception);
                        }
                        else {
                            angular.copy(angular.fromJson(response.Data), $scope.state.data);
                        }
                        $scope.state.carregando = false;
                    },
                    function (error) {
                        $scope.$parent.toastr.error('Ao carregar 2.', 'Comunicação com o servidor');
                        console.error(error);
                        $scope.state.tickets.chart.carregando = false;
                    }
                );
        };

        $scope.refresh = function () {
            $scope.state.skip = 0;
            $scope.state.take = 20;

            if ($scope.state.filtro.emissao.de) {
                var emissaoDe = $scope.state.filtro.emissao.de;
                var emissaoDeNoTime = getDateWithoutTime(emissaoDe);
                $scope.state.filtro.emissao.de = emissaoDeNoTime;
            }

            if ($scope.state.filtro.emissao.ate) {
                var emissaoAte = $scope.state.filtro.emissao.ate;
                var emissaoAteNoTime = getDateWithoutTime(emissaoAte);
                $scope.state.filtro.emissao.ate = emissaoAteNoTime;
            }

            getAll();
        }

        $scope.toggleFilter = function () {
            $scope.state.filtro.ativo = !$scope.state.filtro.ativo;
        }

        $scope.clearFilter = function () {
            if ($scope.$parent.config.VisualizaVendasDia)
                $scope.state.filtro.emissao.de = new Date();
        }

        $scope.initialize = function () {
            $scope.clearFilter();
            //$scope.setTerminal();
            getAll();
        };

        $scope.DownloadXml = function (numero, codigo, filial) {
            $scope.togglemodalxml();
            $scope.state.filter = { "numero": numero, "codigo": codigo, "filial": filial }
            saidaService
               .GetXmlSefaz(numero, codigo, filial)
                .then(
                    function (response) {
                        if (response.Status < 0)
                            $scope.$parent.toastr.error(response.Message, '');
                        else {
                            $scope.auxiliar.xml = response.Data;
                        }
                    },
                    function (error) { $scope.$parent.toastr.error(error, 'Comunicação com o servidor'); }
                );

        }

        $scope.formatXml = function (xml) {
            if (!xml)
                return "";
            var formatted = '';
            var reg = /(>)(<)(\/*)/g;
            xml = xml.replace(reg, '$1\r\n$2$3');
            var pad = 0;
            jQuery.each(xml.split('\r\n'), function (index, node) {
                var indent = 0;
                if (node.match(/.+<\/\w[^>]*>$/)) {
                    indent = 0;
                } else if (node.match(/^<\/\w/)) {
                    if (pad != 0) {
                        pad -= 1;
                    }
                } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
                    indent = 1;
                } else {
                    indent = 0;
                }

                var padding = '';
                for (var i = 0; i < pad; i++) {
                    padding += '  ';
                }

                formatted += padding + node + '\r\n';
                pad += indent;
            });

            return formatted;
        }
        $scope.toggleDownloadAll = function () {
            $scope.auxiliar.modalDownload = !$scope.auxiliar.modalDownload;
        }
        $scope.downloadFile = function () {
            saidaService
              .GetXmlSefazDownload($scope.state.filter.numero, $scope.state.filter.codigo, $scope.state.filter.filial).success(function (data, status, headers) {
                  headers = headers();

                  var filename = "Xml" + $scope.state.filter.numero;
                  var contentType = headers['content-type'];

                  var linkElement = document.createElement('a');
                  try {
                   //   var blob = new Blob([data], { type: contentType });
                      var blob = new Blob([new Uint8Array([0xEF, 0xBB, 0xBF]), data.replace(/^\s+|\s+$/g, '')], { type: "text/xml;charset=UTF-8;" });

                      var url = window.URL.createObjectURL(blob);

                      linkElement.setAttribute('href', url);
                      linkElement.setAttribute("download", filename);

                      var clickEvent = new MouseEvent("click", {
                          "view": window,
                          "bubbles": true,
                          "cancelable": false
                      });
                      linkElement.dispatchEvent(clickEvent);
                  } catch (ex) {
                      console.log(ex);
                  }
              }).error(function (data) {
                  console.log(data);
              });

        };

        $scope.togglemodalxml = function () {
            $scope.auxiliar.modalxml = !$scope.auxiliar.modalxml;
        };

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

        $scope.ziparXML = function (inicio, fim) {
            inicio = (!inicio ? "" : inicio);
            fim = (!fim ? "" : fim);
            console.log("/download/ZiparXML/" + formatDate(inicio) + "/" + formatDate(fim));
            var win = window.open("/download/ZiparXML/" + formatDate(inicio) + "/" + formatDate(fim), '_blank');
            win.focus();
        };

        $scope.xmlPorEmail = function (email, inicio, fim) {
            inicio = (!inicio ? "" : inicio);
            fim = (!fim ? "" : fim);
            $scope.$parent.toastr.success('Estamos processando sua requisição, em breve enviaremos os XMLs por email.');
            $scope.toggleDownloadAll()
            relatorioService
              .xmlPorEmail(email, inicio, fim).then(function (data, status, headers) {
                  $scope.$parent.toastr.success('Email enviado com sucesso.');
              }, function (data) {
                  $scope.$parent.toastr.error('Um problema ocorreu durante o envio do email, refaça a operação, ou faça download.', 'Erro');
              });
        };

        var formatDate = function (date) {
            if (date == "")
                return "";
            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
        }

        $scope.exportarExcel = function (inicio, fim) {
            inicio = (!inicio ? "" : inicio);
            fim = (!fim ? "" : fim);

            var win = window.open("/download/ExportarExcel/" + formatDate(inicio) + "/" + formatDate(fim), '_blank');
            win.focus();
        };

        $scope.exportarCSV = function (inicio, fim) {
            inicio = (!inicio ? "" : inicio);
            fim = (!fim ? "" : fim);

            var win = window.open("/download/ExportarCSV/" + formatDate(inicio) + "/" + formatDate(fim), '_blank');
            win.focus();
        };

        $scope.initialize();

    }

})();