IF OBJECT_ID('P_EXP_CTB_MOV_PG_CRED_APROP_SEM_VINC_DESP') IS NOT NULL
    BEGIN
        DROP PROCEDURE P_EXP_CTB_MOV_PG_CRED_APROP_SEM_VINC_DESP;
    END;
GO
--exec P_EXP_CTB_MOV_PG_CRED_APROP_SEM_VINC_DESP 1,4,'20210922','20210922',0
CREATE PROCEDURE P_EXP_CTB_MOV_PG_CRED_APROP_SEM_VINC_DESP(@CD_EMP      INT,
                                                           @CD_FILIAL   INT,
                                                           @DT_INI      DATETIME,
                                                           @DT_FIM      DATETIME,
                                                           @FLAG_LIMPAR INT      = 0)
WITH ENCRYPTION
AS
SET NOCOUNT ON;
    BEGIN TRY
        BEGIN
            DECLARE @RS_CD_EMP INT;
            DECLARE @RS_CD_FILIAL INT;
            DECLARE @RS_DT_MOV DATETIME;
            DECLARE @RS_DT_ENT DATETIME;


			 
            DECLARE @RS_CD_FORN INT;
            DECLARE @RS_RZ_FORN VARCHAR(100);
            DECLARE @RS_HIST VARCHAR(200);
            DECLARE @RS_CD_DESP_REC INT;
            DECLARE @RS_NR_CNT VARCHAR(50);
            DECLARE @RS_CD_CNT_CTB_RED INT;
            DECLARE @RS_DS_DESP_REC VARCHAR(100);
            DECLARE @RS_VLR_NF MONEY;
            DECLARE @RS_VLR_RAT_DESP MONEY;
            DECLARE @RS_RATEIO_CENTRO_CUSTO INT;
            DECLARE @RS_NR_NF INT;
            DECLARE @RS_NM_FANT VARCHAR;
            DECLARE @RS_VLR_ICMS_ITENS MONEY;
            DECLARE @RS_VLR_ICMS_SUBS_ITENS MONEY;
            DECLARE @RS_VLR_BASE_PIS_COFINS MONEY;
            DECLARE @RS_TP_MOV INT;
            DECLARE @RS_TP_MOV_DS VARCHAR(100);
            DECLARE @RS_DEST_ORIG INT;
            DECLARE @RS_CONTASPAGAR VARCHAR(50);
            DECLARE @RS_CD_CTB_CNT_RED INT;
            DECLARE @RS_CD_CTB_CNT VARCHAR(50);
            DECLARE @RS_CD_MOV_OP INT;
            DECLARE @RET_DS_MOV_OP_CONTABIL VARCHAR(100);
            DECLARE @RET_CNT_CENTRO_CUSTO INT;
            DECLARE @RET_DS_CENTRO_CUSTO VARCHAR(100);
            DECLARE @RET_FLAG_APLICAR_CENTRO_CUSTO INT;
            DECLARE @RET_CD_CTB_CNT VARCHAR(100);
            DECLARE @RET_CD_CTB_CNT_RED INT;
            DECLARE @DADOS_NF_ICMS_SUBS_DESP_ATUAL VARCHAR(200);
            DECLARE @DADOS_NF_ICMS_SUBS_DESP_ANT VARCHAR(200);
            DECLARE @DADOS_NF_ICMS_DESP_ATUAL VARCHAR(200);
            DECLARE @DADOS_NF_ICMS_DESP_ANT VARCHAR(200);
            DECLARE @DADOS_NF_ATUAL VARCHAR(200);
            DECLARE @DADOS_NF_ANT VARCHAR(200);
            DECLARE @DADOS_NF_DESP_ATUAL VARCHAR(200);
            DECLARE @DADOS_NF_DESP_ANT VARCHAR(200);
            DECLARE @DADOS_NF_COFINS_DESP_ATUAL VARCHAR(200);
            DECLARE @DADOS_NF_COFINS_DESP_ANT VARCHAR(200);
            DECLARE @HIST VARCHAR(200);
            DECLARE @VLR_TEMP MONEY;
            DECLARE @PERC_COFINS MONEY;
		  DECLARE @PERC_PIS MONEY;
            DECLARE @NR_DP INT;
		  DECLARE @ANO_DP INT;
		  DECLARE @PG_CRED INT;


		  DECLARE @NUMERODUPL VARCHAR(20)
		  DECLARE @NUM_DUPL  BIGINT 

            SET @PERC_COFINS = ISNULL(
                                     (
                                         SELECT PERC_IMP
                                         FROM GLB_IMPOSTOS
                                         WHERE TIPO_IMPOSTO = 2
                                     ), 0);
            SET @PERC_PIS = ISNULL(
                                  (
                                      SELECT PERC_IMP
                                      FROM GLB_IMPOSTOS
                                      WHERE TIPO_IMPOSTO = 1
                                  ), 0);
            SET @DADOS_NF_ANT = '';
            SET @DADOS_NF_DESP_ANT = '';
            SET @DADOS_NF_ICMS_DESP_ANT = '';
            SET @DADOS_NF_ICMS_SUBS_DESP_ANT = '';
            SET @DADOS_NF_COFINS_DESP_ANT = '';


			/*Evita reprocessamento da view "V_EST_NF_ENT_CONTABIL", caso a rotina estiver sendo executada para todas as Filiais*/

			IF OBJECT_ID('tempdb.dbo.##V_EST_NF_ENT_CONTABIL', 'U') IS NULL 
			BEGIN


			SELECT CD_EMP
								 , CD_FILIAL
								 , DT_CAD
								 , DT_ENT
								 , CD_FORN
								 , RZ_FORN
								 , HIST
								 , CD_DESP_REC
								 , NR_CNT
								 , CD_CNT_CTB_RED
								 , DS_DESP_REC
								 , VLR_NF
								 , VLR_RAT_DESP
								 , RATEIO_CENTRO_CUSTO
								 , NR_NF
								 , NM_FANT
								 , VLR_ICMS_ITENS
								 , VLR_ICMS_SUBS_ITENS
								 , VLR_BASE_PIS_COFINS
								 , TP_MOV
								 , TP_MOV_DS
								 , DEST_ORIG
								 , CONTASPAGAR
								 , CD_CTB_CNT_RED
								 , CD_CTB_CNT
								 , CD_MOV_OP
							 , NR_DP
							 , ANO_DP
							 , GETDATE() AS DATAATUAL
							 , @DT_INI as DT_INI
							 , @DT_FIM as DT_FIM
							 , PG_CRED
					INTO ##V_EST_NF_ENT_CONTABIL
					FROM V_EST_NF_ENT_CONTABIL    
					WHERE DT_CAD  BETWEEN  @DT_INI AND @DT_FIM
			END


			IF EXISTS(SELECT 1
							FROM ##V_EST_NF_ENT_CONTABIL (NOLOCK)
							WHERE CONVERT(DATE, DATAATUAL) <> CONVERT(DATE,GETDATE())
							)
			BEGIN
				TRUNCATE TABLE ##V_EST_NF_ENT_CONTABIL;
			END

			
				IF NOT EXISTS(SELECT 1
							FROM ##V_EST_NF_ENT_CONTABIL (NOLOCK)
							WHERE CONVERT(DATE, DATAATUAL) = CONVERT(DATE,GETDATE())
							AND DT_INI = @DT_INI
							AND DT_FIM = @DT_FIM
							)
				BEGIN

					INSERT INTO ##V_EST_NF_ENT_CONTABIL
					SELECT CD_EMP
								 , CD_FILIAL
								 , DT_CAD
								 , DT_ENT
								 , CD_FORN
								 , RZ_FORN
								 , HIST
								 , CD_DESP_REC
								 , NR_CNT
								 , CD_CNT_CTB_RED
								 , DS_DESP_REC
								 , VLR_NF
								 , VLR_RAT_DESP
								 , RATEIO_CENTRO_CUSTO
								 , NR_NF
								 , NM_FANT
								 , VLR_ICMS_ITENS
								 , VLR_ICMS_SUBS_ITENS
								 , VLR_BASE_PIS_COFINS
								 , TP_MOV
								 , TP_MOV_DS
								 , DEST_ORIG
								 , CONTASPAGAR
								 , CD_CTB_CNT_RED
								 , CD_CTB_CNT
								 , CD_MOV_OP
							 , NR_DP
							 , ANO_DP
							 , GETDATE() AS DATAATUAL
							 , @DT_INI as DT_INI
							 , @DT_FIM as DT_FIM
							 , PG_CRED
					FROM V_EST_NF_ENT_CONTABIL    
					WHERE DT_CAD  BETWEEN  @DT_INI AND @DT_FIM

				END

			
			/*Fim Evita reprocessamento da view "V_EST_NF_ENT_CONTABIL"*/

            ------------------------------------------------------------------------------------------------------------------------------
            --CRIANDO A TABELA TEMPORARIA ##CTB_EXP_MOV
            ------------------------------------------------------------------------------------------------------------------------------
            EXEC P_EXP_CTB_MOV_CRIAR_CTB_EXP_MOV
                 @FLAG_LIMPAR;
            DECLARE RS_RESULT CURSOR
            FOR SELECT CD_EMP
                     , CD_FILIAL
                     , DT_CAD
                     , DT_ENT
                     , CD_FORN
                     , RZ_FORN
                     , HIST
                     , CD_DESP_REC
                     , NR_CNT
                     , CD_CNT_CTB_RED
                     , DS_DESP_REC
                     , VLR_NF
                     , VLR_RAT_DESP
                     , RATEIO_CENTRO_CUSTO
                     , NR_NF
                     , NM_FANT
                     , VLR_ICMS_ITENS
                     , VLR_ICMS_SUBS_ITENS
                     , VLR_BASE_PIS_COFINS
                     , TP_MOV
                     , TP_MOV_DS
                     , DEST_ORIG
                     , CONTASPAGAR
                     , CD_CTB_CNT_RED
                     , CD_CTB_CNT
                     , CD_MOV_OP
				 , NR_DP
				 , ANO_DP
				 , PG_CRED
        FROM ##V_EST_NF_ENT_CONTABIL (NOLOCK) 
                WHERE CD_EMP =  @CD_EMP
                      AND CD_FILIAL = @CD_FILIAL
                      AND DT_CAD  BETWEEN  @DT_INI AND @DT_FIM
                     -- AND FLAG_CONTABILIZAR_COMO_DESPESAS = 0
			 ORDER BY CD_EMP
                       , CD_FILIAL
                       , DT_CAD
                       , NR_NF
                       , TP_MOV;	
				   
				   
