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

CREATE PROCEDURE P_PROCESSA_PENDENCIA_IBS_CBS
(
    @CD_TRIB_IBS_CBS INT
)
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;


	IF EXISTS (SELECT 1 
				FROM EST_PROD_CPL_IBS_CBS_PEND
				WHERE CD_TRIB_IBS_CBS = @CD_TRIB_IBS_CBS
				AND STS_GERACAO = 0)
	BEGIN


		UPDATE EST_PROD_CPL_IBS_CBS_PEND
		SET STS_GERACAO = 1
		WHERE CD_TRIB_IBS_CBS = @CD_TRIB_IBS_CBS
		AND STS_GERACAO = 0;

		CREATE TABLE #TEMP (
			CD_EMP INT,
			CD_FILIAL INT,
			CD_TRIB_IBS_CBS INT,
			CD_PROD INT,
			CD_MOV_OP INT,
			ENVIA_PDV INT
		)

		BEGIN TRY

			INSERT INTO #TEMP
			(
				CD_EMP,
				CD_FILIAL,
				CD_TRIB_IBS_CBS,
				CD_PROD,
				CD_MOV_OP
			)
			SELECT DISTINCT
				1 AS CD_EMP,
				PRF.CD_FILIAL,
				E.CD_TRIB_IBS_CBS,
				P.CD_PROD,
				G.CD_MOV_OP
			FROM EST_TRIB_IBS_CBS E
			INNER JOIN EST_TRIB_IBS_CBS_NCM N
				ON E.CD_TRIB_IBS_CBS = N.CD_TRIB_IBS_CBS
			INNER JOIN EST_PROD P
				ON P.NR_NCM = N.NR_NCM
			INNER JOIN EST_TRIB_IBS_CBS_GLB_MOV_OP G
				ON E.CD_TRIB_IBS_CBS = G.CD_TRIB_IBS_CBS
			INNER JOIN PRC_REGIAO_FISCAL PR
				ON PR.CD_REGIAO_FISCAL = E.CD_REGIAO_FISCAL
			INNER JOIN PRC_REGIAO_FISCAL_PRC_FILIAL PRF
				ON PRF.CD_REGIAO_FISCAL = E.CD_REGIAO_FISCAL
			INNER JOIN PRC_FILIAL_CONFIG CFG ON CFG.CD_FILIAL = PRF.CD_FILIAL
									AND CFG.CD_CHAVE = 'CD_MOV_OP_VENDA_PDV'
									AND CFG.VALOR = G.CD_MOV_OP
			WHERE E.CD_TRIB_IBS_CBS = @CD_TRIB_IBS_CBS

			/*Força o envio pdv - No caso da natureza coincidir com a config da filial CD_MOV_OP_VENDA_PDV*/

				DECLARE 
				@CD_EMP INT,
				@CD_FILIAL INT,
				@CD_PROD INT,
				@CD_TRIB_IBS_CBS_CS INT;

				DECLARE cur_atualiza_cpl CURSOR LOCAL FAST_FORWARD FOR
					SELECT 
						CD_EMP,
						CD_FILIAL,
						CD_PROD,
						CD_TRIB_IBS_CBS
					FROM #TEMP;

				OPEN cur_atualiza_cpl;

				FETCH NEXT FROM cur_atualiza_cpl
				INTO @CD_EMP, @CD_FILIAL, @CD_PROD, @CD_TRIB_IBS_CBS_CS;

				WHILE @@FETCH_STATUS = 0
				BEGIN
					UPDATE EST_PROD_CPL
					SET CD_TRIB_IBS_CBS_VD = @CD_TRIB_IBS_CBS_CS
					WHERE CD_EMP = @CD_EMP
					  AND CD_FILIAL = @CD_FILIAL
					  AND CD_PROD = @CD_PROD;

					FETCH NEXT FROM cur_atualiza_cpl
					INTO @CD_EMP, @CD_FILIAL, @CD_PROD, @CD_TRIB_IBS_CBS_CS;
				END

			CLOSE cur_atualiza_cpl;
			DEALLOCATE cur_atualiza_cpl;


			UPDATE EST_PROD_CPL_IBS_CBS_PEND
			SET STS_GERACAO = 2,
				DT_PROCESSAMENTO = GETDATE()
			WHERE CD_TRIB_IBS_CBS = @CD_TRIB_IBS_CBS
			AND STS_GERACAO = 1;

		END TRY
		BEGIN CATCH

			IF @@TRANCOUNT > 0

				UPDATE EST_PROD_CPL_IBS_CBS_PEND
				SET STS_GERACAO = 3,
					DT_PROCESSAMENTO = GETDATE()
				WHERE CD_TRIB_IBS_CBS = @CD_TRIB_IBS_CBS
				AND STS_GERACAO = 1;

			THROW;

		END CATCH
	END
END;