(function () {
    "use strict";

    angular.module('pos').controller('notaFiscalDetailController', controller);
    controller.$inject = ['$scope', '$state', '$stateParams', '$alert', '$window', 'notaFiscalService', '$interval', 'saidaService', '$location', 'notaFiscalComplementarService', '$confirm'];

    function controller($scope, $state, $stateParams, $alert, $window, notaFiscalService, $interval, saidaService, $location, notaFiscalComplementarService, $confirm) {
        $scope.$parent.initializeLayout('Nota Fiscal');

        //[Inicializa objetos]
        $scope.state = {
            data: {
                Numero: decodeURIComponent($stateParams.numero),
                Serie: {
                    Codigo: decodeURIComponent($stateParams.serie)
                },
                Terminal: { Codigo: decodeURIComponent($stateParams.terminal) },
                NFE: { Chave: decodeURIComponent($stateParams.chave) }
            },
            carregando: false,
            vazio: false,
            tabCorrente: 0,
            imposto: { index: -1, ativo: false },
            notasAtivo: false,
            justificativa: '',
            motivoInutilizacao: '',
            modalCancelamento: false,
            modalEnviarSefaz: false,
            ModalRejeicao: false,
            NotasComplementares: {}

        };
        $scope.auxiliar = {
            modaldanfe: false,
        };

        //[Inicializa funcões]
        $scope.initialize = function () {
            $scope.refresh();
        };
        $scope.historyBack = function () {
            $window.history.back();
        }

        $scope.get = function () {
            $scope.state.carregando = true;
            $scope.state.vazio = false;

            if ($scope.state.data.NFE.Chave) {
                notaFiscalService
                    .getByTerminalChave($scope.state.data.Numero, $scope.state.data.Serie.Codigo, $scope.state.data.Terminal.Codigo, $scope.state.data.NFE.Chave)
                    .then(
                        function (response) {
                            if (response.Status < 0)
                                $alert({ text: response.Message, title: $scope.Title });
                            else {
                                $scope.state.data = response.Data;
                                $scope.GetUltimoPdfCorrecaoNfe();
                            }

                            $scope.state.carregando = false;
                            $scope.state.vazio = (!response.Data);
                            $scope.GetListaNotaComplementar();
                        },
                        function (error) {
                            $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                            $scope.state.carregando = false;
                            $scope.state.vazio = false;
                        }
                    );
            }
            else {
                notaFiscalService
                    .get($scope.state.data.Numero, $scope.state.data.Serie.Codigo)
                    .then(
                        function (response) {
                            if (response.Status < 0)
                                $alert({ text: response.Message, title: $scope.Title });
                            else {
                                $scope.state.data = response.Data;
                                $scope.GetUltimoPdfCorrecaoNfe();
                            }

                            $scope.state.carregando = false;
                            $scope.state.vazio = (!response.Data);
                            $scope.GetListaNotaComplementar();
                        },
                        function (error) {
                            $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                            $scope.state.carregando = false;
                            $scope.state.vazio = false;
                        }
                    );
            }
        };
        $scope.refresh = function () {
            $scope.get();
        };
        $scope.GetUltimoPdfCorrecaoNfe = function () {
            var notaFiscal = $scope.state.data;

            if (notaFiscal && notaFiscal.NumeroModeloFiscal == '55') {
                notaFiscalService.GetUltimoPdfCorrecaoNfe(notaFiscal).then(
                    function (response) {
                        if (response.Status < 0) {
                            $scope.state.ultimoPDFCorrecao = null;
                        }
                        else {
                            $scope.state.ultimoPDFCorrecao = response.Data;
                        }
                    },
                    function (error) {
                        $scope.state.ultimoPDFCorrecao = null;
                    }
                );
            }
        };

        $scope.toggleModalCancelamento = function () {
            if ($scope.state.modalCancelamento == true)
                $scope.state.modalCancelamento = false;
            else
                $scope.state.modalCancelamento = true;
        };
        $scope.toggleModalEnviarsefaz = function () {
            if ($scope.state.modalEnviarsefaz == true)
                $scope.state.modalEnviarsefaz = false;
            else
                $scope.state.modalEnviarsefaz = true;
        };
        $scope.toggleModalReenviarsefaz = function () {
            if ($scope.state.modalReenviarsefaz == true)
                $scope.state.modalReenviarsefaz = false;
            else
                $scope.state.modalEReeviarsefaz = true;
        };
        $scope.toggleModalCorrecao = function () {
            if ($scope.state.modalCorrecao == true)
                $scope.state.modalCorrecao = false;
            else
                $scope.state.modalCorrecao = true;
        };

        var intervalPromise;

        $scope.iniciar = function () {
            intervalPromise = $interval(function () {
                $scope.CancelarNota();
            }, 1000);
        };

        $scope.continue = false;
        $scope.CancelarNota = function () {

            $scope.state.carregando = true;
            $interval.cancel(intervalPromise);
            var nf = $scope.state.data.Numero;
            if ($scope.state.data.IDCFSAT != null && $scope.state.data.IDCFSAT != "")
                nf = $scope.state.data.IDCFSAT;
            //chama o servidor se for ok vc chama a funcao 
            notaFiscalService.GetStatusCancelamentoByChaveNFE($scope.state.data.NFE.Chave).then(
                function (response) {
                    if (response.Status < 0)
                        $alert({ text: response.Message, title: $scope.Title });
                    else {
                        if (response.Data) {
                            ;
                            if ((response.Data == "1" || response.Data == "2") && $scope.continue) {
                                $scope.$parent.toastr.success('Nota Cancelada!');
                                if (response.Data == "2")
                                    $scope.$parent.toastr.error('Não foi possivel realizar estornos de creditos ou resgate!');
                                else {
                                    if ($scope.$parent.config.Fidelidade.Ativo && ($scope.state.data.NumeroModeloFiscal == '59' || $scope.state.data.NumeroModeloFiscal == '65')) {
                                        $scope.$parent.toastr.success('Estorno de créditos efetuado!');
                                    }
                                }
                                $scope.state.carregando = false;
                                $scope.toggleModalCancelamento();
                                $scope.continue = false;
                                $interval.cancel(intervalPromise);
                                $scope.initialize();
                                return;
                            }
                            else {
                                ;
                                if ($scope.continue) {
                                    $scope.$parent.toastr.error('Não foi possivel cancelar nota ! ' + response.Data);
                                    $scope.state.carregando = false;
                                    $scope.toggleModalCancelamento();
                                    $scope.continue = false;
                                    $interval.cancel(intervalPromise);
                                    return;
                                }

                            }
                        }
                    }

                    if ($scope.continue)
                        $scope.iniciar();
                },
                function (error) {
                    $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                    $scope.state.carregando = false;
                    if ($scope.continue)
                        $scope.iniciar();
                }
            );
        };

        $scope.AbreModalRejeicao = function () {
            if ($scope.state.data.NFE.Status == "59")
                $scope.$parent.toastr.error('Esta nota ja foi Inutilizada!');
            else
                $scope.AbreModalRejeicao();
        };

        $scope.InutilizarNotaClick = function () {

            //$scope.toggleModalCancelamento();

            if ($scope.state.motivoInutilizacao.length < 15 || $scope.state.motivoInutilizacao.length > 255) {
                $scope.$parent.toastr.error("Voce deve digitar entre 15 e 255 caracteres na justificativa!");
                return;
            }

            $scope.state.carregando = true;
            if (!$scope.state.motivoInutilizacao) {
                $scope.$parent.toastr.error("Voce deve digiar um motivo!");
                $scope.state.carregando = false;
                return;
            }
            $scope.state.carregandoOMNI = true;
            notaFiscalService.InutilizarNota($scope.state.data.Numero, $scope.state.data.Serie.Codigo, $scope.state.motivoInutilizacao).then(
                function (response) {
                    if (response.Status < 0)
                        $alert({ text: response.Message, title: $scope.Title });
                    else {
                        $scope.initialize();
                        $scope.$parent.toastr.success("Nota inutilizada com sucesso!", 'Serviço');
                    }
                    $scope.state.carregandoOMNI = false;
                    $scope.AbreModalRejeicao();
                },
                function (error) {
                    $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                    $scope.state.carregandoOMNI = false;
                    $scope.AbreModalRejeicao();
                }
            );


        };

        $scope.AbreModalRejeicao = function () {
            if ($scope.state.ModalRejeicao == true)
                $scope.state.ModalRejeicao = false;
            else
                $scope.state.ModalRejeicao = true;
        };

        $scope.AbreModalCancelamento = function () {
            if ($scope.state.data.NFE.Status == "49")
                $scope.$parent.toastr.error('Esta nota ja foi cancelada!');
            else
                $scope.toggleModalCancelamento();

        };

        $scope.AbreModalCorrecao = function () {
            if ($scope.state.data.NFE.Status != "5")
                $scope.$parent.toastr.error('Esta nota não foi aprovada!');
            else
                $scope.toggleModalCorrecao();

        };

        $scope.InterromperProcesso = function () {

            notaFiscalService
                .DeleteByChaveNFE($scope.state.data.NFE.Chave)
                .then(
                    function (response) {
                        if (response.Status < 0)
                            $alert({ text: response.Message, title: $scope.Title });
                        else
                            $scope.state.data = response.Data;

                        $scope.state.carregando = false;
                        $scope.state.vazio = (!response.Data);
                    },
                    function (error) {
                        $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                        $scope.state.carregando = false;
                        $scope.state.vazio = false;
                    }
                );

            $scope.state.carregando = false;
            $scope.toggleModalCancelamento();
            $scope.continue = false;
        };

        $scope.CancelarNotaClick = function () {

            //$scope.toggleModalCancelamento();

            if ($scope.state.justificativa.length < 15 || $scope.state.justificativa.length > 255) {
                $scope.$parent.toastr.error("Você deve digitar entre 15 e 255 caracteres na justificativa!");
                return;
            };

            $scope.state.carregando = true;
            if (!$scope.state.justificativa) {
                $scope.$parent.toastr.error("Você deve digitar a justificativa!");
                $scope.state.carregando = false;
                return;
            };
            var nf = $scope.state.data.Numero;
            if ($scope.state.data.IDCFSAT != null && $scope.state.data.IDCFSAT != "")
                nf = $scope.state.data.IDCFSAT;
            if ($scope.state.data.Romaneio != null && $scope.state.data.Romaneio != "") {
                $confirm({ text: "Esta nota possui o romaneio " + $scope.state.data.Romaneio + " ele sera cancelado junto com a nota, tem certeza?" }).then(function () { ; CancelarNota(nf); });

            }
            else {
                CancelarNota(nf);
            }

        };
        function CancelarNota(nf) {
            
            notaFiscalService.InserirCancelamento(nf, $scope.state.data.Serie.Codigo, $scope.state.justificativa, $scope.state.data.Terminal.Codigo).then(
                function (response) {
                    if (response.Status < 0)
                        $alert({ text: response.Message, title: $scope.Title });
                    else {
                        ;
                        if (response.Message == '') {
                            $scope.continue = true;
                            $scope.CancelarNota();

                        }
                        else {
                            $scope.$parent.toastr.success(response.Message);
                            $scope.toggleModalCancelamento();
                            $scope.initialize();
                        }
                    }
                },
                function (error) {
                    $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                    $scope.state.carregando = false;
                }
            );
        }

        $scope.CorrigirNotaClick = function () {
            if (!$scope.state.notaCorrecoes) {
                $scope.$parent.toastr.error("Você deve digitar as correções!");
                $scope.state.carregando = false;
                return;
            }

            if ($scope.state.notaCorrecoes.length < 15 || $scope.state.notaCorrecoes.length > 1000) {
                $scope.$parent.toastr.error("Você deve digitar entre 15 e 1000 caracteres na descrição das correções!");
                return;
            }

            var notaFiscal = $scope.state.data;
            var correcoes = $scope.state.notaCorrecoes;

            $scope.state.carregando = true;

            notaFiscalService.SendCorrecaoNFE(notaFiscal, correcoes).then(
                function (response) {
                    if (response.Status < 0) {
                        $alert({ text: response.Message, title: $scope.Title });
                        $scope.state.carregando = false;
                    }
                    else {
                        $scope.$parent.toastr.success(response.Message, "Correção OK!");
                        $scope.GetUltimoPdfCorrecaoNfe();
                        $scope.state.notaCorrecoes = '';
                        $scope.state.carregando = false;
                        $scope.toggleModalCorrecao();
                    }
                },
                function (error) {
                    $scope.state.carregando = false;
                    $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                }
            );
        };

        $scope.toggleNotas = function () {
            $scope.state.notasAtivo = !$scope.state.notasAtivo;
        };
        $scope.toggleImposto = function (index) {
            $scope.state.imposto.index = index;
            $scope.state.imposto.ativo = !$scope.state.imposto.ativo;
        };
        $scope.setNextImposto = function () {
            if ($scope.state.imposto.index < ($scope.state.data.Itens.length - 1))
                $scope.state.imposto.index++;
        };
        $scope.setPriorImposto = function () {
            if ($scope.state.imposto.index > 0)
                $scope.state.imposto.index--;
        };

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

                // var blob = new Blob([$scope.formatXml($scope.state.data.Xml)], { type: "text/xml;charset=utf-8;" });
                var url = window.URL.createObjectURL(blob);
                var filename = "Xml" + $scope.state.data.Numero;

                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);
            }
            if ($scope.state.data.XmlCancelamento)
                $scope.downloadXmlCancelamento();
        };

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

                //var blob = new Blob([$scope.formatXml($scope.state.data.XmlCancelamento)], { type: "text/xml;charset=utf-8;" });
                var url = window.URL.createObjectURL(blob);
                var filename = "XmlCancelamento" + $scope.state.data.Numero;

                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);
            }
        };

        $scope.formatXml = function (xml) {
            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.EnviaNotaSefaz = function () {
            $scope.state.modalEnviarsefaz = true;
            $scope.state.carregandoEnviarSefaz = true;
            notaFiscalService
                .EnviaNotaSefaz($scope.state.data.Numero, $scope.state.data.Serie.Codigo, $scope.state.data.Filial.Nome)
                .then(
                    function (response) {
                        if (response.Status < 0) {
                            $scope.state.carregandoEnviarSefaz = false;
                            $scope.state.modalEnviarsefaz = false;
                            $scope.$parent.toastr.error(response.Message, 'Encerramento NF de saída');
                        } else {
                            //$scope.state.data = response.Data;
                            $scope.state.carregandoEnviarSefaz = false;
                            $scope.state.modalEnviarsefaz = false;
                            $scope.$parent.toastr.clear();
                            $scope.$parent.toastr.success("NF Gerada com sucesso.");
                            $scope.state.data = response.Data;
                            $interval($scope.initialize(), 1000);
                        }
                    },
                    function (error) {
                        $scope.state.carregandoEnviarSefaz = false;
                        $scope.state.modalEnviarsefaz = false;
                        $scope.$parent.toastr.error(error, 'Comunicação com o servidor');
                    }
                );
        }

        $scope.PdfFileText = function () {
            return $scope.state.data.PDFFile;
            //currentBlob = new Blob(text, { type: 'application/pdf' });
            //return URL.createObjectURL(currentBlob);
        };

        $scope.PdfCorrecaoText = function () {
            return $scope.state.ultimoPDFCorrecao;
            //currentBlob = new Blob(text, { type: 'application/pdf' });
            //return URL.createObjectURL(currentBlob);
        };

        $scope.toggledanfe = function () {
            $scope.auxiliar.modaldanfe = !$scope.auxiliar.modaldanfe;
        };

        $scope.toogleModalPDFCorrecao = function () {
            $scope.auxiliar.modalPDFCorrecao = !$scope.auxiliar.modalPDFCorrecao;
        };

        $scope.imprimir = function () {
            var divToPrint = document.getElementById('impressao');
            var newWin = window.open('', 'Print-Window');

            newWin.document.open();
            newWin.document.write('<html><head>' + getStyle() + '</head><body onload="window.print()">' + divToPrint.innerHTML + '</body></html>');
            newWin.document.close();

            setTimeout(function () {
                newWin.close();
            }, 10);
        }
        var getStyle = function () {

            return "<link href='/content/css/bootstrap.paper.min.css' rel='stylesheet' type='text/css'> " +
                "<link href='/content/css/bootstrap.grid.custom.min.css' rel='stylesheet'> " +
                "<link href='/content/css/font-awesome.min.css' rel='stylesheet' type='text/css'> " +
                "<link href='/content/css/animate.min.css' rel='stylesheet' type='text/css'> " +
                "<link href='/content/css/angular-toast.min.css' rel='stylesheet'> " +
                "<link href='/content/css/material-icons.css' rel='stylesheet'> " +
                "<link href='/content/css/site-lightblue.css' title='prefered' rel='stylesheet' type='text/css'> " +
                "<link href='/content/css/Dev.css' rel='stylesheet'> " +
                "<base href='/'> ";
        };

        $scope.visualizarDanfe = function () {
            console.log("ok");
        };

        $scope.abrirCliente = function () {
            $state.go("state-cliente-edit", {
                id: $scope.state.data.Cliente.Codigo,
            });
        };

        $scope.reenviarNota = function () {
            $scope.state.modalReenviarsefaz = true;
            $scope.state.carregandoReenviarSefaz = true;
            notaFiscalService.ReenviaNotaSefaz($scope.state.data.Numero, $scope.state.data.Serie.Codigo, $scope.state.data.Filial.Nome).then(
                function (response) {
                    if (response.Status < 0) {
                        $scope.state.modalReenviarsefaz = false;
                        $scope.state.carregandoReenviarSefaz = false;
                        $alert({ text: response.Message, title: $scope.Title });
                    } else {
                        $scope.state.modalReenviarsefaz = false;
                        $scope.state.carregandoReenviarSefaz = false;
                        $scope.state.data = response.Data;
                        $interval($scope.initialize(), 1000);
                    }
                },
                function (error) {
                    $scope.state.modalReenviarsefaz = false;
                    $scope.state.carregandoReenviarSefaz = false;
                    $scope.$parent.toastr.error(error, 'Serviço');
                });
        };

        $scope.ReenvioForcado = function () {
            $scope.state.modalReenviarsefaz = true;
            $scope.state.carregandoReenviarSefaz = true;
            notaFiscalService.ReenvioForcado($scope.state.data.Numero, $scope.state.data.Serie.Codigo, $scope.state.data.Filial.Nome).then(
                function (response) {
                    if (response.Status < 0) {
                        $scope.state.modalReenviarsefaz = false;
                        $scope.state.carregandoReenviarSefaz = false;
                        $alert({ text: response.Message, title: $scope.Title });
                    } else {
                        $scope.state.modalReenviarsefaz = false;
                        $scope.state.carregandoReenviarSefaz = false;
                        $scope.state.data = response.Data;
                        $interval($scope.initialize(), 1000);
                    }
                },
                function (error) {
                    $scope.state.modalReenviarsefaz = false;
                    $scope.state.carregandoReenviarSefaz = false;
                    $scope.$parent.toastr.error(error, 'Serviço');
                });
        };

        $scope.editarNota = function () {
            $state.go('state-consumivel-edit', { id: $scope.state.data.ConsumivelID });
        };

        $scope.GerarNotaComplementar = function () {
            notaFiscalComplementarService.create($scope.state.data).then(
                function (response) {
                    if (response.Status < 0)
                        $alert({ text: response.Message, title: $scope.Title });
                    else {
                        var newId = response.Data.Id;
                        $state.go("state-nfcomplementar-edit", {
                            codigo: newId,
                        });
                    }
                },
                function (error) {
                    $scope.$parent.toastr.error(error, 'Serviço');
                });
        };

        $scope.GetListaNotaComplementar = function () {
            notaFiscalComplementarService.getByOrigem($scope.state.data).then(
                function (response) {
                    if (response.Status < 0)
                        $alert({ text: response.Message, title: $scope.Title });
                    else {
                        $scope.state.NotasComplementares = response.Data;
                    }
                },
                function (error) {
                    $scope.$parent.toastr.error(error, 'Serviço');
                });
        };

        $scope.goToNotaComplementar = function (id, status) {
            if (status)
                return;
            $state.go("state-nfcomplementar-edit", {
                codigo: id
            });
        };

        /*Inicializa funções*/
        $scope.initialize();
    }

})();