IF OBJECT_ID('P_EXP_CTB_MOV_PG_CRED_APROP') IS NOT NULL
    BEGIN
        DROP PROCEDURE P_EXP_CTB_MOV_PG_CRED_APROP;
    END;
GO

CREATE PROCEDURE P_EXP_CTB_MOV_PG_CRED_APROP(@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_RZ_FORN VARCHAR(225);
            DECLARE @RS_NR_CNT VARCHAR(50);
            DECLARE @RS_CNT_CENTRO_CTB VARCHAR(50);
            DECLARE @RS_DT_EMIS DATETIME;
            DECLARE @RS_CD_FORN INT;
            DECLARE @RS_HIST VARCHAR(500);
            DECLARE @RS_CD_DESP_REC INT;
            DECLARE @RS_CD_CNT_CTB_RED INT;
            DECLARE @RS_DS_DESP_REC VARCHAR(200);
            DECLARE @RS_RATEIO_CENTRO_CUSTO INT;
            DECLARE @RS_VLR_RAT_DESP MONEY;
            DECLARE @RS_VLR_RAT_DESP2 MONEY;         
            DECLARE @RS_VLR_RAT_CENTRO_CUSTO MONEY;
            DECLARE @RS_DS_CENTRO_CTB VARCHAR(100);
            DECLARE @RS_NR_NF BIGINT;
            DECLARE @RS_NM_FANT VARCHAR(200);
            DECLARE @RS_NR_DP INT;
            DECLARE @RS_IMP_CD_FILIAL INT;
            DECLARE @RS_IMP_CD_FORN INT;
            DECLARE @RS_IMP_HIST VARCHAR(500);
            DECLARE @RS_IMP_RZ_FORN VARCHAR(200);
            DECLARE @RS_IMP_DS_IMP VARCHAR(100);
            DECLARE @RS_IMP_VLR_IMP MONEY;
            DECLARE @RS_IMP_CD_CNT_CTB_RED INT;
            DECLARE @RS_IMP_NR_CNT VARCHAR(50);
            DECLARE @RS_IMP_NR_NF BIGINT;
            DECLARE @RS_IMP_NM_FANT VARCHAR(200);
            DECLARE @RS_IMP_DT_EMIS DATETIME;
            DECLARE @RS_IMP_CD_DESP_REC INT;
			DECLARE @RS_VLR_DUPL MONEY;
            DECLARE @RET_CD_CTB_CNT VARCHAR(100);
            DECLARE @RET_CD_CTB_CNT_RED INT;
            DECLARE @DADOS_DUP_ATUAL VARCHAR(200);
            DECLARE @DADOS_DUP_ANT VARCHAR(200);
            DECLARE @DADOS_DUP_DESP_ATUAL VARCHAR(200);
            DECLARE @DADOS_DUP_DESP_ANT VARCHAR(200);
            DECLARE @HIST VARCHAR(200);
            DECLARE @PERC_COFINS MONEY;
            DECLARE @PERC_PIS MONEY;
            DECLARE @CD_GRP_ECON INT;
			DECLARE @CD_PG_CRED INT; 
			DECLARE @ANO INT;
			DECLARE @NR_TIT VARCHAR (200);
			DECLARE @PARC INT;
			DECLARE @MIN_PARC INT;
		 
		    DECLARE @NUMERODUPL VARCHAR(20)
		    DECLARE @NUM_DUPL  BIGINT ;
	
            SET @DADOS_DUP_ATUAL = '';
            SET @DADOS_DUP_ANT = '';
            SET @DADOS_DUP_DESP_ATUAL = '';
            SET @DADOS_DUP_DESP_ANT = '';
	
            ------------------------------------------------------------------------------------------------------------------------------
            --CRIANDO A TABELA TEMPORARIA ##CTB_EXP_MOV
            ------------------------------------------------------------------------------------------------------------------------------
            EXEC P_EXP_CTB_MOV_CRIAR_CTB_EXP_MOV
                 @FLAG_LIMPAR;
            SET @CD_GRP_ECON =
            (
                SELECT PRC_GRP_ECON_PRC_FILIAL.CD_GRP_ECON
                FROM
                     PRC_FILIAL
                     INNER JOIN PRC_GRP_ECON_PRC_FILIAL
                     ON PRC_FILIAL.CD_EMP = PRC_GRP_ECON_PRC_FILIAL.CD_EMP
                        AND PRC_FILIAL.CD_FILIAL = PRC_GRP_ECON_PRC_FILIAL.CD_FILIAL
                WHERE PRC_FILIAL.CD_EMP = @CD_EMP
                      AND PRC_FILIAL.CD_FILIAL = @CD_FILIAL
                      AND PRC_FILIAL.FILIAL_MTZ_GRP_ECON = 1
            );
            IF ISNULL(@CD_GRP_ECON, 0) = 0
                BEGIN
                    RETURN;
                END;
            SET @PERC_COFINS = ISNULL(
                                     (
                                         SELECT TOP 1 PERC_IMP
                                         FROM GLB_IMPOSTOS
                                         WHERE TIPO_IMPOSTO = 2
                                     ), 0);
            SET @PERC_PIS = ISNULL(
                                  (
                                      SELECT TOP 1 PERC_IMP
                                      FROM GLB_IMPOSTOS
                                      WHERE TIPO_IMPOSTO = 1
                                  ), 0);
            DECLARE RS_RESULT CURSOR
            FOR 
		  
				WITH CTE_PG_DESP_RAT_CONTAS AS (
				SELECT DISTINCT
                       V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.RZ_FORN 
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_CNT                     
					  ,ISNULL(V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.CNT_CENTRO_CTB, '') AS CNT_CENTRO_CTB   
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FILIAL                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.DT_CAD AS DT_EMIS                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FORN                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.HIST                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_DESP_REC                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_CNT_CTB_RED                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.DS_DESP_REC                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.RATEIO_CENTRO_CUSTO					 
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.VLR_RAT_DESP					 
					  ,ISNULL(V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.VLR_RAT_CENTRO_CUSTO, 0) AS VLR_RAT_CENTRO_CUSTO
                      ,ISNULL(V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.DS_CENTRO_CTB, '')       AS DS_CENTRO_CTB                      
					  ,ISNULL(V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_NF, 0)                AS NR_NF                     
					  ,PRC_FILIAL.NM_FANT                     
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_DP					 
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_PG_CRED					 
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.ANO					 
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_TIT  
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.PARC
					  ,V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.VLR_DP 
					  ,PG_CRED_PARC.MIN_PARC 
                  FROM   --   SELECT TOP 1 * FROM V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL
                       V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL
					   INNER JOIN V_PG_CRED_NR_PARC PARC ON  V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_EMP = PARC.CD_EMP 
														AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FILIAL = PARC.CD_FILIAL
													    AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_DP = PARC.NR_DP 
														AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.ANO   = PARC.ANO

					 
                     LEFT OUTER JOIN V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL
                     ON V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_EMP = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.CD_EMP
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FILIAL = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.CD_FILIAL
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.DT_CAD = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.DT_CAD
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_DESP_REC = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.CD_DESP_REC
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_NF = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.NR_NF
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FORN = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.CD_FORN
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_DP = V_PG_DESP_RAT_CONTAS_CENTRO_CUSTO_PAGAR_CONTABIL.NR_DP
                     INNER JOIN PRC_FILIAL
                     ON V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_EMP = PRC_FILIAL.CD_EMP
                        AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FILIAL = PRC_FILIAL.CD_FILIAL
					 OUTER APPLY (SELECT MIN(PARC) AS MIN_PARC
									FROM PG_CRED PG2
									WHERE V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_EMP = PG2.CD_EMP 
														AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FILIAL = PG2.CD_FILIAL
													    AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.NR_DP = PG2.NR_DP 
														AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.ANO = PG2.ANO
														AND CAST(PG2.DT_CAD AS DATE) BETWEEN CAST(@DT_INI AS DATE) AND CAST(@DT_FIM AS DATE)
														) PG_CRED_PARC
                   WHERE V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_EMP = @CD_EMP
                      AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.DT_CAD BETWEEN @DT_INI AND @DT_FIM
                      AND V_PG_DESP_RAT_CONTAS_PAGAR_CONTABIL.CD_FILIAL IN
                (
                    SELECT CD_FILIAL
                    FROM PRC_GRP_ECON_PRC_FILIAL
                    WHERE CD_GRP_ECON = @CD_GRP_ECON  )

			 ) SELECT * FROM CTE_PG_DESP_RAT_CONTAS	ORDER BY RZ_FORN,NR_DP,NR_NF,PARC ASC
			 
            --ABRINDO CURSOR
            OPEN RS_RESULT;
		
            --ATRIBUINDO VALORES DO SELECT NAS VARIÁVEIS
            FETCH NEXT FROM RS_RESULT INTO @RS_RZ_FORN, @RS_NR_CNT, @RS_CNT_CENTRO_CTB, @RS_CD_FILIAL, @RS_DT_EMIS, 
										   @RS_CD_FORN, @RS_HIST, @RS_CD_DESP_REC, @RS_CD_CNT_CTB_RED, @RS_DS_DESP_REC, 
										   @RS_RATEIO_CENTRO_CUSTO, @RS_VLR_RAT_DESP, @RS_VLR_RAT_CENTRO_CUSTO, @RS_DS_CENTRO_CTB, 
										   @RS_NR_NF, @RS_NM_FANT, @RS_NR_DP,@CD_PG_CRED,@ANO,@NR_TIT,@PARC,@RS_VLR_DUPL, @MIN_PARC;						
           --INICIANDO LAÇO
            WHILE @@FETCH_STATUS = 0
                BEGIN
                    SET @DADOS_DUP_ATUAL = CAST(@RS_CD_FORN AS VARCHAR)+'-'+CAST(@RS_NR_DP AS VARCHAR)+'-'+CAST(@RS_NR_NF AS VARCHAR)+'-'+CAST(@RS_CD_FILIAL AS VARCHAR)+'-'+CAST(@PARC AS VARCHAR);												
				
                    ------------------------------------------------------------------------------------------------------------------
                    --CONTA ESTOQUE - NATUREZA DE OPERACAO
                    ------------------------------------------------------------------------------------------------------------------

                    IF @DADOS_DUP_ANT <> @DADOS_DUP_ATUAL
                        BEGIN
                            SET @DADOS_DUP_ANT = CAST(@RS_CD_FORN AS VARCHAR)+'-'+CAST(@RS_NR_DP AS VARCHAR)+'-'+CAST(@RS_NR_NF AS VARCHAR)+'-'+CAST(@RS_CD_FILIAL AS VARCHAR)+'-'+CAST(@PARC AS VARCHAR);
                            SELECT @RET_CD_CTB_CNT = CD_CTB_CNT
                                 , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                            FROM UFD_BUSCA_CONTA_PG_FORN(@CD_EMP, @RS_CD_FORN);
                            IF @RS_HIST <> ''
                                BEGIN
                                    SET @HIST = 'VR. REF. COMPRA\PREST.SERVICO FORNECEDOR '+@RS_RZ_FORN+' - '+@RS_HIST+' CONF. DOC NR '+(CASE
                                                                                                                                             WHEN @RS_NR_NF = 0
                                                                                                                                             THEN 'DIVERSOS'
                                                                                                                                             ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                                         END);
                                END;
                            ELSE
                                BEGIN
                                    SET @HIST = 'VR. REF. COMPRA\PREST.SERVICO FORNECEDOR '+@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);
                                END;		                						
				
					   SET @NUMERODUPL =  RIGHT('0000'+ CAST(@RS_CD_FILIAL AS VARCHAR(4)),4) + CAST(@RS_NR_DP AS VARCHAR )
					   SET @NUM_DUPL  =  @NUMERODUPL 
					   SET @HIST = REPLACE (@HIST, '	',' ');
					   
                            ------------------------------------------------------------------------------------------------------------------
                            --CONTAS ESTOQUE - CREDITO - NATUREZA DE OPERAÇÃO
                            ------------------------------------------------------------------------------------------------------------------
 
 -- Capturando valor total da duplicata para composição do credito

                            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 @CD_EMP AS CD_EMP
							            , @CD_FILIAL AS CD_FILIAL_EXPORT
							            , @RS_CD_FILIAL AS CD_FILIAL
                                        , 15 AS CD_MOVIMENTO
                                        , 'PAGAMENTO FORNECEDOR - APROPRIAR' AS MOVIMENTO
                                        , 'PAGTO DUPL. APROPRIAR - 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_EMIS AS DT_MOV
                                        , @HIST AS HIST
									    , @RS_VLR_DUPL AS VLR_LANC--CASE WHEN  @PARC > 1 THEN @RS_VLR_RAT_DESP ELSE   @RS_VLR_DUPL END AS VLR_LANC
										, 'C' AS TP_TRANSA
                                        , 0 AS RATEIO_CENTRO_CUSTO
                                        , '' AS DS_CENTRO_CUSTO
                                        , 0 AS CNT_CENTRO_CUSTO
                                        , 0 AS VLR_CENTRO_CUSTO
                                        , 'FORNECEDOR' AS ORIG_CONTA
                                        , @RS_CD_FORN AS COD_CONTA
                                        , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                        , 'T' AS TIPO_LANCTO
                                        , 0 AS CD_EVENTO
							        	,@NUM_DUPL
							         	,@ANO
							        	,@NR_TIT
								        , 0 AS CD_BC_LANC
										, @CD_PG_CRED as COD_INTERNO ;
                        END;
                    SET @DADOS_DUP_DESP_ATUAL = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+@DADOS_DUP_ATUAL;
                    IF (@DADOS_DUP_DESP_ATUAL <> @DADOS_DUP_DESP_ANT) and @PARC = @MIN_PARC
                        BEGIN
                            SET @DADOS_DUP_DESP_ANT = CAST(@RS_CD_DESP_REC AS VARCHAR)+'-'+@DADOS_DUP_ATUAL;
                            IF @RS_HIST <> ''
                                BEGIN
                                    SET @HIST = 'VR. REF. COMPRA\PREST.SERVICO FORNECEDOR '+@RS_RZ_FORN+' - '+@RS_HIST+' CONF. DOC NR '+(CASE
                                                                                                                                             WHEN @RS_NR_NF = 0
                                                                                                                                             THEN 'DIVERSOS'
                                                                                                                                             ELSE RIGHT('00000000'+CAST(@RS_NR_NF AS VARCHAR), 8)
                                                                                                                                         END);
                                END;
                            ELSE
                                BEGIN
                                    SET @HIST = 'VR. REF. COMPRA\PREST.SERVICO FORNECEDOR '+@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);
                                END;	
						SET @HIST = REPLACE (@HIST, '	',' ');
                            ------------------------------------------------------------------------------------------------------------------
                            --CONTAS ESTOQUE - DEBITO - NATUREZA DE OPERAÇÃO E DESPESAS
                            ------------------------------------------------------------------------------------------------------------------
                            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 @CD_EMP AS CD_EMP
							     , @CD_FILIAL AS CD_FILIAL_EXPORT
							     , @RS_CD_FILIAL AS CD_FILIAL
                                        , 15 AS CD_MOVIMENTO
                                        , 'PAGAMENTO FORNECEDOR - APROPRIAR' AS MOVIMENTO
                                        , '' AS OPERACAO
                                        , 'PAGTO DUPL. APROPRIAR - DEBITO' AS OPERACAO_DEBITO
                                        , 0 AS CD_CNT_RED_CREDITO
                                        , '' AS CD_CNT_CREDITO
                                        , @RS_CD_CNT_CTB_RED AS CD_CNT_RED_DEBITO
                                        , @RS_NR_CNT AS CD_CNT_DEBITO
                                        , @RS_DT_EMIS AS DT_MOV
                                        , @HIST AS HIST
                                        , CASE @RS_VLR_RAT_DESP WHEN 0 THEN @RS_VLR_DUPL ELSE @RS_VLR_RAT_DESP END AS VLR_LANC--@RS_VLR_RAT_DESP AS VLR_LANC
                                        , 'D' AS TP_TRANSA
                                        , (CASE
                                               WHEN @RS_VLR_RAT_CENTRO_CUSTO = 0
                                               THEN 0
                                               ELSE @RS_RATEIO_CENTRO_CUSTO
                                           END) AS RATEIO_CENTRO_CUSTO
                                        , (CASE
                                               WHEN @RS_VLR_RAT_CENTRO_CUSTO = 0
                                               THEN ''
                                               ELSE @RS_DS_CENTRO_CTB
                                           END) AS DS_CENTRO_CUSTO
                                        , (CASE
                                               WHEN @RS_VLR_RAT_CENTRO_CUSTO = 0
                                               THEN ''
                                               ELSE @RS_CNT_CENTRO_CTB
                                           END) AS CNT_CENTRO_CUSTO
                                        , (CASE
                                               WHEN @RS_VLR_RAT_CENTRO_CUSTO = 0
                                               THEN 0
                                               ELSE @RS_VLR_RAT_CENTRO_CUSTO
                                           END) AS VLR_CENTRO_CUSTO
                                        , 'DESP\REC' 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
								,@ANO
								,@NR_TIT
								, 0 AS CD_BC_LANC
							    , @CD_PG_CRED as COD_INTERNO ;
                        END;			

                    ------------------------------------------------------------------------------------------------------------------
                    --PRÓXIMO REGISTRO				
                    ------------------------------------------------------------------------------------------------------------------
                    --ATRIBUINDO VALORES DO SELECT NAS VARIÁVEIS
                    FETCH NEXT FROM RS_RESULT INTO @RS_RZ_FORN, @RS_NR_CNT, @RS_CNT_CENTRO_CTB, @RS_CD_FILIAL, @RS_DT_EMIS, 
												   @RS_CD_FORN, @RS_HIST, @RS_CD_DESP_REC, @RS_CD_CNT_CTB_RED, @RS_DS_DESP_REC, 
												   @RS_RATEIO_CENTRO_CUSTO, @RS_VLR_RAT_DESP, @RS_VLR_RAT_CENTRO_CUSTO, @RS_DS_CENTRO_CTB, 
												   @RS_NR_NF, @RS_NM_FANT, @RS_NR_DP,@CD_PG_CRED,@ANO,@NR_TIT,@PARC,@RS_VLR_DUPL, @MIN_PARC;	
                END;
            CLOSE RS_RESULT;
            DEALLOCATE RS_RESULT;	
		
	
            ------------------------------------------------------------------------------------------------------------------
            --IMPOSTOS
            ------------------------------------------------------------------------------------------------------------------		

            DECLARE RS_RESULT CURSOR
            FOR SELECT PG_CRED.CD_FILIAL
                     , PG_CRED.CD_FORN
                     , PG_CRED.HIST
                     , PG_FORN.RZ_FORN
                     , GLB_IMPOSTOS.DS_IMP
                     , PG_CRED_IMPOSTO.VLR_IMP
                     , GLB_DESP_REC.CD_CNT_CTB_RED
                     , GLB_DESP_REC.NR_CNT
                     , ISNULL(PG_CRED_NF.NR_NF, 0) AS NR_NF
                     , PRC_FILIAL.NM_FANT
                     , PG_CRED.DT_CAD AS DT_EMIS
                     , GLB_DESP_REC.CD_DESP_REC
					 , PG_CRED.CD_PG_CRED
					 , PG_CRED.NR_DP
					 , PG_CRED.ANO					
                FROM
                     PG_CRED
                     INNER JOIN PG_FORN
                     ON PG_CRED.CD_EMP = PG_FORN.CD_EMP
                        AND PG_CRED.CD_FORN = PG_FORN.CD_FORN
                     INNER JOIN PG_CRED_IMPOSTO
                     ON PG_CRED.CD_EMP = PG_CRED_IMPOSTO.CD_EMP
                        AND PG_CRED.CD_FILIAL = PG_CRED_IMPOSTO.CD_FILIAL
                        AND PG_CRED.CD_PG_CRED = PG_CRED_IMPOSTO.CD_PG_CRED
                     INNER JOIN GLB_IMPOSTOS
                     ON PG_CRED_IMPOSTO.CD_IMP = GLB_IMPOSTOS.CD_CTR
                     INNER JOIN GLB_DESP_REC
                     ON GLB_IMPOSTOS.CD_DESP_REC = GLB_DESP_REC.CD_DESP_REC
                     LEFT OUTER JOIN PG_CRED_NF
                     ON PG_CRED.CD_EMP = PG_CRED_NF.CD_EMP
                        AND PG_CRED.CD_FILIAL = PG_CRED_NF.CD_FILIAL
                        AND PG_CRED.NR_DP = PG_CRED_NF.NR_DP
                        AND PG_CRED.ANO = PG_CRED_NF.ANO
                     INNER JOIN PRC_FILIAL
                     ON PG_CRED.CD_EMP = PRC_FILIAL.CD_EMP
                        AND PG_CRED.CD_FILIAL = PRC_FILIAL.CD_FILIAL
                WHERE PG_CRED.CD_EMP = @CD_EMP
                      AND PG_CRED.DT_CAD BETWEEN @DT_INI AND @DT_FIM
                      AND PG_CRED.CD_FILIAL IN
                (
                    SELECT CD_FILIAL
                    FROM PRC_GRP_ECON_PRC_FILIAL
                    WHERE CD_GRP_ECON = @CD_GRP_ECON
                )
                      AND PG_FORN.IGNORAR_EXP_CONTABIL = 0
                ORDER BY PG_CRED.CD_FORN
                       , PG_CRED.HIST;
				
			
            --ABRINDO CURSOR
            OPEN RS_RESULT;
		
            --ATRIBUINDO VALORES DO SELECT NAS VARIÁVEIS
            FETCH NEXT FROM RS_RESULT INTO @RS_IMP_CD_FILIAL, @RS_IMP_CD_FORN, @RS_IMP_HIST, @RS_IMP_RZ_FORN, 
										   @RS_IMP_DS_IMP, @RS_IMP_VLR_IMP, @RS_IMP_CD_CNT_CTB_RED, @RS_IMP_NR_CNT, 
										   @RS_IMP_NR_NF, @RS_IMP_NM_FANT, @RS_IMP_DT_EMIS, @RS_IMP_CD_DESP_REC,
										   @CD_PG_CRED,@RS_NR_DP,@ANO;			
					 

            --INICIANDO LAÇO
            WHILE @@FETCH_STATUS = 0
                BEGIN
                    SELECT @RET_CD_CTB_CNT = CD_CTB_CNT
                         , @RET_CD_CTB_CNT_RED = CD_CTB_CNT_RED
                    FROM UFD_BUSCA_CONTA_PG_FORN(@CD_EMP, @RS_IMP_CD_FORN);
                    SET @HIST = 'RETENCAO DE IMPOSTO '+@RS_IMP_DS_IMP+' - REF: '+@RS_IMP_RZ_FORN+' CONF. DOC NR '+(CASE
                                                                                                                       WHEN @RS_IMP_NR_NF = 0
                                                                                                                       THEN 'DIVERSOS'
                                                                                                                       ELSE RIGHT('00000000'+CAST(@RS_IMP_NR_NF AS VARCHAR), 8)
                                                                                                                   END);

				SET @NUMERODUPL = RIGHT('0000'+ CAST(@RS_IMP_CD_FILIAL AS VARCHAR(4)),4) + CAST(@RS_NR_DP AS VARCHAR )
				SET @NUM_DUPL  =  @NUMERODUPL 
				SET @HIST = REPLACE (@HIST, '	',' ');
                    ------------------------------------------------------------------------------------------------------------------
                    --CONTAS FORNECEDOR - DÉBITO - 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 @CD_EMP AS CD_EMP
							    , @CD_FILIAL AS CD_FILIAL_EXPORT
							    , @RS_IMP_CD_FILIAL AS CD_FILIAL
                                , 15 AS CD_MOVIMENTO
                                , 'PAGAMENTO FORNECEDOR - APROPRIAR' AS MOVIMENTO
                                , '' AS OPERACAO
                                , 'RETENCAO DE IMPOSTOS - 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_IMP_DT_EMIS AS DT_MOV
                                , @HIST AS HIST
                                , @RS_IMP_VLR_IMP AS VLR_LANC
                                , 'D' AS TP_TRANSA
                                , 0 AS RATEIO_CENTRO_CUSTO
                                , '' AS DS_CENTRO_CUSTO
                                , 0 AS CNT_CENTRO_CUSTO
                                , 0 AS VLR_CENTRO_CUSTO
                                , 'FORNECEDOR' AS ORIG_CONTA
                                , @RS_IMP_CD_FORN AS COD_CONTA
                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                , 'T' AS TIPO_LANCTO
                                , 0 AS CD_EVENTO
								,@NUM_DUPL
								,@ANO
								,@NR_TIT
								, 0 AS CD_BC_LANC
							    , @CD_PG_CRED as COD_INTERNO ;								
                    ------------------------------------------------------------------------------------------------------------------
                    --CONTAS IMPOSTO - 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 @CD_EMP AS CD_EMP
							     , @CD_FILIAL AS CD_FILIAL_EXPORT
							     , @RS_IMP_CD_FILIAL AS CD_FILIAL
                                , 15 AS CD_MOVIMENTO
                                , 'PAGAMENTO FORNECEDOR - APROPRIAR' AS MOVIMENTO
                                , 'RETENCAO DE IMPOSTOS - CREDITO' AS OPERACAO
                                , '' AS OPERACAO_DEBITO
                                , ISNULL(@RS_IMP_CD_CNT_CTB_RED, 0) AS CD_CNT_RED_CREDITO
                                , ISNULL(@RS_IMP_NR_CNT, 'SEM CLASSIFICACAO') AS CD_CNT_CREDITO
                                , 0 AS CD_CNT_RED_DEBITO
                                , '' AS CD_CNT_DEBITO
                                , @RS_IMP_DT_EMIS AS DT_MOV
                                , @HIST AS HIST
                                , @RS_IMP_VLR_IMP AS VLR_LANC
                                , 'C' AS TP_TRANSA
                                , 0 AS RATEIO_CENTRO_CUSTO
                                , '' AS DS_CENTRO_CUSTO
                                , 0 AS CNT_CENTRO_CUSTO
                                , 0 AS VLR_CENTRO_CUSTO
                                , 'DESP\REC' AS ORIG_CONTA
                                , @RS_IMP_CD_DESP_REC AS COD_CONTA
                                , OBJECT_NAME(@@PROCID) AS NM_PROCEDURE
                                , 'T' AS TIPO_LANCTO
                                , 0 AS CD_EVENTO
								,@NUM_DUPL
								,@ANO
								,@NR_TIT
								, 0 AS CD_BC_LANC
							    , @CD_PG_CRED as COD_INTERNO ;								
		
                    --ATRIBUINDO VALORES DO SELECT NAS VARIÁVEIS
                    FETCH NEXT FROM RS_RESULT INTO @RS_IMP_CD_FILIAL, @RS_IMP_CD_FORN, @RS_IMP_HIST, @RS_IMP_RZ_FORN, 
												   @RS_IMP_DS_IMP, @RS_IMP_VLR_IMP, @RS_IMP_CD_CNT_CTB_RED, @RS_IMP_NR_CNT, 
												   @RS_IMP_NR_NF, @RS_IMP_NM_FANT, @RS_IMP_DT_EMIS, @RS_IMP_CD_DESP_REC,
												   @CD_PG_CRED,@RS_NR_DP,@ANO;
                END;
            CLOSE RS_RESULT;
            DEALLOCATE RS_RESULT;
        END;
    END TRY
    BEGIN CATCH
		DECLARE @MENSAGEMERRO	VARCHAR(250);
		DECLARE @SEVERIDADEERRO INT;
		DECLARE @ESTADOERRO		INT;
	
		SELECT	@MENSAGEMERRO = ERROR_MESSAGE(), 
				@SEVERIDADEERRO = ERROR_SEVERITY(), 
				@ESTADOERRO = ERROR_STATE();
		CLOSE RS_RESULT;
        DEALLOCATE RS_RESULT;
		
        INSERT INTO ADM_ERRO (NUMERO, SEVERIDADE, ESTADO, ROTINA, LINHA, MENSAGEM, DTERRO)
		SELECT
			ERROR_NUMBER() AS NUMERO,
			@SEVERIDADEERRO AS SEVERIDADE,
			@ESTADOERRO AS ESTADO,
			ERROR_PROCEDURE() AS ROTINA,
			ERROR_LINE() AS LINHA,
			@MENSAGEMERRO AS MENSAGEM,
			GETDATE() AS DTERRO;
			
			RAISERROR (@MENSAGEMERRO, @SEVERIDADEERRO, @ESTADOERRO);
			RETURN -2;	
			
    END CATCH;
	
	
	 