IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_GERA_EST_NF_SAI_NF_ENT]') AND type in (N'P', N'PC'))
    DROP PROCEDURE P_GERA_EST_NF_SAI_NF_ENT 
GO

--P_GERA_EST_NF_SAI_NF_ENT 1,999,3018008,3,456 

CREATE PROCEDURE P_GERA_EST_NF_SAI_NF_ENT (@CD_EMP INT =1
										  ,@CD_FILIAL	INT 
										  ,@CD_NF_SAI	INT
										  ,@CD_NF_SERIE INT
										  ,@CD_MOV_OP	 INT )

AS
SET NOCOUNT ON;
/********************************************************************************************************************************/


DECLARE @CD_NF_NOVO INT = 0
      , @NR_NF_NOVO INT = 0
      , @DT_ENT DATE=GETDATE()
      , @mensagemErro varchar(500);


/********************************************************************************************************************************/


if exists(select * FROM 
				    EST_NF_SAI S
				    JOIN EST_NF_SAI_NF_ENT SE ON 
				    s.CD_EMP	 = SE.CD_EMP AND
				    S.CD_FILIAL = SE.CD_FILIAL AND
				    S.CD_NF	 = SE.CD_NF_SAI
				WHERE
				    S.CD_NF= @CD_NF_SAI 
				    AND S.CD_FILIAL=@CD_FILIAL
				    AND S.CD_EMP=1
				    )
begin

    print 'Nota fiscal já emitida anteriormente .. ' + convert(varchar, getdate(),108);    
    print ' CD_NF = ' + convert(varchar, @CD_NF_SAI );
    print ' CD_FILIAL = ' + convert(varchar, @CD_FILIAL);
    print '************************'
    return
end


/********************************************************************************************************************************/


begin try

/********************************************************************************************************************************/
    Print 'Gerando a numeracao da nota fical '  
/********************************************************************************************************************************/

    SET @CD_NF_NOVO=(SELECT ISNULL(MAX(CD_NF),0) + 1 FROM EST_NF_ENT
					    WHERE
						    CD_EMP =@CD_EMP
						    AND CD_FILIAL = @CD_FILIAL)
    SET @NR_NF_NOVO=(SELECT ISNULL(MAX(NR_NF),0) + 1
				    FROM EF_NF_CTR_NR WHERE CD_EMP =@CD_EMP
						    AND CD_FILIAL = @CD_FILIAL
						    AND CD_NF_SERIE=@CD_NF_SERIE)				
/******************************************************************************************************************/
 
    INSERT INTO EF_NF_CTR_NR (CD_EMP,CD_FILIAL,NR_NF,CD_NF_SERIE,NR_SELO_SAIDA,DT_CAD)
    SELECT
	   @CD_EMP AS CD_EMP,
	   @CD_FILIAL AS CD_FILIAL,
	   @NR_NF_NOVO AS NR_NF,
	   @CD_NF_SERIE AS CD_NF_SERIE,
	   0 AS NR_SELO_SAIDA,
	   GETDATE() AS DT_CAD
	    
    print 'CD_NF = ' + convert(varchar, @CD_NF_NOVO ) + ' and CD_FILIAL = ' + convert(varchar, @CD_FILIAL);
    print 'Nota.: ' + convert(varchar, @NR_NF_NOVO);
 
/********************************************************************************************************************************/
    
    print 'Inserindo o cabeçalho da nota fiscal.. ' + convert(varchar, getdate(),108);

