public async Task <Core.NotasFiscais.NotaFiscal> EnviarNota(NotaFiscalModel notaFiscalModel, Modelo modelo)
        {
            notaFiscalModel.ValidateModel();

            if (notaFiscalModel.HasErrors)
            {
                throw new ArgumentException("Nota fiscal contém erros de validação não resolvidos.");
            }

            if (notaFiscalModel.Pagamentos[0].FormaPagamento != "Sem Pagamento" &&
                notaFiscalModel.Produtos.Sum(c => c.QtdeProduto * c.ValorUnitario) !=
                notaFiscalModel.Pagamentos.Sum(p => p.QtdeParcelas * p.ValorParcela))
            {
                await _dialogService.ShowError("Valor total da nota não corresponde ao valor de pagamento.",
                                               "Erro!", "Ok", null);

                throw new ArgumentException("Valor total da nota não corresponde ao valor de pagamento.");
            }

            Core.NotasFiscais.NotaFiscal notaFiscal = null;
            var config   = _configuracaoService.GetConfiguracao();
            var ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao;

            await Task.Run(() =>
            {
                var modeloNota = modelo;
                const TipoEmissao tipoEmissao = TipoEmissao.Normal; //verificar status do serviço e etc
                var destinatario   = GetDestinatario(notaFiscalModel, ambiente, modelo);
                var documentoDanfe =
                    destinatario != null ? destinatario.DocumentoDanfe : "CPF"; //Encapsular isso aqui
                var emitente = _emissorService.GetEmissor();
                var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), emitente.Endereco.UF);

                var identificacao = GetIdentificacao(notaFiscalModel, codigoUF, DateTime.Now, emitente, modeloNota,
                                                     Convert.ToInt32(notaFiscalModel.Serie), notaFiscalModel.Numero, tipoEmissao, ambiente, documentoDanfe);
                var produtos      = GetProdutos(notaFiscalModel, config);
                var pagamentos    = GetPagamentos(notaFiscalModel);
                var totalNFe      = GetTotalNFe(notaFiscalModel);
                var infoAdicional = new InfoAdicional(produtos);
                var transporte    = GetTransporte(notaFiscalModel, modelo);

                notaFiscal = new Core.NotasFiscais.NotaFiscal(emitente, destinatario, identificacao, transporte,
                                                              totalNFe, infoAdicional, produtos, pagamentos);

                var cscId = ambiente == Ambiente.Homologacao ? config.CscIdHom : config.CscId;
                var csc   = ambiente == Ambiente.Homologacao ? config.CscHom : config.Csc;
                _enviaNotaFiscalService.EnviarNotaFiscal(notaFiscal, cscId, csc);
            });

            NotaEnviadaEvent(notaFiscal);
            return(notaFiscal);
        }
        private async void EnviarNotaNovamenteCmd_ExecuteAsync(NotaFiscalMemento notaPendenteMemento)
        {
            IsBusy      = true;
            BusyContent = "Enviando...";

            var config = _configuracaoService.GetConfiguracao();

            var modelo = notaPendenteMemento.Tipo == "NFC-e" ? Modelo.Modelo65 : Modelo.Modelo55;

            //Preencher objeto da NotaFiscal a partir do XML e enviar para a correspondente ViewModel NFe ou NFCe
            var app        = Application.Current;
            var mainWindow = app.MainWindow;

            if (!_consultaStatusServicoService.ExecutarConsultaStatus(config, modelo))
            {
                MessageBox.Show(mainWindow,
                                "Serviço continua indisponível. Aguarde o reestabelecimento da conexão e tente novamente.",
                                "Erro de conexão ou serviço indisponível", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var ambiente     = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao;
            var notaFiscalDb = _notaFiscalRepository.GetNotaFiscalByChave(notaPendenteMemento.Chave);
            var xml          = await notaFiscalDb.LoadXmlAsync();

            var notaFiscalBo = _notaFiscalRepository.GetNotaFiscalFromNfeProcXml(xml);

            notaFiscalBo.Identificacao.DataHoraEmissao = DateTime.Now;

            foreach (var prod in notaFiscalBo.Produtos)
            {
                var produtoDb = _produtoService.GetByCodigo(prod.Codigo);
                prod.Id = produtoDb.Id;
            }

            try
            {
                var cscId = ambiente == Ambiente.Homologacao ? config.CscIdHom : config.CscId;
                var csc   = ambiente == Ambiente.Homologacao ? config.CscHom : config.Csc;

                _notaFiscalRepository.ExcluirNota(notaPendenteMemento.Chave, ambiente);
                _enviaNotaFiscalService.EnviarNotaFiscal(notaFiscalBo, cscId, csc);

                IsBusy = false;

                var mbResult = MessageBox.Show(mainWindow, "Nota enviada com sucesso! Deseja imprimi-la?",
                                               "Emissão NFe", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);

                if (mbResult == MessageBoxResult.Yes)
                {
                    BusyContent = "Gerando impressão...";
                    IsBusy      = true;
                    await GeradorPDF.GerarPdfNotaFiscal(notaFiscalBo);
                }

                IsBusy = false;

                var          notaIndex = NotasFiscais.IndexOf(notaPendenteMemento);
                Destinatario destinatario;
                var          destinatarioUf = notaFiscalBo.Emitente.Endereco.UF;

                if (notaFiscalBo.Destinatario != null)
                {
                    destinatario   = notaFiscalBo.Destinatario;
                    destinatarioUf = destinatario.Endereco != null ? destinatario.Endereco.UF : destinatarioUf;
                }
                else
                {
                    destinatario = new Destinatario("CONSUMIDOR NÃO IDENTIFICADO");
                }

                var valorTotalProdutos = notaFiscalBo.ValorTotalProdutos.ToString("N2", new CultureInfo("pt-BR"));

                var notaMemento = new NotaFiscalMemento(notaFiscalBo.Identificacao.Numero,
                                                        notaFiscalBo.Identificacao.Modelo, notaFiscalBo.Identificacao.DataHoraEmissao,
                                                        notaFiscalBo.DataHoraAutorização, destinatario.NomeRazao, destinatarioUf, valorTotalProdutos,
                                                        notaFiscalBo.Identificacao.Status, notaFiscalBo.Identificacao.Chave);

                NotasFiscais[notaIndex] = notaMemento;
                NotaPendenteReenviadaEvent(notaFiscalBo);
            }
            catch (Exception e)
            {
                log.Error(e);
                MessageBox.Show(mainWindow,
                                "Ocorreram os seguintes erros ao tentar enviar a nota fiscal:\n\n" + e.InnerException.Message,
                                "Erro", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }