IF OBJECT_ID('P_PDV_VD_IT_TRIBUTACAO_CADASTRO_VENDA_REALIZADA') IS NOT NULL
	DROP PROCEDURE P_PDV_VD_IT_TRIBUTACAO_CADASTRO_VENDA_REALIZADA
GO
--EXEC P_PDV_VD_IT_TRIBUTACAO_CADASTRO_VENDA_REALIZADA 1,3, '2017-02-01','2017-02-28'
CREATE PROCEDURE [dbo].[P_PDV_VD_IT_TRIBUTACAO_CADASTRO_VENDA_REALIZADA] (@CD_EMP INT=1,
																		  @CD_FILIAL INT, 
																		  @DT_INI DATETIME, 
																		  @DT_FIM DATETIME,
																		  @ANO INT=0,
																		  @MES INT=0)
WITH ENCRYPTION AS
SET NOCOUNT ON 
DECLARE @CD_VD INT
DECLARE @CD_IT INT
DECLARE @CD_TRIB_FC VARCHAR(3)
DECLARE @PERC_ICMS MONEY
DECLARE @CD_PROD INT
DECLARE @CONTADOR INT
DECLARE @PERC_RED MONEY

DECLARE @DTINI AS DATETIME, @DTFIM AS DATETIME, @DTATUAL AS DATETIME;
SET @DTATUAL= CONVERT(CHAR(10),GETDATE(),112)

SET NOCOUNT ON 	
	IF @MES > 0 
	begin
		SET @DTINI  =  CONVERT(VARCHAR, @ANO*100+@MES ) + '01';
		SET @DTFIM  =  dbo.F_FINAL_MES(@DTINI);
	end

	IF @MES = 0 
	begin
		SET @DTINI  =  @DT_INI;
		SET @DTFIM  =  @DT_FIM;
	end

CREATE TABLE #EstTrib (CD_TRIB INT,
					   CD_TRIB_FC VARCHAR(10))

INSERT INTO #EstTrib
SELECT
	CD_TRIB,
	CASE WHEN TIPO_REGIME_EMPRESA=0  THEN
		CASE WHEN (SUBS_TRIB+SUBS_TRIB_ANT) > 0 THEN
			'060'
		WHEN ISENTO > 0 THEN
			'040'
		WHEN ICMS > 0 THEN
			'000'
		ELSE
			CD_TRIB_FC 
		END
	ELSE --SIMPLES NACIONAL
		CASE WHEN (SUBS_TRIB+SUBS_TRIB_ANT)>0 THEN
			'060'
		WHEN ISENTO > 0 THEN
			'040'
		WHEN ICMS > 0 THEN
			'000'
		ELSE
			CD_TRIB_FC 
		END
	END AS trib_cadastro
FROM
	EST_TRIB

DECLARE CCorrigeCupons CURSOR FAST_FORWARD FOR 
SELECT 
	IT.CD_VD, 
	IT.CD_IT, 
	IT.CD_PROD, 
	TR.CD_TRIB_FC,
	T.PERC_ICMS,
	T.PERC_RED
FROM   
	PDV_VD_IT IT INNER JOIN EST_PROD_CPL_TRIB_EST T ON
	IT.CD_EMP = T.CD_EMP AND
	IT.CD_FILIAL = T.CD_FILIAL AND
	IT.CD_PROD = T.CD_PROD 
	INNER JOIN PRC_FILIAL ON
	IT.CD_EMP = PRC_FILIAL.CD_EMP AND
	IT.CD_FILIAL = PRC_FILIAL.CD_FILIAL 
	INNER JOIN #EstTrib TR ON
	T.CD_TRIB = TR.CD_TRIB 
WHERE  
	IT.CD_EMP =@CD_EMP
	AND IT.CD_FILIAL=@CD_FILIAL
	AND IT.DT_VD BETWEEN @DTINI AND @DTFIM
	and RIGHT(TR.CD_TRIB_FC,2) COLLATE SQL_Latin1_General_CP1_CI_AS <> RIGHT(IT.CD_TRIB_FC,2)
	AND T.TP_MOV=0
	AND T.TP_TRANSA=1

OPEN CCorrigeCupons
FETCH NEXT FROM CCorrigeCupons INTO @CD_VD,@CD_IT,@CD_PROD,@CD_TRIB_FC,@PERC_ICMS,@PERC_RED
	WHILE @@FETCH_STATUS=0
	  begin
	  PRINT 'Filial.: ' + CONVERT(VARCHAR, @CD_FILIAL) + ' ' + CONVERT(VARCHAR, @CONTADOR) + ' ' + CONVERT(VARCHAR, GETDATE (),108)
	  update
		PDV_VD_IT
	  set 
		CD_TRIB_FC=@CD_TRIB_FC,
		TX_ICMS_IT=@PERC_ICMS,
		TX_RED_IT=@PERC_RED
	  WHERE
		CD_EMP =@CD_EMP
		AND CD_FILIAL = @CD_FILIAL
		AND CD_VD = @CD_VD
		AND CD_IT = @CD_IT
	  SET @CONTADOR=@CONTADOR+1
	FETCH NEXT FROM CCorrigeCupons INTO @CD_VD,@CD_IT,@CD_PROD,@CD_TRIB_FC,@PERC_ICMS,@PERC_RED
	end
PRINT 'Concluido.'
CLOSE CCorrigeCupons;
DEALLOCATE CCorrigeCupons;
DROP TABLE #EstTrib;