/********************************************************************************************************************************/

    INSERT INTO EST_NF_ENT (CD_EMP,CD_FILIAL,CD_NF,CD_FORN,DT_ENT,DT_EMI_NF,NR_NF
					   ,VLR_NF,VLR_ICMS,VLR_FRETE,VLR_OUTROS,VLR_BASE_ICMS,ALIQ_ICMS,VLR_TOT_PROD,CD_NT_OP
					   ,CD_NT_MOV,VLR_DESC,VLR_BASE_ICMS_SUBS,VLR_ICMS_SUBS,VLR_IPI,VRL_ISENTAS,VLR_ESTORNO,NR_CONH_TRANSP
					   ,DEV,COB,STS_NF,HIST,HIST2,CD_VAL,VLR_PROD_ICMS_SUBS,TP_NF,CD_NF_SAIDA,TP_DEV_NF
					   ,IMP_NF,ORIG_LANC,CD_NF_PROD,CD_USU,DT_CAD,DT_ULT_ALT,TP_SUBS_TRIB,NF_IPI_BASE_CALC,VLR_ENCG_FIN
					   ,PERC_ICMS_ENCG_FIN,ENCG_TRIB,TP_LANC,CD_PED,HR_EMI_NF,CD_NF_SERIE,VLR_DESC_CAB,INF_DESCONTO,OBS4
					   ,OBS5,DS_TRANSP,PLACA_VEIC,PLACA_UF,CGC_CPF_TRANSP,ENDE_TRANSP,DS_CID_TRANSP,UF_TRANSP,INSC_EST_TRANSP,QT_VOL
					   ,ESPCIE_VOL,MC_VOL,NR_VOL,PESO_BRT,PESO_LIQ,DT_ENTRADA_EST,PERC_IPI_FRETE,VLR_PERC_IPI_FRETE,CALC_SUBS_PMC,PERC_REDU_SUBS_PMC,PGTO_VISTA_PRAZO
					   ,FLAG_RATEIO_DIF,FLAG_N_GERAR_DAR,NR_SELO_SAIDA,CD_MT_CANCEL,NR_FORMULARIO,NR_PED_FORN,IGNORAR_GERACAO_FINAN,FLAG_DESACORDO,CD_USU_LIBEROU_DESACORDO
					   ,CD_USU_LIBEROU_CUSTO_VARIACAO,FLAG_NF_PROD_TOTAL_BRUTO,CD_MT_DEV_VD,DT_CONTABILIZAR,FRETE_INCIDE_BASE_ICMS,BAIRRO_DESTINATARIO,BAIRRO_EMITENTE
					   ,CEP_DESTINATARIO,CEP_EMITENTE,CIDADE_DESTINATARIO,CIDADE_EMITENTE,CNPJ_DESTINATARIO,CNPJ_EMITENTE,END_DESTINATARIO,END_EMITENTE,INSC_ESTADUAL_DESTINATARIO
					   ,INSC_ESTADUAL_EMITENTE,RZ_DESTINATARIO,RZ_EMITENTE,RZ_TRANSPORTADOR,UF_DESTINATARIO,CD_ANTT,TP_FRETE,UF_EMITENTE,APLICATIVO,VERSAO_APLICATIVO
					   ,UF_VEIC,CNPJ_TRANSP,END_TRANSP,BAIRRO_TRANSP,CIDADE_TRANSP,INSC_ESTADUAL_TRANSP,QTDE_VOLUME,PESO_BRUTO,ESPECIE,MARCA
					   ,NUMERACAO,HR_ENT,CD_CID_EMITENTE,CD_CID_DESTINATARIO,CD_CID_TRANSP,XML_NOTA,FLAG_NOTA_INTEGRACAO,NFE_REJEITADA,CRT,EMAIL_TRANSP
					   ,VLR_ICMS_DESONERADO,DT_HR_CAD,IDENTIFICACAO_OPERACAO,FLAG_REPOSICAO_PBM,VLR_NOTA_FINANCEIRO)

    SELECT
	    S.CD_EMP
	   ,S.CD_FILIAL
	   ,@CD_NF_NOVO CD_NF
	   ,S.CD_FILIAL CD_FORN
	   ,@DT_ENT  DT_ENT
	   ,@DT_ENT DT_EMI_NF
	   ,@NR_NF_NOVO NR_NF
	   ,S.VLR_NF
	   ,S.VLR_ICMS
	   ,S.VLR_FRETE
	   ,S.VLR_OUTROS
	   ,S.VLR_BASE_ICMS
	   ,S.ALIQ_ICMS
	   ,S.VLR_TOT_PROD
	   ,0 CD_NT_OP
	   ,@CD_MOV_OP CD_NT_MOV
	   ,S.VLR_DESC
	   ,S.VLR_BASE_ICMS_SUBS
	   ,S.VLR_ICMS_SUBS
	   ,ISNULL(S.VLR_IPI,0) VLR_IPI
	   ,0 VRL_ISENTAS
	   ,0 VLR_ESTORNO
	   ,0 NR_CONH_TRANSP
	   ,S.DEV
	   ,S.COB
	   ,S.STS_NF
	   ,'NOTA FISCAL REF.:' +CONVERT(VARCHAR, S.NF_NF) HIST
	   ,''  HIST2
	   ,0 CD_VAL
	   ,S.VLR_PROD_ICMS_SUBS
	   ,S.TP_NF
	   ,CD_NF CD_NF_SAIDA
	   ,S.TP_DEV_NF
	   ,1 IMP_NF
	   ,1 ORIG_LANC
	   ,0 CD_NF_PROD
	   ,1 CD_USU
	   ,GETDATE() DT_CAD
	   ,NULL DT_ULT_ALT
	   ,0 TP_SUBS_TRIB
	   ,0 NF_IPI_BASE_CALC
	   ,0 VLR_ENCG_FIN
	   ,0 PERC_ICMS_ENCG_FIN
	   ,0 ENCG_TRIB
	   ,0 TP_LANC
	   ,S.CD_PED
	   ,CONVERT(varchar, DATEADD(MINUTE, -1, GETDATE()),108 ) HR_EMI_NF
	   ,S.CD_NF_SERIE
	   ,S.VLR_DESC VLR_DESC_CAB
	   ,S.INF_DESCONTO
	   ,'NOTA FISCAL REF. A NOTA SAIDA NR:' +CONVERT(VARCHAR, S.NF_NF)  OBS4
	   ,'' OBS5
	   ,S.DS_TRANSP
	   ,S.PLACA_VEIC
	   ,S.PLACA_UF
	   ,S.CGC_CPF_TRANSP
	   ,S.ENDE_TRANSP
	   ,S.DS_CID_TRANSP
	   ,S.UF_TRANSP
	   ,S.INSC_EST_TRANSP
	   ,S.QT_VOL
	   ,0 ESPCIE_VOL
	   ,S.MC_VOL
	   ,S.NR_VOL
	   ,0 PESO_BRT
	   ,0 PESO_LIQ
	   ,CONVERT(DATE, GETDATE()) DT_ENTRADA_EST
	   ,0 PERC_IPI_FRETE
	   ,0 VLR_PERC_IPI_FRETE
	   ,0 CALC_SUBS_PMC
	   ,0 PERC_REDU_SUBS_PMC
	   ,0 PGTO_VISTA_PRAZO
	   ,0 FLAG_RATEIO_DIF
	   ,0 FLAG_N_GERAR_DAR
	   ,S.NR_SELO_SAIDA
	   ,S.CD_MT_CANCEL
	   ,S.NR_FORMULARIO
	   ,0 NR_PED_FORN
	   ,0 IGNORAR_GERACAO_FINAN
	   ,0 FLAG_DESACORDO
	   ,0 CD_USU_LIBEROU_DESACORDO
	   ,0 CD_USU_LIBEROU_CUSTO_VARIACAO    
	   ,S.FLAG_NF_PROD_TOTAL_BRUTO
	   ,0 CD_MT_DEV_VD
	   ,CONVERT(DATE, GETDATE()) DT_CONTABILIZAR
	   ,0 FRETE_INCIDE_BASE_ICMS
	   --,S.BAIRRO_DESTINATARIO
	   ,S.BAIRRO_EMITENTE
	   ,S.BAIRRO_EMITENTE
	   --,S.CEP_DESTINATARIO
	   ,S.CEP_EMITENTE
	   ,S.CEP_EMITENTE
	   --,S.CIDADE_DESTINATARIO
	   ,S.CIDADE_EMITENTE
	   ,S.CIDADE_EMITENTE	   
	   --,S.CNPJ_DESTINATARIO
	   ,S.CNPJ_EMITENTE
	   ,S.CNPJ_EMITENTE
	   --,S.END_DESTINATARIO
	   ,S.END_EMITENTE
	   ,S.END_EMITENTE
	   --,S.INSC_ESTADUAL_DESTINATARIO
	   ,S.INSC_ESTADUAL_EMITENTE
	   ,S.INSC_ESTADUAL_EMITENTE
	   --,S.RZ_DESTINATARIO
	   ,S.RZ_EMITENTE
	   ,S.RZ_EMITENTE
	   ,S.RZ_TRANSPORTADOR
	   ,S.UF_DESTINATARIO
	   ,0 CD_ANTT
	   ,S.TP_FRETE
	   ,S.UF_EMITENTE
	   --,S.APLICATIVO
	   ,'Procedure ' APLICATIVO
	   --,S.VERSAO_APLICATIVO
	   ,'10569' VERSAO_APLICATIVO
	   ,NULL UF_VEIC
	   ,NULL CNPJ_TRANSP
	   ,NULL END_TRANSP
	   ,NULL BAIRRO_TRANSP
	   ,NULL CIDADE_TRANSP
	   ,NULL INSC_ESTADUAL_TRANSP
	   ,NULL QTDE_VOLUME
	   ,0 PESO_BRUTO
	   ,NULL ESPECIE
	   ,NULL MARCA
	   ,NULL NUMERACAO
	   ,CONVERT(TIME,  GETDATE()) HR_ENT
	   ,S.CD_CID_EMITENTE
	   ,S.CD_CID_DESTINATARIO
	   ,S.CD_CID_TRANSP
	   ,NULL XML_NOTA
	   ,0 FLAG_NOTA_INTEGRACAO
	   ,S.NFE_REJEITADA
	   ,NULL CRT
	   ,S.EMAIL_TRANSP
	   ,S.VLR_ICMS_DESONERADO
	   ,GETDATE() DT_HR_CAD
	   ,0 IDENTIFICACAO_OPERACAO
	   ,0 FLAG_REPOSICAO_PBM
	   ,0 VLR_NOTA_FINANCEIRO
    FROM 
	   EST_NF_SAI S 
    WHERE
	   S.CD_NF= @CD_NF_SAI 
	   AND S.CD_FILIAL=@CD_FILIAL
	   AND S.CD_EMP=1
	   
	   IF @@ROWCOUNT=0
	   BEGIN
	   	set @mensagemErro ='Falha na geracao do cabecao da NF '  
		RAISERROR (@mensagemErro, 16,0);
		RETURN
	   END
 