/*

SELECT * FROM V_EST_NF_ENT_CONTABIL WHERE CD_FILIAL = 701 AND DT_ENT  
BETWEEN '20210512' AND '20210512' --AND NR_DP = 1700294   
ORDER BY CD_EMP , CD_FILIAL  , DT_CAD, NR_NF, TP_MOV

*/				

            --Abrindo cursor
            OPEN RS_RESULT;
		
            --Atribuindo valores do select nas variáveis
            FETCH NEXT FROM RS_RESULT INTO @RS_CD_EMP, @RS_CD_FILIAL, @RS_DT_MOV, @RS_DT_ENT, 
								   @RS_CD_FORN, @RS_RZ_FORN, @RS_HIST, @RS_CD_DESP_REC, 
								   @RS_NR_CNT, @RS_CD_CNT_CTB_RED, @RS_DS_DESP_REC, @RS_VLR_NF, 
								   @RS_VLR_RAT_DESP, @RS_RATEIO_CENTRO_CUSTO, @RS_NR_NF, 
								   @RS_NM_FANT, @RS_VLR_ICMS_ITENS, @RS_VLR_ICMS_SUBS_ITENS, 
								   @RS_VLR_BASE_PIS_COFINS, @RS_TP_MOV, @RS_TP_MOV_DS, @RS_DEST_ORIG, 
								   @RS_CONTASPAGAR, @RS_CD_CTB_CNT_RED, @RS_CD_CTB_CNT, @RS_CD_MOV_OP,				
								   @NR_DP,@ANO_DP,@PG_CRED;
					 

            --Iniciando laço
            WHILE @@FETCH_STATUS = 0
                BEGIN	
                    --@TP_CONTA
                    --TipoEstoque = 0                   --TipoIcmsPagar = 1
                    --TipoIcmsRecuperar = 2             --TipoPisRecuperar = 3
                    --TipoPisPagar = 4                  --TipoCofinsRecuperar = 5
                    --TipoCofinsPagar = 6               --TipoIcmsSubst = 7

                    SET @DADOS_NF_ATUAL = CAST(@RS_CD_FORN AS VARCHAR)+'-'+CAST(@RS_DT_ENT AS VARCHAR)+ '-' +CAST(@RS_VLR_NF AS VARCHAR)+'-'+CAST(@RS_NR_NF AS VARCHAR)+'-'+CAST(@RS_CD_FILIAL AS VARCHAR);												
                    ------------------------------------------------------------------------------------------------------------------
                    --CONTA ESTOQUE - NATUREZA DE OPERACAO
                    ------------------------------------------------------------------------------------------------------------------

                    IF @DADOS_NF_ANT <> @DADOS_NF_ATUAL 
                      BEGIN
				    				                              
					      --SET @DADOS_NF_ANT = CAST(@RS_CD_FORN AS VARCHAR) +'-'+CAST(@RS_VLR_NF AS VARCHAR)+'-'+CAST(@RS_NR_NF AS VARCHAR)+'-'+CAST(@RS_CD_FILIAL AS VARCHAR);
						   SET @DADOS_NF_ANT = CAST(@RS_CD_FORN AS VARCHAR)+'-'+CAST(@RS_DT_ENT AS VARCHAR)+ '-' +CAST(@RS_VLR_NF AS VARCHAR)+'-'+CAST(@RS_NR_NF AS VARCHAR)+'-'+CAST(@RS_CD_FILIAL AS VARCHAR);	
                           
						   SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
									 , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
									 , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
									 , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
									 , @RET_CD_CTB_CNT = CD_CTB_CNT
									 , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
								FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 0, 0, @CD_FILIAL);
				 
						   IF @RS_TP_MOV <> 3  -- Quando for " 3 - Doação/Brinde/Bonificação deve levar os dados da movimentação
				   
						     BEGIN
							   if @RS_DEST_ORIG = 1  -- 1 = FORNECEDOR   2 = FILIAL 
								BEGIN
					  
								  IF EXISTS
								  (
									 SELECT TOP 1 CD_EMP
									 FROM PG_FORN_CNT_CTB
									 WHERE CD_EMP = @CD_EMP
										  AND CD_FORN = @RS_CD_FORN
								  )
									 BEGIN
										SELECT @RET_CD_CTB_CNT = CD_CTB_CNT
											, @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
										FROM PG_FORN_CNT_CTB
										WHERE CD_EMP = @CD_EMP
											 AND CD_FORN = @RS_CD_FORN;
									 END;

						        END;
					         END

					  				
						   SET @NUMERODUPL =  RIGHT('0000'+ CAST(@RS_CD_FILIAL AS VARCHAR(4)),4) + CAST(@NR_DP AS VARCHAR )
						   SET @NUM_DUPL  =  @NUMERODUPL 
								SET @HIST = 'VR. REF. '+@RET_DS_MOV_OP_CONTABIL+' DESTINATARIO '+@RS_RZ_FORN+' CONF. DOC NR: '+(CASE
																																	WHEN @RS_NR_NF = 0
                                                                                                                                THEN 'DIVERSOS'
                                                                                                                                ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                            END);
					   
							SET @HIST = REPLACE (@HIST,'	',' ')
                            ------------------------------------------------------------------------------------------------------------------
                            --Contas estoque - Credito - Natureza de operação
                            ------------------------------------------------------------------------------------------------------------------

                            INSERT INTO ##CTB_EXP_MOV
							 (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
							 CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
							 VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
							 ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                   SELECT @RS_CD_EMP AS CD_EMP
                                        , @CD_FILIAL AS CD_FILIAL_EXPORT
                                        , @RS_CD_FILIAL AS CD_FILIAL
                                        , 13 AS CD_MOVIMENTO
                                        , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                        , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' - CREDITO' AS OPERACAO
                                        , '' AS OPERACAO_DEBITO
                                        , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_CREDITO
                                        , @RET_CD_CTB_CNT AS CD_CNT_CREDITO
                                        , 0 AS CD_CNT_RED_DEBITO
                                        , '' AS CD_CNT_DEBITO
                                        , @RS_DT_ENT AS DT_MOV
                                        , @HIST AS HIST
								--, (CASE WHEN @RS_VLR_RAT_DESP > 0  THEN
								--	   @RS_VLR_RAT_DESP
								--    ELSE
								--	   @RS_VLR_NF
								--    END )AS VLR_LANC
								,  @RS_VLR_NF AS  VLR_LANC
                                        , 'C' AS TP_TRANSA
                                        , (CASE
                                               WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                               THEN 0
                                               ELSE 1
                                           END) AS RATEIO_CENTRO_CUSTO
                                        , (CASE
                                               WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                               THEN ''
                                               ELSE @RET_DS_CENTRO_CUSTO
                                           END) AS DS_CENTRO_CUSTO
                                        , (CASE
                                               WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                               THEN 0
                                               ELSE @RET_CNT_CENTRO_CUSTO
                                           END) AS CNT_CENTRO_CUSTO
                                        , (CASE
                                               WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                               THEN 0
                                               ELSE @RS_VLR_NF
                                           END) AS VLR_CENTRO_CUSTO
                                        , 'NAT MOV 0-ESTOQUE' AS ORIG_CONTA
								, @RS_CD_DESP_REC AS COD_CONTA
                                        , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
								,'T' AS TIPO_LANCTO
								, 0 AS CD_EVENTO
								, @NUM_DUPL  AS NR_DP
								, @ANO_DP  AS ANO
								, @RS_NR_NF AS NR_DOC
								, 0 AS CD_BC_LANC
								, @PG_CRED;	
                        END;

                    SET @DADOS_NF_DESP_ATUAL = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+@DADOS_NF_ATUAL;

                    IF @DADOS_NF_DESP_ATUAL <> @DADOS_NF_DESP_ANT
                        BEGIN
                            SET @DADOS_NF_DESP_ANT = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
							 
					   SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
							 , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
							 , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
							 , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
							 , @RET_CD_CTB_CNT = CD_CTB_CNT
							 , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
					   FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 0, 1, @CD_FILIAL);

                            SET @HIST = 'VR. REF. '+@RET_DS_MOV_OP_CONTABIL+' DESTINATARIO '+@RS_RZ_FORN+' CONF. DOC NR: '+(CASE
                                                                                                                                WHEN @RS_NR_NF = 0
                                                                                                                                THEN 'DIVERSOS'
                                                                                                                                ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                            END);
						SET @HIST = REPLACE (@HIST,'	',' ')
                            ------------------------------------------------------------------------------------------------------------------
                            --Contas estoque - debito - Natureza de operação e despesas
                            ------------------------------------------------------------------------------------------------------------------
                            IF NOT EXISTS (SELECT 1 FROM ##CTB_EXP_MOV M
										   WHERE M.CD_FILIAL = @CD_FILIAL
										   and M.NR_DP = @NUM_DUPL
										   AND M.DT_MOV = @RS_DT_ENT
										   AND M.VLR_LANC = (CASE WHEN @RS_VLR_RAT_DESP > 0  THEN
															   @RS_VLR_RAT_DESP
															ELSE
															   @RS_VLR_NF
															END )
											AND M.NR_DOC <> @RS_NR_NF)
							BEGIN
							
								INSERT INTO ##CTB_EXP_MOV
								 (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								 CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								 VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								 ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)
								 
									   SELECT @RS_CD_EMP AS CD_EMP
											, @CD_FILIAL AS CD_FILIAL_EXPORT
											, @RS_CD_FILIAL AS CD_FILIAL
											, 13 AS CD_MOVIMENTO
											, 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
											, '' AS OPERACAO
											, 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' - DEBITO' AS OPERACAO_DEBITO
											, 0 AS CD_CNT_RED_CREDITO
											, '' AS CD_CNT_CREDITO
									,(CASE WHEN @RS_CD_CNT_CTB_RED = 0 THEN
										@RET_CD_CTB_CNT_RED
									 ELSE  
										@RS_CD_CNT_CTB_RED
									 END) AS CD_CNT_RED_DEBITO

									 ,(CASE WHEN @RS_CD_CNT_CTB_RED = 0  THEN
										@RET_CD_CTB_CNT
									 ELSE  
										@RS_NR_CNT  
									 END) AS CD_CNT_DEBITO
											, @RS_DT_ENT AS DT_MOV
											, @HIST AS HIST
											, (CASE WHEN @RS_VLR_RAT_DESP > 0  THEN
										   @RS_VLR_RAT_DESP
										ELSE
										   @RS_VLR_NF
										END )AS VLR_LANC
											, 'D' AS TP_TRANSA
											, (CASE
												   WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
												   THEN 0
												   ELSE 1
											   END) AS RATEIO_CENTRO_CUSTO
									
											, (CASE
												   WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
												   THEN ''
												   ELSE @RET_DS_CENTRO_CUSTO
											   END) AS DS_CENTRO_CUSTO

											, (CASE
												   WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
												   THEN 0
												   ELSE @RET_CNT_CENTRO_CUSTO
											   END) AS CNT_CENTRO_CUSTO
									 
											, (CASE
												   WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
												   THEN 0
												   ELSE @RS_VLR_NF
											   END) AS VLR_CENTRO_CUSTO
									 
											, 'NAT MOV 0-ESTOQUE' AS ORIG_CONTA
									, @RS_CD_DESP_REC AS COD_CONTA
											, OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
											, 'T' AS TIPO_LANCTO
											, 0 AS CD_EVENTO
									, @NUM_DUPL  AS NR_DP
									, @ANO_DP  AS ANO
									, @RS_NR_NF AS NR_DOC
									, 0 AS CD_BC_LANC	
									, @PG_CRED;
							END
						END;
                    IF @RS_VLR_ICMS_ITENS > 0
                        BEGIN
                            ------------------------------------------------------------------------------------------------------------------
                            --CONTA ICMS A RECUPERAR - NATUREZA DE OPERACAO
                            ------------------------------------------------------------------------------------------------------------------
                            SET @DADOS_NF_ICMS_DESP_ATUAL = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+CAST(@RS_VLR_ICMS_ITENS AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
                            IF @DADOS_NF_ICMS_DESP_ATUAL <> @DADOS_NF_ICMS_DESP_ANT
                                BEGIN
                                    SET @DADOS_NF_ICMS_DESP_ANT = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+CAST(@RS_VLR_ICMS_ITENS AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 2, 0, @CD_FILIAL);
                                    SET @HIST = 'VR. REF. ICMS S/'+@RET_DS_MOV_OP_CONTABIL+' DESTINATARIO '+@RS_RZ_FORN+' CONF. DOC NR: '+(CASE
                                                                                                                                               WHEN @RS_NR_NF = 0
                                                                                                                                               THEN 'DIVERSOS'
                                                                                                                                               ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                                           END);
								SET @HIST = REPLACE (@HIST,'	',' ')
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas ICMS recuperar - Credito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)


                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' ICMS - CREDITO' AS OPERACAO
                                                , '' AS OPERACAO_DEBITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_CREDITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_CREDITO
                                                , 0 AS CD_CNT_RED_DEBITO
                                                , '' AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @RS_VLR_ICMS_ITENS AS VLR_LANC
                                                , 'C' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RS_VLR_ICMS_ITENS
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 2-ICMS RECUPERAR' AS ORIG_CONTA
									  , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC
									   , @PG_CRED;	

                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 2, 1, @CD_FILIAL);
								
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas ICMS recuperar - Debito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , '' AS OPERACAO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' ICMS - DEBITO' AS OPERACAO_DEBITO
                                                , 0 AS CD_CNT_RED_CREDITO
                                                , '' AS CD_CNT_CREDITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_DEBITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @RS_VLR_ICMS_ITENS AS VLR_LANC
                                                , 'D' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RS_VLR_ICMS_ITENS
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 2-ICMS RECUPERAR' AS ORIG_CONTA
									  , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL   AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC
									   , @PG_CRED;	

                                END;
                        END;
                    IF @RS_VLR_BASE_PIS_COFINS > 0
                        BEGIN						    											
                            ------------------------------------------------------------------------------------------------------------------
                            --CONTA COFINS A RECUPERAR - NATUREZA DE OPERACAO
                            ------------------------------------------------------------------------------------------------------------------
                            SET @DADOS_NF_COFINS_DESP_ATUAL = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+CAST(@RS_VLR_BASE_PIS_COFINS AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
                            IF @DADOS_NF_COFINS_DESP_ATUAL <> @DADOS_NF_COFINS_DESP_ANT
                                BEGIN
                                    SET @DADOS_NF_COFINS_DESP_ANT = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+CAST(@RS_VLR_BASE_PIS_COFINS AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 5, 0, @CD_FILIAL);
                                    SET @HIST = 'VR. REF. COFINS S/'+@RET_DS_MOV_OP_CONTABIL+' DESTINATARIO '+@RS_RZ_FORN+' CONF. DOC NR: '+(CASE
                                                                                                                                                 WHEN @RS_NR_NF = 0
                                                                                                                                                 THEN 'DIVERSOS'
                                                                                                                                                 ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                                             END);
                                    SET @VLR_TEMP = ROUND((@RS_VLR_BASE_PIS_COFINS * @PERC_COFINS) / 100, 2);
                                    IF @PERC_COFINS = 0
                                        BEGIN
                                            SET @RET_CD_CTB_CNT = 'PERCENTUAL DO COFINS NAO INFORMADO';
                                        END;
								SET @HIST = REPLACE (@HIST,'	',' ')
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas Estoque - Credito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)
                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' COFINS - CREDITO' AS OPERACAO
                                                , '' AS OPERACAO_DEBITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_CREDITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_CREDITO
                                                , 0 AS CD_CNT_RED_DEBITO
                                                , '' AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @VLR_TEMP AS VLR_LANC
                                                , 'C' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @VLR_TEMP
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 5-COFINS RECUPERAR' AS ORIG_CONTA
									  , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC	
									   , @PG_CRED;			
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas COFINS recuperar - Debito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 5, 1, @CD_FILIAL);
                                    IF @PERC_COFINS = 0
                                        BEGIN
                                            SET @RET_CD_CTB_CNT = 'PERCENTUAL DO COFINS NAO INFORMADO';
                                        END;

                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , '' AS OPERACAO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' COFINS - DEBITO' AS OPERACAO_DEBITO
                                                , 0 AS CD_CNT_RED_CREDITO
                                                , '' AS CD_CNT_CREDITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_DEBITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @VLR_TEMP AS VLR_LANC
                                                , 'D' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @VLR_TEMP
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 5-COFINS RECUPERAR' AS ORIG_CONTA
									  , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL  AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC
									   , @PG_CRED;	
							
							        ------------------------------------------------------------------------------------------------------------------
                                    --CONTA PIS A RECUPERAR - NATUREZA DE OPERACAO
                                    ------------------------------------------------------------------------------------------------------------------
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 3, 0, @CD_FILIAL);
                                    SET @HIST = 'VR. REF. PIS S/'+@RET_DS_MOV_OP_CONTABIL+' DESTINATARIO '+@RS_RZ_FORN+' CONF. DOC NR: '+(CASE
                                                                                                                                              WHEN @RS_NR_NF = 0
                                                                                                                                              THEN 'DIVERSOS'
                                                                                                                                              ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                                          END);
                                    SET @VLR_TEMP = ROUND((@RS_VLR_BASE_PIS_COFINS * @PERC_PIS) / 100, 2);
                                    IF @PERC_PIS = 0
                                        BEGIN
                                            SET @RET_CD_CTB_CNT = 'PERCENTUAL DO PIS NAO INFORMADO';
                                        END;
								SET @HIST = REPLACE (@HIST,'	',' ')
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas ESTOQUE - Credito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' PIS - CREDITO' AS OPERACAO
                                                , '' AS OPERACAO_DEBITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_CREDITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_CREDITO
                                                , 0 AS CD_CNT_RED_DEBITO
                                                , '' AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @VLR_TEMP AS VLR_LANC
                                                , 'C' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @VLR_TEMP
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 3-PIS RECUPERAR' AS ORIG_CONTA
									  , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL   AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC
									   , @PG_CRED;	
													
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas PIS recuperar - Debito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 3, 1, @CD_FILIAL);
                                    IF @PERC_PIS = 0
                                        BEGIN
                                            SET @RET_CD_CTB_CNT = 'PERCENTUAL DO PIS NAO INFORMADO';
                                        END;

                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , '' AS OPERACAO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' PIS - DEBITO' AS OPERACAO_DEBITO
                                                , 0 AS CD_CNT_RED_CREDITO
                                                , '' AS CD_CNT_CREDITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_DEBITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @VLR_TEMP AS VLR_LANC
                                                , 'D' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @VLR_TEMP
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 3-PIS RECUPERAR' AS ORIG_CONTA
									   , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL   AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC	
									   , @PG_CRED;
                                END;
                        END;
                    IF @RS_VLR_ICMS_SUBS_ITENS > 0
                        BEGIN
                            ------------------------------------------------------------------------------------------------------------------
                            --CONTA ICMS SUBST A RECUPERAR - NATUREZA DE OPERACAO
                            ------------------------------------------------------------------------------------------------------------------
                            SET @DADOS_NF_ICMS_SUBS_DESP_ATUAL = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+CAST(@RS_VLR_ICMS_SUBS_ITENS AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
                            IF @DADOS_NF_ICMS_SUBS_DESP_ATUAL <> @DADOS_NF_ICMS_SUBS_DESP_ANT
                                BEGIN
                                    SET @DADOS_NF_ICMS_SUBS_DESP_ANT = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+CAST(@RS_VLR_ICMS_SUBS_ITENS AS VARCHAR)+'-'+@DADOS_NF_ATUAL;
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 7, 0, @CD_FILIAL);
                                    SET @HIST = 'VR. REF. ICMS SUBST S/'+@RET_DS_MOV_OP_CONTABIL+' DESTINATARIO '+@RS_RZ_FORN+' CONF. DOC NR: '+(CASE
                                                                                                                                                     WHEN @RS_NR_NF = 0
                                                                                                                                                     THEN 'DIVERSOS'
                                                                                                                                                     ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                                                 END);
								SET @HIST = REPLACE (@HIST,'	',' ')
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas ESTOQUE - Credito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------
                                    INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' ICMS SUBST - CREDITO' AS OPERACAO
                                                , '' AS OPERACAO_DEBITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_CREDITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_CREDITO
                                                , 0 AS CD_CNT_RED_DEBITO
                                                , '' AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @RS_VLR_ICMS_SUBS_ITENS AS VLR_LANC
                                                , 'C' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RS_VLR_ICMS_SUBS_ITENS
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 7-SUBST A PAGAR' AS ORIG_CONTA        
									   , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   ,  @NUM_DUPL   AS NR_DP
									   ,  @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC
									   , @PG_CRED;	
													
                                    ------------------------------------------------------------------------------------------------------------------
                                    --Contas ICMS SUBST recuperar - Debito - Natureza de operação
                                    ------------------------------------------------------------------------------------------------------------------								
                                    SELECT @RET_DS_MOV_OP_CONTABIL = DS_MOV_OP_CONTABIL
                                         , @RET_CNT_CENTRO_CUSTO = CNT_CENTRO_CUSTO
                                         , @RET_DS_CENTRO_CUSTO = DS_CENTRO_CUSTO
                                         , @RET_FLAG_APLICAR_CENTRO_CUSTO = FLAG_APLICAR_CENTRO_CUSTO
                                         , @RET_CD_CTB_CNT = CD_CTB_CNT
                                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                                    FROM UFD_BUSCA_CONTA_MOV(@CD_EMP, @RS_CD_MOV_OP, 7, 1, @CD_FILIAL);
                                    
									INSERT INTO ##CTB_EXP_MOV
								    (CD_EMP,  CD_FILIAL_EXPORT,CD_FILIAL, CD_MOVIMENTO, MOVIMENTO, OPERACAO, OPERACAO_DEBITO,
								    CD_CNT_RED_CREDITO, CD_CNT_CREDITO, CD_CNT_RED_DEBITO, CD_CNT_DEBITO, DT_MOV, HIST,
								    VLR_LANC, TP_TRANSA, RATEIO_CENTRO_CUSTO, DS_CENTRO_CUSTO, CNT_CENTRO_CUSTO, VLR_CENTRO_CUSTO,
								    ORIG_CONTA, COD_CONTA,NM_PROCEDURE,TIPO_LANCTO, CD_EVENTO, NR_DP, ANO, NR_DOC, CD_BC_LANC, COD_INTERNO)

                                           SELECT @RS_CD_EMP AS CD_EMP
                                                , @CD_FILIAL AS CD_FILIAL_EXPORT
                                                , @RS_CD_FILIAL AS CD_FILIAL
                                                , 13 AS CD_MOVIMENTO
                                                , 'MOVIMENTACAO ESTOQUE ENTRADA' AS MOVIMENTO
                                                , '' AS OPERACAO
                                                , 'APROPRIAR '+@RET_DS_MOV_OP_CONTABIL+' ICMS SUBST - DEBITO' AS OPERACAO_DEBITO
                                                , 0 AS CD_CNT_RED_CREDITO
                                                , '' AS CD_CNT_CREDITO
                                                , @RET_CD_CTB_CNT_RED AS CD_CNT_RED_DEBITO
                                                , @RET_CD_CTB_CNT AS CD_CNT_DEBITO
                                                , @RS_DT_ENT AS DT_MOV
                                                , @HIST AS HIST
                                                , @RS_VLR_ICMS_SUBS_ITENS AS VLR_LANC
                                                , 'D' AS TP_TRANSA
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE 1
                                                   END) AS RATEIO_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN ''
                                                       ELSE @RET_DS_CENTRO_CUSTO
                                                   END) AS DS_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RET_CNT_CENTRO_CUSTO
                                                   END) AS CNT_CENTRO_CUSTO
                                                , (CASE
                                                       WHEN @RET_FLAG_APLICAR_CENTRO_CUSTO = 0
                                                       THEN 0
                                                       ELSE @RS_VLR_ICMS_SUBS_ITENS
                                                   END) AS VLR_CENTRO_CUSTO
                                                , 'NAT MOV 7-SUBST A PAGAR' AS ORIG_CONTA
									   , @RS_CD_DESP_REC AS COD_CONTA
                                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                                , 'T' AS TIPO_LANCTO
                                                , 0 AS CD_EVENTO
									   , @NUM_DUPL  AS NR_DP
									   , @ANO_DP  AS ANO
									   , @RS_NR_NF AS NR_DOC
									   , 0 AS CD_BC_LANC
									   , @PG_CRED;	
                                END;
                        END;					

                    ------------------------------------------------------------------------------------------------------------------
                    --Próximo registro				
                    ------------------------------------------------------------------------------------------------------------------
                    --Atribuindo valores do select nas variáveis
                    FETCH NEXT FROM RS_RESULT INTO @RS_CD_EMP, @RS_CD_FILIAL, @RS_DT_MOV, @RS_DT_ENT, 
												   @RS_CD_FORN, @RS_RZ_FORN, @RS_HIST, @RS_CD_DESP_REC, 
												   @RS_NR_CNT, @RS_CD_CNT_CTB_RED, @RS_DS_DESP_REC, @RS_VLR_NF, 
												   @RS_VLR_RAT_DESP, @RS_RATEIO_CENTRO_CUSTO, @RS_NR_NF, @RS_NM_FANT, 
												   @RS_VLR_ICMS_ITENS, @RS_VLR_ICMS_SUBS_ITENS, @RS_VLR_BASE_PIS_COFINS, 
												   @RS_TP_MOV, @RS_TP_MOV_DS, @RS_DEST_ORIG, @RS_CONTASPAGAR, 
												   @RS_CD_CTB_CNT_RED, @RS_CD_CTB_CNT, @RS_CD_MOV_OP, @NR_DP , @ANO_DP, @PG_CRED;
                
			 END;
            CLOSE RS_RESULT;
            DEALLOCATE RS_RESULT;
        END;
 
    END TRY
    BEGIN CATCH

        CLOSE RS_RESULT;
        DEALLOCATE RS_RESULT;

	   DECLARE @ErrorMessage VARCHAR(4000) = ERROR_MESSAGE();
	   DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
	   DECLARE @ErrorState INT = ERROR_STATE();

        INSERT INTO ADM_ERRO ( numero ,severidade ,estado ,rotina ,linha ,mensagem ,dtErro )
			SELECT
				ERROR_NUMBER()	  AS numero
				,@ErrorSeverity	  AS severidade
				,@ErrorState		  AS estado
				,ERROR_PROCEDURE()	  AS rotina
				,ERROR_LINE()		  AS linha
				,@ErrorMessage	  AS mensagem
				,GETDATE()		  AS dtErro ;

	    RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);

    END CATCH;
