
IF EXISTS
(
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'[P_PDV_VD_IT_COMIS_RECALC_EXECUTE_ALL]')
          AND type IN(N'P', N'PC')
)
    BEGIN
        DROP PROCEDURE [P_PDV_VD_IT_COMIS_RECALC_EXECUTE_ALL]
    END;
GO

--EXEC P_PDV_VD_IT_COMIS_RECALC_EXECUTE_ALL  '2017-08-01','2017-08-30', 12
CREATE PROCEDURE [P_PDV_VD_IT_COMIS_RECALC_EXECUTE_ALL] @DT_INI DATE = NULL,
                                                              @DT_FIM DATE = NULL,
															  @CD_FILIAL_PAR INT=0
AS
BEGIN TRY
    BEGIN
        PRINT 'Inicio do recalculo';
        SET NOCOUNT ON;
        DECLARE @CD_FILIAL INT;
        DECLARE @CD_EMP INT 
		DECLARE @DT_INI_PROC DATETIME
		DECLARE @DT_FIM_PROC DATETIME
		DECLARE @CD_CTR INT
		DECLARE @FLAG_PROCESSAMENTO_HISTORICO INT = 0

		IF @DT_INI IS NULL
            BEGIN
                SELECT @DT_INI = GETDATE();
                SET @DT_FIM = @DT_INI;
                SET @DT_INI = DATEADD(DAY,-3,@DT_INI);
            
			END;


IF NOT EXISTS(SELECT
				TOP 1 CD_CTR
			  FROM
				PDV_VD_COMIS_PROCESSAMENTO
			  WHERE
				STS_PROC IN (0,1))
begin
    PRINT 'Sem Agendamento'
    DECLARE filiaisComissao CURSOR FAST_FORWARD FOR 
	SELECT 
		CD_EMP, 
		CD_FILIAL,
		@DT_INI,
		@DT_FIM,
		0 AS CD_CTR,
		0 AS FLAG_HISTORICO
        FROM 
			PRC_FILIAL
		WHERE 
			CD_FILIAL = CASE WHEN  @CD_FILIAL_PAR > 0 THEN  @CD_FILIAL_PAR ELSE CD_FILIAL END ;

end        
else
begin
	PRINT 'Agendamento'
	UPDATE
		PDV_VD_COMIS_PROCESSAMENTO
	SET 
		STS_PROC = 0,
		DT_PROC_INI=NULL,
		DT_PROC_FIM=NULL
    WHERE
	   STS_PROC <>2 

    DECLARE filiaisComissao CURSOR FAST_FORWARD FOR 
	SELECT 
		CD_EMP, 
		CD_FILIAL,
		DT_INI,
		DT_FIM,
		CD_CTR,
		FLAG_PROCESSAMENTO_HISTORICO AS FLAG_HISTORICO
        FROM 
		  PDV_VD_COMIS_PROCESSAMENTO
	   WHERE 
		  CD_FILIAL = CASE WHEN  @CD_FILIAL_PAR > 0 THEN  @CD_FILIAL_PAR ELSE CD_FILIAL END
		  AND STS_PROC = 0;
end	
	
	
		OPEN filiaisComissao;
        FETCH NEXT FROM filiaisComissao INTO @CD_EMP,@CD_FILIAL,@DT_INI_PROC,@DT_FIM_PROC,@CD_CTR, @FLAG_PROCESSAMENTO_HISTORICO;
        WHILE @@FETCH_STATUS = 0
            BEGIN
             PRINT 'Filial '+ CONVERT( VARCHAR(10), @CD_FILIAL) +' '+CONVERT(VARCHAR, @DT_INI_PROC, 112)
					   +' a '+CONVERT(VARCHAR, @DT_FIM_PROC, 112) 
					   + ' ' + convert(varchar,getdate(),108);
             
			 IF @CD_CTR > 0
			 begin
				UPDATE
					PDV_VD_COMIS_PROCESSAMENTO
				SET 
					STS_PROC = 1,
					DT_PROC_INI=GETDATE()
				WHERE
					CD_CTR = @CD_CTR
			 end
			    

			 IF ISNULL(@FLAG_PROCESSAMENTO_HISTORICO,0) = 0
			 BEGIN

				 PRINT 'Calculando cupons fiscais ' + convert(varchar,getdate(),108);
					EXEC dbo.P_PDV_VD_IT_COMIS_RECALC
						 @CD_EMP,
						 @CD_FILIAL,
						 '',
						@DT_INI_PROC,
						@DT_FIM_PROC;
                
				 PRINT 'Calculando notas fiscais ' + convert(varchar,getdate(),108);
					EXEC dbo.P_EST_NF_SAI_IT_COMIS_RECALC
						 @CD_EMP,
						 @CD_FILIAL,
						 '',
						@DT_INI_PROC,
						@DT_FIM_PROC;

				 PRINT 'Calculando cupons quantidade ' + convert(varchar,getdate(),108);
					EXEC P_PDV_VD_IT_COMIS_RECALC_QTDE
						 @CD_EMP,
						 @CD_FILIAL,
						 '',
						@DT_INI_PROC,
						@DT_FIM_PROC,
						0;
				PRINT 'Calculando regressao de comissao ' + convert(varchar,getdate(),108);
					EXEC P_PDV_VD_IT_COMIS_RECALC_REGRESSAO 
						@CD_EMP,
						@CD_FILIAL,
						'',
						@DT_INI_PROC,
						@DT_FIM_PROC,
						0
				END
				ELSE
				BEGIN
					EXEC dbo.P_PDV_VD_IT_COMIS_RECALC_HISTORICO
						 @CD_EMP,
						 @CD_FILIAL,
						 '',
						@DT_INI_PROC,
						@DT_FIM_PROC;
                
				 PRINT 'Calculando notas fiscais ' + convert(varchar,getdate(),108);
					EXEC dbo.P_EST_NF_SAI_IT_COMIS_RECALC_HISTORICO
						 @CD_EMP,
						 @CD_FILIAL,
						 '',
						@DT_INI_PROC,
						@DT_FIM_PROC;

				 PRINT 'Calculando cupons quantidade ' + convert(varchar,getdate(),108);
					EXEC P_PDV_VD_IT_COMIS_RECALC_QTDE_HISTORICO
						 @CD_EMP,
						 @CD_FILIAL,
						 '',
						@DT_INI_PROC,
						@DT_FIM_PROC,
						0;
				PRINT 'Calculando regressao de comissao ' + convert(varchar,getdate(),108);
					EXEC P_PDV_VD_IT_COMIS_RECALC_REGRESSAO_HISTORICO
						@CD_EMP,
						@CD_FILIAL,
						'',
						@DT_INI_PROC,
						@DT_FIM_PROC,
						0
				END


				 IF @CD_CTR > 0
				 begin
				 
					PRINT 'Gravando processamento de comissao ' + convert(varchar,getdate(),108);

					UPDATE
						PDV_VD_COMIS_PROCESSAMENTO
					SET 
						STS_PROC = 2,
						DT_PROC_FIM=GETDATE()
					WHERE
						CD_CTR = @CD_CTR
				 end

                FETCH NEXT FROM filiaisComissao INTO @CD_EMP,@CD_FILIAL,@DT_INI_PROC,@DT_FIM_PROC,@CD_CTR, @FLAG_PROCESSAMENTO_HISTORICO;
            END;
        PRINT 'Concluido.';
        CLOSE filiaisComissao;
        DEALLOCATE filiaisComissao;
    END;
END TRY
BEGIN CATCH

   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;