/********************************************************************************************************************************/    
    print 'Inserindo os itens da nota fiscal.. ' + convert(varchar, getdate(),108);
/********************************************************************************************************************************/

 INSERT INTO EST_NF_ENT_IT (CD_EMP,CD_FILIAL,CD_NF,CD_PROD,DS_PROD,VLR_IT,QT_IT,VLR_ICMS_IT,ALIQ_ICMS,CD_TRIB
			 ,UN,PERC_IPI,VLR_PRC_CUSTO,VLR_BASE_ICMS,VLR_ICMS_SUBS,VLR_BASE_SUBS,VLR_PRC_CUSTO_ANT,QT_EST_ANT,CD_NT_OP
			 ,VLR_IPI,PERC_DESC,VLR_DESC,SEQ_ITEM,VLR_ISENTO,VLR_OUTROS,VLR_TOT_IT,CD_SIGLA,PERC_IVA
			 ,QT_EMB,VLR_FRETE_IT,PIS_COFINS,PERC_DESC_FINAN,PERC_DESC_COMERCIAL,CD_CTR_COT_VIGENTE,PERC_REDU_BASE_SUBS
			 ,PERC_REDU_BASE_ICMS,VLR_PROD_FRETE,LISTA_PROD,VLR_BASE_PIS,VLR_PIS,PERC_ALIQ_PIS,VLR_BASE_COFINS,VLR_COFINS
			 ,PERC_ALIQ_COFINS,VLR_BASE_ICMS_RET,VLR_ICMS_RET,VLR_OUTRAS_DESPESAS,VLR_PROD_PMC,CD_SIT_OPERA_SIMPLES_NACIO,MODALI_BASE_ICMS_SUBST,MODALI_BASE_ICMS
			 ,VLR_CRED_BASE_SN,VLR_CRED_ICMS_SN,DT_ENT,CST_COFINS,VLR_IMPOSTO_REA,CST_PIS,PIS_COFINS_RECALCULADO
			 ,ALIQ_ICMS_INTERNO,TP_PROD,CD_USU_LIBEROU_VALIDADE_LOTE,FLAG_N_GERAR_DAR,TIPO_TRIBUTACAO_PIS_COFINS,VLR_CUSTO_MD,FLAG_EXCECAO_PIS_COFINS
			 ,SIGLA_EXCECAO_PIS_COFINS,VLR_CUSTO_ANT_RECALC,N_ITEM_PED,XPED_IT,VLR_DESC_FINAN
			 ,FLAG_PROD_CESTA_BASICA,VLR_CUSTO_GER,VLR_CUSTO_GERENCIAL_TRANSF,FLAG_ICMS_RETIDO_CALCULADO,VLR_BASE_ICMS_OP
			 ,VLR_ICMS_OP,VLR_CUSTO_SEM_ST,PERC_ICMS_OP,PERC_IVA_RET,PERC_ICMS_RET,PRZ_DESC_FIN,VLR_RESSARCIMENTO_ICMS,IND_TOTAL
			 ,VLR_CUSTO_ACERTO,VLR_ICMS_DESONERADO,ICMS_DESONERADO_MOTIVO,PERC_ICMS_DESTINO_DIFAL,PERC_ICMS_ORIGEM_DIFAL,GERAR_DIFAL,FECOP_RECALCULADO
			 ,PERC_FECOP,FLAG_CFOP_ALTERADO_MANUAL,PERC_DIFERIMENTO,VLR_ICMS_DIFERIMENTO,VLR_BASE_ICMS_LUCRO_REAL,PERC_ICMS_LUCRO_REAL
			 ,VLR_ICMS_LUCRO_REAL,TP_MOV)

     SELECT 
	    I.CD_EMP
	   ,I.CD_FILIAL
	   ,@CD_NF_NOVO 
	   ,I.CD_PROD
	   ,I.DS_PROD
	   ,I.VLR_IT
	   ,I.QT_IT
	   ,t.VLR_ICMS VLR_ICMS_IT
	   ,t.PERC_ICMS ALIQ_ICMS
	   ,T.CD_TRIB
	   ,I.UN
	   ,I.PERC_IPI
	   ,T.VLR_CUSTO VLR_PRC_CUSTO
	   ,T.VLR_BASE_ICMS VLR_BASE_ICMS
	   ,T.VLR_ICMS_SUBS VLR_ICMS_SUBS
	   ,T.VLR_BASE_SUBS
	   ,0 VLR_PRC_CUSTO_ANT
	   ,I.QT_EST_ANT
	   ,T.CD_NT_OP
	   ,ISNULL(I.VLR_IPI_IT,0) VLR_IPI
	   ,I.PERC_DESC_IT PERC_DESC
	   ,I.VLR_DESC_IT VLR_DESC
	   ,I.CD_IT SEQ_ITEM
	   ,I.VLR_ISENTO
	   ,I.VLR_OUTROS
	   ,I.VLR_TOT_IT
	   ,0 CD_SIGLA
	   ,I.PERC_IVA
	   ,1 QT_EMB
	   ,0 VLR_FRETE_IT
	   ,I.PIS_COFINS
	   ,0 PERC_DESC_FINAN
	   ,0 PERC_DESC_COMERCIAL
	   ,0 CD_CTR_COT_VIGENTE
	   ,I.PERC_REDU_BASE_SUBS
	   ,I.PERC_REDU_BASE_ICMS
	   ,I.VLR_PROD_FRETE
	   ,I.LISTA_PROD
	   ,T.VLR_BASE_PIS
	   ,T.VLR_PIS
	   ,I.PERC_ALIQ_PIS
	   ,T.VLR_BASE_COFINS
	   ,T.VLR_COFINS
	   ,T.PERC_COFINS PERC_ALIQ_COFINS
	   ,I.VLR_BASE_ICMS_RET
	   ,T.VLR_ICMS_RET
	   ,I.VLR_OUTROS_DESPESAS VLR_OUTRAS_DESPESAS
	   ,I.VLR_PMC VLR_PROD_PMC
	   ,I.CD_SIT_OPERA_SIMPLES_NACIO
	   ,I.MODALI_BASE_ICMS_SUBST
	   ,I.MODALI_BASE_ICMS
	   ,I.VLR_CRED_BASE_SN
	   ,I.VLR_CRED_ICMS_SN
	   ,@DT_ENT
	   ,T.CST_COFINS
	   ,0 VLR_IMPOSTO_REA
	   ,T.CST_PIS
	   ,0 PIS_COFINS_RECALCULADO
	   ,I.ALIQ_ICMS_INTERNO
	   ,I.TP_PROD
	   ,0 CD_USU_LIBEROU_VALIDADE_LOTE
	   ,0 FLAG_N_GERAR_DAR
	   ,I.TIPO_TRIBUTACAO_PIS_COFINS
	   ,I.VLR_CUSTO_MD
	   ,I.FLAG_EXCECAO_PIS_COFINS 
	   ,I.SIGLA_EXCECAO_PIS_COFINS
	   ,0 VLR_CUSTO_ANT_RECALC
	   ,I.N_ITEM_PED
	   ,I.XPED_IT
	   ,0 VLR_DESC_FINAN
	   ,I.FLAG_PROD_CESTA_BASICA
	   ,I.VLR_CUSTO_MD VLR_CUSTO_GER
	   ,I.VLR_CUSTO_GERENCIAL_TRANSF
	   ,0 FLAG_ICMS_RETIDO_CALCULADO
	   ,I.VLR_BASE_ICMS_OP
	   ,I.VLR_ICMS_OP
	   ,0 VLR_CUSTO_SEM_ST
	   ,I.PERC_ICMS_OP
	   ,0 PERC_IVA_RET
	   ,0 PERC_ICMS_RET
	   ,0 PRZ_DESC_FIN
	   ,I.VLR_RESSARCIMENTO_ICMS
	   ,I.IND_TOTAL
	   ,I.VLR_CUSTO_ACERTO
	   ,I.VLR_ICMS_DESONERADO
	   ,I.ICMS_DESONERADO_MOTIVO
	   ,I.PERC_ICMS_DESTINO_DIFAL
	   ,I.PERC_ICMS_ORIGEM_DIFAL
	   ,I.GERAR_DIFAL
	   ,I.FECOP_RECALCULADO
	   ,I.PERC_FECOP
	   ,0 FLAG_CFOP_ALTERADO_MANUAL
	   ,I.PERC_DIFERIMENTO
	   ,I.VLR_ICMS_DIFERIMENTO
	   ,I.VLR_BASE_ICMS_LUCRO_REAL
	   ,I.PERC_ICMS_LUCRO_REAL
	   ,I.VLR_ICMS_LUCRO_REAL
	   ,T.TP_MOV
	   --,T.*
    FROM   
	   EST_NF_SAI S
	   JOIN EST_NF_SAI_IT I ON 
	   S.CD_EMP = I.CD_EMP AND
	   S.CD_FILIAL = I.CD_FILIAL AND
	   S.CD_NF = I.CD_NF
	   CROSS APPLY [dbo].[UFD_EST_PROD_TRIB](  I.CD_EMP,
									   I.CD_FILIAL,
									   @CD_MOV_OP,
									   s.CD_FILIAL,
									   I.CD_PROD,
									   0,
									   0,
									   0,
									   CASE WHEN I.QT_IT =0 THEN 1 ELSE I.QT_IT END ,
									   I.VLR_IT,
									   0,
									   0,
									   0,
									   0,
									   0,				--@TIPO_OPERACAO
									   0)	T		
    WHERE
	   I.CD_NF= @CD_NF_SAI 
	   AND I.CD_FILIAL=@CD_FILIAL
	   AND I.CD_EMP=1;

	   IF @@ROWCOUNT=0
	   BEGIN
		ROLLBACK TRAN;
	   	set @mensagemErro ='Falha na geracao dos itens da NF '  
		RAISERROR (@mensagemErro, 16,0);
		RETURN
	   END

	   

	    if (select count(*)
			 from est_nf_sai_it
			 where
				cd_emp= @CD_EMP
				and cd_filial = @CD_FILIAL
				and cd_nf=@CD_NF_SAI)
				<> (select count(*)
					   from
						  est_nf_ent_it
					   where
						  cd_emp= @CD_EMP
						  and cd_filial = @CD_FILIAL
						  and cd_nf=@CD_NF_NOVO)
	   BEGIN
	   	set @mensagemErro ='Quantidade de itens divergente da NF saída'  
		RAISERROR (@mensagemErro, 16,0);
		RETURN
	   END



/********************************************************************************************************************************/    
    print 'Inserindo a referencia da nota de saida ... ' + convert(varchar, getdate(),108);
/********************************************************************************************************************************/
	   
    
	   INSERT INTO EST_NF_ENT_EF_NF_CTR_NF(CD_EMP,CD_FILIAL,CD_NF_ENT,NR_NF,CD_NF_SERIE,FLAG_NOTA_INTEGRACAO)
	   SELECT 
		  @CD_EMP
		  ,@CD_FILIAL
		  ,@CD_NF_NOVO    CD_NF_ENT
		  ,@NR_NF_NOVO	NR_NF
		  ,@CD_NF_SERIE   CD_NF_SERIE
		  ,0 FLAG_NOTA_INTEGRACAO

	   INSERT INTO EST_NF_ENT_DEVOLUCAO_NFE_CHAVE_REFERENCIA (CD_EMP ,CD_FILIAL ,CD_NF ,NR_AUTORIZADOR ,NR_ECF
													   ,CD_CX ,MODELO ,CD_UF ,ANO_MES_EMI ,CNPJ ,SERIE ,NR_NF)
	   SELECT 
		   s.CD_EMP
		  ,s.CD_FILIAL
		  ,@CD_NF_NOVO 
		  --,ISNULL(NFCPL.NR_AUTORIZADOR, nfe.NR_AUTORIZADOR)
		  ,nfe.NR_AUTORIZADOR 
		  ,0 NR_ECF
		  ,0 CD_CX
		  ,'' MODELO
		  ,0 AS CD_UF
		  ,0 AS ANO_MES_EMI
		  ,'' AS CNPJ
		  ,0 AS SERIE
		  ,S.NF_NF
		  --,ISNULL(NFCPL.NF_NF, S.NF_NF )
	    FROM 
		  EST_NF_SAI S 
		  JOIN EST_NF_SAI_NFE nfe ON
		  s.CD_EMP = nfe.CD_EMP AND
		  s.CD_FILIAL = nfe.CD_FILIAL AND
		  s.CD_NF = nfe.CD_NF 

		  --LEFT JOIN (SELECT 
				--	   A.CD_EMP
				--	   , A.CD_NF 
				--	   , A.CD_FILIAL
				--	   , C.NF_NF
				--	   , NFE.NR_AUTORIZADOR
				--	   FROM 
				--	   EST_NF_SAI  A
				--	   LEFT JOIN EST_NF_SAI_EST_NF_SAI_CPL  B ON 
				--	   A.CD_EMP = B.CD_EMP AND
				--	   A.CD_FILIAL = B.CD_FILIAL AND
				--	   A.CD_NF = B.CD_NF
				--	   LEFT JOIN EST_NF_SAI C ON 
				--	   B.CD_EMP	 = C.CD_EMP AND
				--	   B.CD_FILIAL = C.CD_FILIAL AND
				--	   B.CD_NF_REF = C.CD_NF
				--	   LEFT JOIN EST_NF_SAI_NFE nfe ON
				--	   C.CD_EMP = nfe.CD_EMP AND
				--	   C.CD_FILIAL = nfe.CD_FILIAL AND
				--	   C.CD_NF = nfe.CD_NF) nfcpl ON 
		  --s.CD_EMP    = nfcpl.CD_EMP AND
		  --s.CD_FILIAL = nfcpl.CD_FILIAL AND
		  --s.CD_NF	    = nfcpl.CD_NF 
	   WHERE
		  S.CD_NF= @CD_NF_SAI 
		  AND S.CD_FILIAL=@CD_FILIAL
		  AND S.CD_EMP=1;


/********************************************************************************************************************************/    
    print 'Inserindo o relaciomento de saida com entrada... ' + convert(varchar, getdate(),108);
/********************************************************************************************************************************/
    insert into EST_NF_SAI_NF_ENT(CD_EMP,CD_FILIAL,CD_NF_SAI, CD_NF_ENT)
    select 
	   @CD_EMP
	   ,@CD_FILIAL
	   ,@CD_NF_SAI
	   ,@CD_NF_NOVO;

    print 'Foi emitida a Nota.: ' + convert(varchar, @NR_NF_NOVO) + ' na filial ' +convert(varchar, @cd_filial) + ' - Entrada' ;
    print 'Time - ' +convert(varchar, getdate(),108)
    print '******************************' ;

end try 
begin catch
	
		set @mensagemErro ='Falha na geracao da NF ' + ERROR_MESSAGE() 
		RAISERROR (@mensagemErro, 16,0);

		--RETURN -2;	

end catch