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

CREATE PROCEDURE [P_PDV_VD_IT_COMIS_RECALC_HISTORICO] (   @CD_EMP      INT = 1,
										   @CD_FILIAL   INT, 
										   @CD_FUN      VARCHAR(MAX)='',                           
										   @DT_INI      DATETIME = NULL,
										   @DT_FIM      DATETIME = NULL,
										   @CD_PROD     INT=0,
										   @consulta	tinyint = 0) 
AS
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
--BEGIN TRY
BEGIN
DECLARE @CD_EMP_RS		INT
		,@CD_FILIAL_RS	INT
		,@CD_VD_RS		INT
		,@CD_IT_RS		INT
		,@CD_PROD_RS		INT
		,@CD_VEND		INT
		,@CD_VEND_RS		INT ;
DECLARE @PERC_COMIS		MONEY
DECLARE @DS_PERC_COMIS	VARCHAR(100)
DECLARE @VLR_COMISSAO_FABRIC MONEY
DECLARE @DS_VLR_COMIS	VARCHAR(100)

DECLARE @PRE_VENC_NOVO_MODELO  varchar(100) 
SELECT @PRE_VENC_NOVO_MODELO = dbo.UFD_BUSCA_PARAM_SISTEMA (@CD_EMP, 'PRE_VENCIDO_UTILIZA_NOVO_MODELO_COMISSAO', 0, 0)
-----------------------------------------------------------------------------------------------------------
CREATE TABLE #TMP_FILIAL(CD_EMP    INT,
						 CD_FILIAL INT);
CREATE TABLE #TMP_VEND(CD_EMP INT, 
					   CD_FUN INT);

CREATE NONCLUSTERED INDEX ix_tmp_vend
ON [dbo].[#TMP_VEND] ([CD_EMP],[CD_FUN]);

CREATE TABLE #VENDASPROCESSAR(CD_EMP                         INT
									, CD_FILIAL                      INT
									, CD_VD                          INT
									, CD_IT                          INT
									, CD_PROD                        INT
									, CD_VEND                        INT
									, PERC_COMIS_VENDA               MONEY
									, VLR_COMISSAO_FABRIC_VENDA      MONEY
									, PERC_COMIS_VENDA_NOVO          MONEY
									, VLR_COMISSAO_FABRIC_VENDA_NOVO MONEY
									, DS_COMIS_PERC                  VARCHAR(100)
									, DS_COMIS_VLR                   VARCHAR(100)
									, FLAG_PRE_VENCIDOS				 INT
									, CD_TBL_COMIS_PERC				 INT
									, TP_NIVEL_PERC					 INT
									, CD_TBL_COMIS_VLR				 INT
									, TP_NIVEL_VLR					 INT
									, DT_VD							 DATETIME
									);
-----------------------------------------------------------------------------------------------------------
	INSERT INTO #TMP_FILIAL
	SELECT
		 @CD_EMP,
		 @CD_FILIAL
	--	,ID
	--FROM
	--	 UFD_PRM_IN_STRING(@CD_FILIAL);


	SELECT *
	INTO #V_EST_PROD_TBL_COMIS_POSSUI
	FROM V_EST_PROD_TBL_COMIS_POSSUI_HISTORICO
-----------------------------------------------------------------------------------------------------------	
	IF LTRIM(RTRIM(@CD_FUN))<>''
	BEGIN
		INSERT INTO #TMP_VEND
		SELECT
			F.CD_EMP,
			F.CD_FUN 
		FROM
			FP_FUNC  F
			INNER JOIN FP_CARGO_EST_PROD_TBL_COMIS AS CC ON 
			F.CD_EMP	=CC.CD_EMP AND 
			F.CD_CARGO  =CC.CD_CARGO
		WHERE  
			F.CD_EMP =@CD_EMP
			AND F.CD_FUN IN(SELECT ID FROM UFD_PRM_IN_STRING(@CD_FUN));
	END
	ELSE
	BEGIN
		INSERT INTO #TMP_VEND
		SELECT  DISTINCT
			F.CD_EMP,
			F.CD_FUN 
		FROM  
			FP_FUNC  F
	END
-----------------------------------------------------------------------------------------------------------
	IF @CD_PROD > 0
		BEGIN
			INSERT INTO #VENDASPROCESSAR
			SELECT DISTINCT
				 A.CD_EMP
				,A.CD_FILIAL
				,A.CD_VD
				,A.CD_IT
				,A.CD_PROD
				,A.CD_VEND
				,ISNULL(A.PERC_COMIS,0)
				,ISNULL(A.VLR_COMISSAO_FABRIC,0)
				,0 AS PERC_NOVO
				,0 AS VLR_NOVO
				,'NAO DEFINIDO' AS DS_COMIS_PERC
				,'NAO DEFINIDO' AS DS_COMIS_VLR
				,FLAG_PRE_VENCIDOS
				,0
				,0
				,0
				,0
				,A.DT_VD
			FROM
				PDV_VD_IT AS A WITH (NOLOCK) 
				INNER JOIN #TMP_VEND AS V ON V.CD_EMP = A.CD_EMP
											 AND V.CD_FUN=A.CD_VEND
				INNER JOIN #TMP_FILIAL AS L ON A.CD_FILIAL=L.CD_FILIAL
											   AND A.CD_EMP=L.CD_EMP
				LEFT JOIN #V_EST_PROD_TBL_COMIS_POSSUI AS PC ON A.CD_EMP=PC.CD_EMP
																AND A.CD_FILIAL=PC.CD_FILIAL
																AND A.CD_PROD=PC.CD_PROD
																AND PC.TIPO_COMISSAO=0
			WHERE A.CD_EMP=@CD_EMP
				  AND A.DT_VD BETWEEN @DT_INI AND @DT_FIM 
				  AND A.CD_PROD =@CD_PROD
				  AND A.CD_FILIAL =@CD_FILIAL
		END
	ELSE	
		BEGIN
			INSERT INTO #VENDASPROCESSAR 
			SELECT DISTINCT
					A.CD_EMP
					, A.CD_FILIAL
					, A.CD_VD
					, A.CD_IT
					, A.CD_PROD	
					, A.CD_VEND
					, ISNULL(A.PERC_COMIS, 0)
					, ISNULL(A.VLR_COMISSAO_FABRIC, 0)
					, 0 PERC_NOVO
					, 0 VLR_NOVO
					, 'NAO DEFINIDO' DS_COMIS_PERC
					, 'NAO DEFINIDO' DS_COMIS_VLR 
					, FLAG_PRE_VENCIDOS
					, 0
					, 0
					, 0
					, 0
					,A.DT_VD
			FROM
				PDV_VD_IT AS A WITH (NOLOCK)
				INNER JOIN #TMP_FILIAL L ON A.CD_FILIAL = L.CD_FILIAL
											AND A.CD_EMP = L.CD_EMP
				INNER JOIN #TMP_VEND AS V ON V.CD_EMP = A.CD_EMP
											 AND V.CD_FUN=A.CD_VEND
				LEFT JOIN #V_EST_PROD_TBL_COMIS_POSSUI PC ON A.CD_EMP = PC.CD_EMP
																AND A.CD_FILIAL = PC.CD_FILIAL
																AND A.CD_PROD = PC.CD_PROD
																AND PC.TIPO_COMISSAO = 0
			WHERE  A.CD_EMP = @CD_EMP
					AND A.DT_VD BETWEEN @DT_INI AND @DT_FIM 
					AND A.CD_FILIAL =@CD_FILIAL
		END
-----------------------------------------------------------------------------------------------------------
	CREATE TABLE #INPUT	(CD_EMP    INT,
						  CD_FILIAL INT,
						  CD_PROD   INT,
						  CD_FUN    INT
						 ); 
	INSERT INTO #INPUT
	SELECT
		 CD_EMP
		,CD_FILIAL
		,CD_PROD
		,CD_VEND
	FROM
		 #VENDASPROCESSAR; 
----------------------------------------------------------------------------------------------------------------
--UFD_EST_PROD_COMIS_VALORES
----------------------------------------------------------------------------------------------------------------
		CREATE TABLE  #RS_TAB_COMIS (	  CD_FUN			INT
									, CD_TBL_COMIS       INT
									, FLAG_DESC_OUTR_TBL INT
									, PERC_COMIS         MONEY
									, PERC_COMIS_PRE_VENC MONEY
									, TP_NIVEL           INT
									, CD_PROD            INT
									, CD_FILIAL          INT
									, CD_EMP             INT
									, TP_VALOR			 TINYINT
									, DT_EVENT1			 DATETIME
									, DT_EVENT2			 DATETIME
									, DT_EVENT3			 DATETIME
									);

		CREATE TABLE #TBL_TP (TP_VALOR TINYINT);
		CREATE  TABLE #RS_TAB_ATIVA (	 CD_EMP       INT
										, CD_TBL_COMIS INT
										, TP_VALOR     TINYINT
										, CD_FUN INT
										);
		CREATE  TABLE #RS_DADOS_TBL_COMIS  (  
												CD_FUN INT ,
												CD_FILIAL INT,
												CD_PROD INT,
												CD_TBL_COMIS       INT
												, TP_VALOR           INT
												, FLAG_DESC_OUTR_TBL INT
												, PERC_COMIS         MONEY
												, PERC_COMIS_PRE_VENC MONEY
												, TP_NIVEL           INT
												, DT_EVENT1			 DATETIME
												, DT_EVENT2			 DATETIME
												, DT_EVENT3			 DATETIME
												);
		DECLARE @CD_GRP_ECON INT;
		SET @CD_GRP_ECON = (SELECT TOP 1 CD_GRP_ECON 
								FROM PRC_GRP_ECON_PRC_FILIAL FIL 
										INNER JOIN #INPUT INP ON 
											INP.CD_EMP = FIL.CD_EMP AND 
											INP.CD_FILIAL = FIL.CD_FILIAL);
 -------------------------------------------------------------------------------------------------------------------------------      
 --Declarando tabela de arvore mercadologica do produto      
 -------------------------------------------------------------------------------------------------------------------------------      
		CREATE TABLE #EST_PROD_ARV_MERC (
											 CD_EMP              INT
											,CD_PROD             INT
											,CD_ARV_MERC_CATEG   INT
											,CD_ARV_MERC_SEG     INT
											,CD_ARV_MERC_PAPEL   INT
											,CD_ARV_MERC_MIX     INT
											,CD_ARV_MERC_CONSUMO INT
											,CD_ARV_MERC_LINHA   INT
											,CD_ARV_MERC_MTZ_BCG INT
											,CD_MC               INT
											,CD_ARV_MERC_FAMILIA INT
											,CD_APRES            INT
											,CD_ARV_MERC_EQUI    INT
											,CD_GRP_EXPO         INT
											,CD_FABRIC           INT);
-------------------------------------------------------------------------------------------------------------------------------      
--BUSCANDO ARVORE MERC. DO PRODUTO      
-------------------------------------------------------------------------------------------------------------------------------       
	INSERT INTO #EST_PROD_ARV_MERC
	SELECT
		   ARV.CD_EMP 
		 , ARV.CD_PROD
		 , ARV.CD_ARV_MERC_CATEG
		 , ARV.CD_ARV_MERC_SEG
		 , ARV.CD_ARV_MERC_PAPEL
		 , ARV.CD_ARV_MERC_MIX
		 , ARV.CD_ARV_MERC_CONSUMO
		 , ARV.CD_ARV_MERC_LINHA
		 , ARV.CD_ARV_MERC_MTZ_BCG
		 , ARV.CD_MC
		 , ARV.CD_ARV_MERC_FAMILIA
		 , ARV.CD_APRES
		 , ARV.CD_ARV_MERC_EQUI
		 , ARV.CD_GRP_EXPO
		 , P.CD_FABRIC
	FROM
		EST_PROD_EST_ARV_MERCADOLOGICA ARV
		INNER JOIN EST_PROD P ON ARV.CD_EMP = P.CD_EMP
								 AND ARV.CD_PROD = P.CD_PROD
	     INNER JOIN #INPUT INP ON P.CD_EMP = INP.CD_EMP
						AND P.CD_PROD = INP.CD_PROD;
 -------------------------------------------------------------------------------      
 --CONSUTA TABELAS DE COMISSÃO PELO TIPO(%/R$) DE COMISSÃO  
 -------------------------------------------------------------------------------      
	INSERT INTO #TBL_TP
	SELECT
		 1
	UNION ALL
	SELECT
		 0;
	INSERT INTO #RS_TAB_ATIVA
	SELECT DISTINCT
		 COMIS.CD_EMP
		,COMIS.CD_TBL_COMIS
		,A.TP_VALOR
		,INP.CD_FUN
		,comis.DT_EVENT as DT_EVENT1
		,A.DT_EVENT AS DT_EVENT2
	FROM
	--	 FP_CARGO_EST_PROD_TBL_COMIS AS COMIS
	--INNER JOIN EST_PROD_TBL_COMIS AS A ON COMIS.CD_EMP=A.CD_EMP
	--									  AND COMIS.CD_TBL_COMIS=A.CD_TBL_COMIS
	 (SELECT *
						FROM (
								SELECT ROW_NUMBER() OVER(PARTITION BY CD_TBL_COMIS, CD_CARGO ORDER BY COALESCE(DT_EVENT,'2000-01-01') DESC) AS RN, *
								FROM FP_CARGO_EST_PROD_TBL_COMIS_audit_trigger AUD --select * from FP_CARGO_EST_PROD_TBL_COMIS
								--WHERE COALESCE(DT_EVENT,'2000-01-01') <= @DT_VD
								WHERE AUD.CD_GRP_ECON=@CD_GRP_ECON 
							 ) Q
						WHERE Q.RN = 1
					) COMIS
		--INNER JOIN EST_PROD_TBL_COMIS_REGRESSAO A ON  
		CROSS APPLY (SELECT *
						FROM (
								SELECT ROW_NUMBER() OVER(PARTITION BY CD_TBL_COMIS ORDER BY COALESCE(DT_EVENT,'2000-01-01') DESC) AS RN, *
								FROM EST_PROD_TBL_COMIS_audit_trigger AUD
								--WHERE COALESCE(DT_EVENT,'2000-01-01') <= @DT_VD
								WHERE COMIS.CD_EMP = AUD.CD_EMP 
								AND COMIS.CD_TBL_COMIS = AUD.CD_TBL_COMIS
								AND AUD.STS_TBL = 0 
							 ) Q
						WHERE Q.RN = 1
					) A
	INNER JOIN FP_FUNC AS FUN ON COMIS.CD_EMP=FUN.CD_EMP
								 AND COMIS.CD_CARGO=FUN.CD_CARGO
	INNER JOIN #INPUT AS INP ON A.CD_EMP=INP.CD_EMP
								AND FUN.CD_FUN=INP.CD_FUN
	--WHERE A.STS_TBL=0
		  --AND COMIS.CD_GRP_ECON=@CD_GRP_ECON;
-------------------------------------------------------------------------------------------------------------------------------      
--CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 1 - PRODUTOS      
-------------------------------------------------------------------------------------------------------------------------------      
	INSERT INTO #RS_DADOS_TBL_COMIS
	SELECT DISTINCT
			CD_FUN
		,CD_FILIAL
		,CD_PROD
		,CD_TBL_COMIS
		,A.TP_VALOR
		,FLAG_DESC_OUTR_TBL
		,PERC_COMIS
		,PERC_COMIS_PRE_VENC
		,TP_NIVEL
		,DT_EVENT1
		,DT_EVENT2
		,DT_EVENT3
	FROM
		#TBL_TP AS T
		CROSS APPLY
		(
			SELECT
				RS_TAB_ATIVA.CD_FUN
				,FIL.CD_FILIAL
				,ARV.CD_PROD
				,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
				,A.TP_VALOR AS TP_VALOR
				,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
				,B.PERC_COMIS AS PERC_COMIS
				,B.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
				,MAX(A.DT_CAD) AS DT_CAD
				,MAX(B.PERC_COMIS) AS MAX_PERC
				,MAX(B.PERC_COMIS_PRE_VENC) AS MAX_PERC_COMIS_PRE_VENC
				,1 AS TP_NIVEL
				,A.DT_EVENT AS DT_EVENT1
				,B.DT_EVENT AS DT_EVENT2
				,FIL.DT_EVENT AS DT_EVENT3
			FROM
				EST_PROD_TBL_COMIS_AUDIT_TRIGGER AS A
				INNER JOIN EST_PROD_TBL_COMIS_EST_PROD_AUDIT_TRIGGER AS B ON A.CD_EMP=B.CD_EMP
																AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
				INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL_AUDIT_TRIGGER AS FIL ON B.CD_EMP=FIL.CD_EMP
																	AND B.CD_TBL_COMIS=FIL.CD_TBL_COMIS
				INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON B.CD_EMP=RS_TAB_ATIVA.CD_EMP
															AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
				INNER JOIN #EST_PROD_ARV_MERC AS ARV ON B.CD_EMP=ARV.CD_EMP
														AND B.CD_PROD=ARV.CD_PROD
				INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=FIL.CD_FILIAL
				LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
													AND A.TP_VALOR=T.TP_VALOR
			WHERE 
				A.CD_EMP=1
				--AND T.CD_TBL_COMIS IS NULL
			GROUP BY
				RS_TAB_ATIVA.CD_FUN
				,FIL.CD_FILIAL
				,ARV.CD_PROD
				,A.TP_VALOR
				,A.FLAG_DESC_OUTR_TBL
				,B.PERC_COMIS
				,B.PERC_COMIS_PRE_VENC
				,A.DT_EVENT 
				,B.DT_EVENT 
				,FIL.DT_EVENT
		) AS A;
 -------------------------------------------------------------------------------------------------------------------------------      
 --CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 2 - FAMÍLIAS      
 -------------------------------------------------------------------------------------------------------------------------------      
		INSERT INTO #RS_DADOS_TBL_COMIS
		SELECT DISTINCT
				CD_FUN
			,CD_FILIAL
			,CD_PROD
			,CD_TBL_COMIS
			,A.TP_VALOR
			,FLAG_DESC_OUTR_TBL
			,PERC_COMIS
			,PERC_COMIS_PRE_VENC
			,TP_NIVEL
			,DT_EVENT1
			,DT_EVENT2
			,DT_EVENT3

		FROM
			#TBL_TP AS T
			CROSS APPLY
			(
				SELECT
					RS_TAB_ATIVA.CD_FUN
					,FIL.CD_FILIAL
					,ARV.CD_PROD
					,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
					,A.TP_VALOR AS TP_VALOR
					,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
					,B.PERC_COMIS AS PERC_COMIS
					,B.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
					,MAX(A.DT_CAD) AS DT_CAD
					,MAX(B.PERC_COMIS) AS MAX_PERC_COMIS
					,MAX(B.PERC_COMIS_PRE_VENC) AS MAX_PERC_COMIS_PRE_VENC
					,2 AS TP_NIVEL
					,A.DT_EVENT AS DT_EVENT1
					,B.DT_EVENT AS DT_EVENT2
					,FIL.DT_EVENT AS DT_EVENT3
				FROM
					EST_PROD_TBL_COMIS AS A
				INNER JOIN EST_PROD_TBL_COMIS_EST_ARV_MERC_FAMILIA AS B ON A.CD_EMP=B.CD_EMP
																			AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
				INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL AS FIL ON B.CD_EMP=FIL.CD_EMP
																	AND B.CD_TBL_COMIS=FIL.CD_TBL_COMIS
				INNER JOIN #EST_PROD_ARV_MERC AS ARV ON B.CD_EMP=ARV.CD_EMP
														AND B.CD_ARV_MERC_FAMILIA=ARV.CD_ARV_MERC_FAMILIA
				INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON A.CD_EMP=RS_TAB_ATIVA.CD_EMP
															AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
				INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=FIL.CD_FILIAL
				LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
													AND A.TP_VALOR=T.TP_VALOR
				WHERE A.CD_EMP=1
					AND A.STS_TBL=0
					--AND T.CD_TBL_COMIS IS NULL
				GROUP BY
					RS_TAB_ATIVA.CD_FUN
					,FIL.CD_FILIAL
					,ARV.CD_PROD
					,A.TP_VALOR
					,A.FLAG_DESC_OUTR_TBL
					,B.PERC_COMIS
					,B.PERC_COMIS_PRE_VENC
					,A.DT_EVENT 
					,B.DT_EVENT 
					,FIL.DT_EVENT
			) AS A;
-------------------------------------------------------------------------------------------------------------------------------          
--CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 3 - MARCAS      
-------------------------------------------------------------------------------------------------------------------------------      
		INSERT INTO #RS_DADOS_TBL_COMIS
		SELECT DISTINCT
			 CD_FUN
			,a.CD_FILIAL
			,CD_PROD
			,CD_TBL_COMIS
			,A.TP_VALOR
			,FLAG_DESC_OUTR_TBL
			,PERC_COMIS
			,PERC_COMIS_PRE_VENC
			,TP_NIVEL
			,DT_EVENT1
			,DT_EVENT2
			,DT_EVENT3
		FROM
			#TBL_TP AS T
			CROSS APPLY
			(
			  SELECT
				   RS_TAB_ATIVA.CD_FUN
				  ,ARV.CD_PROD
				  ,FIL.cd_filial
				  ,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
				  ,A.TP_VALOR AS TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS AS PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
				  ,MAX(A.DT_CAD) AS DT_CAD
				  ,MAX(B.PERC_COMIS) AS MAX_PERC_COMIS
				  ,MAX(B.PERC_COMIS_PRE_VENC) AS MAX_PERC_COMIS_PRE_VENC
				  ,3 AS TP_NIVEL
				  ,A.DT_EVENT AS DT_EVENT1
					,B.DT_EVENT AS DT_EVENT2
					,FIL.DT_EVENT AS DT_EVENT3
			  FROM
				   EST_PROD_TBL_COMIS AS A
				  INNER JOIN EST_PROD_TBL_COMIS_EST_MC AS B ON A.CD_EMP=B.CD_EMP
															   AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
				  INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL AS FIL ON B.CD_EMP=FIL.CD_EMP
																	 AND B.CD_TBL_COMIS=FIL.CD_TBL_COMIS
				  INNER JOIN #EST_PROD_ARV_MERC AS ARV ON B.CD_EMP=ARV.CD_EMP
														  AND B.CD_MC=ARV.CD_MC
				  INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON A.CD_EMP=RS_TAB_ATIVA.CD_EMP
															  AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
				  INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=FIL.CD_FILIAL
				  LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
														AND A.TP_VALOR=T.TP_VALOR
			  WHERE 
				A.CD_EMP=1
				AND A.STS_TBL=0
				--AND T.CD_TBL_COMIS IS NULL
		  GROUP BY
			   RS_TAB_ATIVA.CD_FUN
			  ,ARV.CD_PROD
			  ,FIL.cd_filial
			  ,A.TP_VALOR
			  ,A.FLAG_DESC_OUTR_TBL
			  ,B.PERC_COMIS
			  ,B.PERC_COMIS_PRE_VENC
			  ,A.DT_EVENT 
					,B.DT_EVENT 
					,FIL.DT_EVENT
		) AS A;
 -------------------------------------------------------------------------------------------------------------------------------      
 --CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 4 - FABRICANTES      
 -------------------------------------------------------------------------------------------------------------------------------      
		INSERT INTO #RS_DADOS_TBL_COMIS
		SELECT DISTINCT
			 CD_FUN
			,CD_FILIAL
			,CD_PROD
			,CD_TBL_COMIS
			,A.TP_VALOR
			,FLAG_DESC_OUTR_TBL
			,PERC_COMIS
			,PERC_COMIS_PRE_VENC
			,TP_NIVEL
			,DT_EVENT1
			,DT_EVENT2
			,DT_EVENT3
		FROM
			 #TBL_TP AS T
			CROSS APPLY
			(
			  SELECT
				   RS_TAB_ATIVA.CD_FUN
				  ,FIL.CD_FILIAL
				  ,ARV.CD_PROD
				  ,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
				  ,A.TP_VALOR AS TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS AS PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
				  ,MAX(A.DT_CAD) AS DT_CAD
				  ,MAX(B.PERC_COMIS) AS MAX_PERC_COMIS
				  ,MAX(B.PERC_COMIS_PRE_VENC) AS MAX_PERC_COMIS_PRE_VENC
				  ,4 AS TP_NIVEL
				   ,A.DT_EVENT AS DT_EVENT1
					,B.DT_EVENT AS DT_EVENT2
					,FIL.DT_EVENT AS DT_EVENT3
			  FROM
				  EST_PROD_TBL_COMIS AS A
				  INNER JOIN EST_PROD_TBL_COMIS_EST_PROD_FABRIC AS B ON A.CD_EMP=B.CD_EMP
																		AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
				  INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL AS FIL ON B.CD_EMP=FIL.CD_EMP
																	 AND B.CD_TBL_COMIS=FIL.CD_TBL_COMIS
				  INNER JOIN #EST_PROD_ARV_MERC AS ARV ON B.CD_EMP=ARV.CD_EMP
														  AND B.CD_FABRIC=ARV.CD_FABRIC
				  INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON B.CD_EMP=RS_TAB_ATIVA.CD_EMP
															  AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
				  INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=FIL.CD_FILIAL
				  LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
														AND A.TP_VALOR=T.TP_VALOR
			  WHERE 
				A.CD_EMP=1
				AND A.STS_TBL=0
				--AND T.CD_TBL_COMIS IS NULL
			  GROUP BY
				   RS_TAB_ATIVA.CD_FUN
				  ,FIL.CD_FILIAL
				  ,ARV.CD_PROD
				  ,A.TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC
				  ,A.DT_EVENT 
					,B.DT_EVENT 
					,FIL.DT_EVENT
			) AS A;
-------------------------------------------------------------------------------------------------------------------------------      
 --CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 5 - CATEGORIAS      
 -------------------------------------------------------------------------------------------------------------------------------      
		INSERT INTO #RS_DADOS_TBL_COMIS
		SELECT DISTINCT
			 CD_FUN
			,CD_FILIAL
			,CD_PROD
			,CD_TBL_COMIS
			,A.TP_VALOR
			,FLAG_DESC_OUTR_TBL
			,PERC_COMIS
			,PERC_COMIS_PRE_VENC
			,TP_NIVEL
			,DT_EVENT1
			,DT_EVENT2
			,DT_EVENT3
		FROM
			#TBL_TP AS T
			CROSS APPLY
			(
			  SELECT
				   RS_TAB_ATIVA.CD_FUN
				  ,FIL.CD_FILIAL
				  ,ARV.CD_PROD
				  ,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
				  ,A.TP_VALOR AS TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS AS PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
				  ,MAX(A.DT_CAD) AS DT_CAD
				  ,MAX(B.PERC_COMIS) AS MAX_PERC_COMIS
				  ,MAX(B.PERC_COMIS_PRE_VENC) AS MAX_PERC_COMIS_PRE_VENC
				  ,5 AS TP_NIVEL
				   ,A.DT_EVENT AS DT_EVENT1
					,B.DT_EVENT AS DT_EVENT2
					,FIL.DT_EVENT AS DT_EVENT3
			  FROM
				   EST_PROD_TBL_COMIS AS A
				  INNER JOIN EST_PROD_TBL_COMIS_EST_ARV_MERC_CATEGORIA AS B ON A.CD_EMP=B.CD_EMP
																			   AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
				  INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL AS FIL ON B.CD_EMP=FIL.CD_EMP
																	 AND B.CD_TBL_COMIS=FIL.CD_TBL_COMIS
				  INNER JOIN #EST_PROD_ARV_MERC AS ARV ON B.CD_EMP=ARV.CD_EMP
														  AND B.CD_ARV_MERC_CATEG=ARV.CD_ARV_MERC_CATEG
				  INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON A.CD_EMP=RS_TAB_ATIVA.CD_EMP
															  AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
				  INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=FIL.CD_FILIAL
				  LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
														AND A.TP_VALOR=T.TP_VALOR
			  WHERE 
					A.CD_EMP=1
					AND A.STS_TBL=0
					-- AND T.CD_TBL_COMIS IS NULL
			  GROUP BY
				   RS_TAB_ATIVA.CD_FUN
				  ,FIL.CD_FILIAL
				  ,ARV.CD_PROD
				  ,A.TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC
				  ,A.DT_EVENT 
					,B.DT_EVENT 
					,FIL.DT_EVENT
			) AS A;
 ------------------------------------------------------------------------------------------------------------------------------      
 --CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 6 - LINHAS      
 -------------------------------------------------------------------------------------------------------------------------------      
	 INSERT INTO #RS_DADOS_TBL_COMIS
		SELECT DISTINCT
			 CD_FUN
			,CD_FILIAL
			,CD_PROD
			,CD_TBL_COMIS
			,A.TP_VALOR
			,FLAG_DESC_OUTR_TBL
			,PERC_COMIS
			,PERC_COMIS_PRE_VENC
			,TP_NIVEL
			,DT_EVENT1
			,DT_EVENT2
			,DT_EVENT3
		FROM
			 #TBL_TP AS T
			CROSS APPLY
			(
			  SELECT
				   RS_TAB_ATIVA.CD_FUN
				  ,FIL.CD_FILIAL
				  ,ARV.CD_PROD
				  ,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
				  ,A.TP_VALOR AS TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS AS PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
				  ,MAX(A.DT_CAD) AS DT_CAD
				  ,MAX(B.PERC_COMIS) AS MAX_PERC_COMIS
				  ,MAX(B.PERC_COMIS_PRE_VENC) AS MAX_PERC_COMIS_PRE_VENC
				  ,6 AS TP_NIVEL
				  ,A.DT_EVENT AS DT_EVENT1
					,B.DT_EVENT AS DT_EVENT2
					,FIL.DT_EVENT AS DT_EVENT3
			  FROM
				  EST_PROD_TBL_COMIS AS A
				  INNER JOIN EST_PROD_TBL_COMIS_EST_ARV_MERC_LINHA AS B ON A.CD_EMP=B.CD_EMP
																		   AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
				  INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL AS FIL ON B.CD_EMP=FIL.CD_EMP
																	 AND B.CD_TBL_COMIS=FIL.CD_TBL_COMIS
				  INNER JOIN #EST_PROD_ARV_MERC AS ARV ON B.CD_EMP=ARV.CD_EMP
														  AND B.CD_ARV_MERC_LINHA=ARV.CD_ARV_MERC_LINHA
				  INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON A.CD_EMP=RS_TAB_ATIVA.CD_EMP
															  AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
				  INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=FIL.CD_FILIAL
				  LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
														AND A.TP_VALOR=T.TP_VALOR
			  WHERE 
					A.CD_EMP=1
					AND A.STS_TBL=0
					--AND T.CD_TBL_COMIS IS NULL
			  GROUP BY
				   RS_TAB_ATIVA.CD_FUN
				  ,ARV.CD_PROD
				  ,FIL.CD_FILIAL
				  ,A.TP_VALOR
				  ,A.FLAG_DESC_OUTR_TBL
				  ,B.PERC_COMIS
				  ,B.PERC_COMIS_PRE_VENC
				   ,A.DT_EVENT 
					,B.DT_EVENT 
					,FIL.DT_EVENT
			) AS A;
 -------------------------------------------------------------------------------------------------------------------------------      
 --CONSULTANDO AS TBLS DE COMISSÃO NO NÍVEL 7 - FILIAL      
 -------------------------------------------------------------------------------------------------------------------------------      
	INSERT INTO #RS_DADOS_TBL_COMIS
	SELECT DISTINCT
		 CD_FUN
		,CD_FILIAL
		,CD_PROD
		,CD_TBL_COMIS
		,A.TP_VALOR
		,FLAG_DESC_OUTR_TBL
		,PERC_COMIS
		,0 AS PERC_COMIS_PRE_VENC
		,TP_NIVEL
		,DT_EVENT1
			,DT_EVENT2
			,DT_EVENT3
	FROM
		 #TBL_TP AS T
		CROSS APPLY
		(
		  SELECT
			   RS_TAB_ATIVA.CD_FUN
			  ,b.CD_FILIAL
			  ,ARV.CD_PROD
			  ,MAX(A.CD_TBL_COMIS) AS CD_TBL_COMIS
			  ,A.TP_VALOR AS TP_VALOR
			  ,A.FLAG_DESC_OUTR_TBL AS FLAG_DESC_OUTR_TBL
			  ,B.PERC_COMIS AS PERC_COMIS
			  ,MAX(A.DT_CAD) AS DT_CAD
			  ,MAX(B.PERC_COMIS) AS MAX_PERC_COMIS
			  ,7 AS TP_NIVEL
			   ,A.DT_EVENT AS DT_EVENT1
					,B.DT_EVENT AS DT_EVENT2
					,null AS DT_EVENT3
		  FROM
			  EST_PROD_TBL_COMIS AS A
			  INNER JOIN EST_PROD_TBL_COMIS_PRC_FILIAL AS B ON A.CD_EMP=B.CD_EMP
															   AND A.CD_TBL_COMIS=B.CD_TBL_COMIS
			  INNER JOIN #RS_TAB_ATIVA AS RS_TAB_ATIVA ON A.CD_EMP=RS_TAB_ATIVA.CD_EMP
														  AND B.CD_TBL_COMIS=RS_TAB_ATIVA.CD_TBL_COMIS
			  INNER JOIN #EST_PROD_ARV_MERC AS ARV ON ARV.CD_EMP=B.CD_EMP
			  INNER JOIN #TMP_FILIAL AS FIL2 ON FIL2.CD_FILIAL=B.CD_FILIAL
			  LEFT JOIN #RS_DADOS_TBL_COMIS AS T ON T.CD_TBL_COMIS=A.CD_TBL_COMIS
													AND A.TP_VALOR=T.TP_VALOR
		  WHERE 
				A.CD_EMP=1
				AND A.STS_TBL=0
				--AND T.CD_TBL_COMIS IS NULL
		  GROUP BY
			   RS_TAB_ATIVA.CD_FUN
			  ,b.CD_FILIAL
			  ,ARV.CD_PROD
			  ,A.TP_VALOR
			  ,A.FLAG_DESC_OUTR_TBL
			  ,B.PERC_COMIS
			  ,A.DT_EVENT 
					,B.DT_EVENT
		) AS A;
-------------------------------------------------------------------------------------------------------------------------------
--RESULTADO
-------------------------------------------------------------------------------------------------------------------------------
	SELECT
		 CD_FUN		
		,MIN(TP_NIVEL)TP_NIVEL
		,CD_PROD
		,CD_FILIAL
		,1 AS CD_EMP
		,TP_VALOR
		into #ComisLine
	FROM
		 #RS_DADOS_TBL_COMIS		 
	GROUP BY
		 CD_FUN		 
		,CD_PROD
		,CD_FILIAL 
		,TP_VALOR;

 	INSERT INTO #RS_TAB_COMIS (CD_FUN,CD_TBL_COMIS, FLAG_DESC_OUTR_TBL, PERC_COMIS, PERC_COMIS_PRE_VENC,
									TP_NIVEL, CD_PROD, CD_FILIAL, CD_EMP, TP_VALOR, DT_EVENT1, DT_EVENT2, DT_EVENT3)
	SELECT
		 A.CD_FUN
		,A.CD_TBL_COMIS
		,A.FLAG_DESC_OUTR_TBL
		,A.PERC_COMIS AS PERC_COMIS
		,A.PERC_COMIS_PRE_VENC AS PERC_COMIS_PRE_VENC
		,A.TP_NIVEL
		,A.CD_PROD
		,A.CD_FILIAL
		,1 AS CD_EMP
		,A.TP_VALOR
		,A.DT_EVENT1
		,A.DT_EVENT2
		,A.DT_EVENT3
	FROM
		 #RS_DADOS_TBL_COMIS		  A
		 JOIN #ComisLine  C ON 
			A.TP_NIVEL	=C.TP_NIVEL	 AND
			A.CD_FUN	=C.CD_FUN	AND 
			A.CD_PROD	=C.CD_PROD	 AND
			A.CD_FILIAL =C.CD_FILIAL AND
			A.TP_VALOR	=C.TP_VALOR	  
-------------------------------------------------------------------------------------------------------------------------------
--UFD_EST_PROD_COMIS 
-------------------------------------------------------------------------------------------------------------------------------
CREATE TABLE  #RS_RET   (	 CD_PROD            INT
							,CD_FUN			 INT
							,CD_FILIAL		 INT
							, CD_TBL_COMIS_PERC  INT
							, TP_NIVEL_PERC      INT
							, PERC_COMIS         MONEY
							, PERC_COMIS_PRE_VENC MONEY
							, DS_COMIS_PERC      VARCHAR(100)
							, FLAG_DESC_OUTR_TBL INT
							, CD_TBL_COMIS_VLR   INT
							, TP_NIVEL_VLR       INT
							, VLR_COMIS          MONEY
							, VLR_COMIS_PRE_VENC MONEY
							, DS_COMIS_VLR       VARCHAR(100)
							, DT_EVENT1			 DATETIME
							, DT_EVENT2			 DATETIME
							, DT_EVENT3			 DATETIME
							)
-------------------------------------------------------------------------------------------------------------------------------
	CREATE TABLE  #RS_TAB_COMIS_2   (CD_PROD            INT
								, CD_FUN         INT
								,CD_FILIAL		 INT
								, CD_TBL_COMIS_PERC  INT
								, TP_NIVEL_PERC      INT
								, PERC_COMIS         MONEY
								, PERC_COMIS_PRE_VENC MONEY
								, DS_COMIS_PERC      NVARCHAR(50)
								, FLAG_DESC_OUTR_TBL INT
								, CD_TBL_COMIS_VLR   INT
								, TP_NIVEL_VLR       INT
								, VLR_COMIS          MONEY
								, VLR_COMIS_PRE_VENC MONEY
								, DS_COMIS_VLR       NVARCHAR(50)
								, DT_EVENT1			 DATETIME
								, DT_EVENT2			 DATETIME
								, DT_EVENT3			 DATETIME
								);

	CREATE TABLE  #TBL_NIVEL  (TP_NIVEL INT, DS_NIVEL VARCHAR(20));
-------------------------------------------------------------------------------------------------------------------------------
	INSERT INTO #TBL_NIVEL
		  SELECT 0, 'SEM COMISSAO'
	UNION SELECT 1, 'PRODUTO'
	UNION SELECT 2, 'FAMILIA'
	UNION SELECT 3, 'MARCA'
	UNION SELECT 4, 'FABRICANTE'
	UNION SELECT 5, 'CATEGORIA'
	UNION SELECT 6, 'LINHA'
	UNION SELECT 7, 'FILIAL';
-------------------------------------------------------------------------------------------------------------------------------
	INSERT INTO  #RS_TAB_COMIS_2
	SELECT
		B.CD_PROD
		,CD_FUN
		,CD_FILIAL	 
		, CASE WHEN TP_VALOR = 0 THEN 
				B.CD_TBL_COMIS  ELSE 0 END AS CD_TBL_COMIS_PERC
		, CASE WHEN TP_VALOR = 0 THEN  
				B.TP_NIVEL	ELSE NULL END AS TP_NIVEL_PERC
		, CASE WHEN TP_VALOR = 0 THEN  
					B.PERC_COMIS	ELSE 0  END AS PERC_COMIS  
		, CASE WHEN TP_VALOR = 0 THEN  
					B.PERC_COMIS_PRE_VENC	ELSE 0  END AS PERC_COMIS_PRE_VENC  
		, '' AS DS_COMIS_PERC
		, B.FLAG_DESC_OUTR_TBL
		--COMISSAO POR VALOR
		, CASE WHEN TP_VALOR = 1 THEN 
				B.CD_TBL_COMIS  ELSE 0 END AS CD_TBL_COMIS
		, CASE WHEN TP_VALOR = 1 THEN  
				B.TP_NIVEL	ELSE NULL END AS TP_NIVEL
		, CASE WHEN TP_VALOR = 1 THEN  
					B.PERC_COMIS	ELSE 0  END AS	VLR_COMIS 
		, CASE WHEN TP_VALOR = 1 THEN  
					B.PERC_COMIS_PRE_VENC	ELSE 0  END AS	VLR_COMIS_PRE_VENC 
		, '' AS DS_COMIS_VLR
		, DT_EVENT1
		, DT_EVENT2
		, DT_EVENT3
	FROM
		#RS_TAB_COMIS B;
-------------------------------------------------------------------------------------------------------------------------------

		DECLARE @ComissaoValor_AnulaPercentual TINYINT = 0;
		IF @PRE_VENC_NOVO_MODELO <> 1
		BEGIN
			INSERT INTO #RS_RET
			SELECT
				 (CD_PROD) AS CD_PROD
				,CD_FUN
				,CD_FILIAL
				,MAX(CASE
					   WHEN ISNULL(FLAG_DESC_OUTR_TBL,0)=0
					   THEN CD_TBL_COMIS_PERC
					   ELSE 0
					 END) AS CD_TBL_COMIS_PERC
				,MIN(CASE
					   WHEN ISNULL(FLAG_DESC_OUTR_TBL,0)=0
					   THEN TP_NIVEL_PERC
					   ELSE 0
					 END) AS TP_NIVEL_PERC
				,MAX(CASE
					   WHEN(ISNULL(FLAG_DESC_OUTR_TBL,0))=0
					   THEN(PERC_COMIS)
					   ELSE 0
					 END) AS PERC_COMIS
				, 0
				,(CASE
						WHEN MAX(ISNULL(FLAG_DESC_OUTR_TBL,0))=1 THEN 
							'COMISSAO ANULADA(%) PELO DESC. VALOR - TAB: '+CAST(MAX(CD_TBL_COMIS_VLR) AS VARCHAR)+' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N  WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_VLR))
						WHEN MAX(ISNULL(PERC_COMIS,0))=0 AND MAX(CD_TBL_COMIS_PERC)>0 THEN 
							'COMISSAO ANULADA(%) PELO NIVEL - TAB: '+CAST(MAX(CD_TBL_COMIS_PERC) AS VARCHAR)+' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_PERC) )
						WHEN MAX(ISNULL(PERC_COMIS,0))=0 AND MAX(CD_TBL_COMIS_PERC)=0 THEN 
							'SEM COMISSAO(%)'
						WHEN  MAX(ISNULL(PERC_COMIS,0))>0 AND MAX(CD_TBL_COMIS_PERC)>0 THEN 
							'MELHOR COMISSAO(%) - TAB: '+CAST(MAX(CD_TBL_COMIS_PERC) AS VARCHAR)+' NIVEL: '+ ( SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_PERC))
					ELSE 'NAO DEFINIDO'
					END) AS DS_COMIS_PERC
				,MAX(FLAG_DESC_OUTR_TBL) AS FLAG_DESC_OUTR_TBL
				,MAX(CD_TBL_COMIS_VLR) AS CD_TBL_COMIS_VLR
				,MIN(TP_NIVEL_VLR) AS TP_NIVEL_VLR
				,MAX(VLR_COMIS) AS VLR_COMIS
				,0
				,(CASE WHEN MAX(ISNULL(VLR_COMIS,0))=0 AND MAX(CD_TBL_COMIS_VLR)>0 THEN 
					'COMISSAO ANULADA(R$) PELO NVEL - TAB: '+CAST(MAX(CD_TBL_COMIS_VLR) AS VARCHAR)+' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_VLR))
					WHEN MAX(ISNULL(VLR_COMIS,0))=0 AND MAX(CD_TBL_COMIS_VLR)=0 THEN 
						'SEM COMISSAO(R$)' 
					WHEN  MAX(ISNULL(VLR_COMIS,0))>0 AND MAX(CD_TBL_COMIS_VLR)>0 THEN 
						'MELHOR COMISSAO(R$) - TAB: '+ CAST(MAX(CD_TBL_COMIS_VLR) AS VARCHAR) + ' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_VLR))
					ELSE 'NAO DEFINIDO'
				  END) AS DS_COMIS_VLR
				  , DT_EVENT1
				, DT_EVENT2
				, DT_EVENT3
			FROM
				 #RS_TAB_COMIS_2 AS T
			GROUP BY
				 CD_FUN
				,CD_PROD
				,CD_FILIAL
				, DT_EVENT1
				, DT_EVENT2
				, DT_EVENT3;
	  -------------------------------------------------------------------------------------------------------------------------------
			SET @ComissaoValor_AnulaPercentual = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = 1 AND CD_CHAVE = 'COMISSAO_VALOR_ANULA_COMIS_PERC'), 0);
			IF @ComissaoValor_AnulaPercentual = 1
			BEGIN
				UPDATE PROCES
				  SET
					  PERC_COMIS_VENDA_NOVO = CASE
												  WHEN RET.VLR_COMIS > 0 THEN 0
												  ELSE RET.PERC_COMIS
											  END
					, VLR_COMISSAO_FABRIC_VENDA_NOVO = RET.VLR_COMIS
					, DS_COMIS_PERC = CASE
										  WHEN RET.VLR_COMIS > 0 THEN 'COMISSAO % ANULADA PELO NVEL (R$) - VALOR '
										  ELSE RET.DS_COMIS_PERC
									  END
					, DS_COMIS_VLR = RET.DS_COMIS_VLR
					, TP_NIVEL_PERC = RET.TP_NIVEL_PERC
					, TP_NIVEL_VLR = RET.TP_NIVEL_VLR
					, CD_TBL_COMIS_PERC = RET.CD_TBL_COMIS_PERC
					, CD_TBL_COMIS_VLR = RET.CD_TBL_COMIS_VLR
				FROM #VENDASPROCESSAR PROCES
					 INNER JOIN #RS_RET RET ON PROCES.CD_FILIAL = RET.CD_FILIAL
											   AND PROCES.CD_VEND = RET.CD_FUN
											   AND PROCES.CD_PROD = RET.CD_PROD
											   AND (	COALESCE(RET.DT_EVENT1,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT2,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT3,'2023-04-06') <= PROCES.dt_vd
													)
											   ;
			END;
			ELSE
			BEGIN
				UPDATE PROCES
				  SET
					  PERC_COMIS_VENDA_NOVO = RET.PERC_COMIS
					, VLR_COMISSAO_FABRIC_VENDA_NOVO = RET.VLR_COMIS
					, DS_COMIS_PERC = RET.DS_COMIS_PERC
					, DS_COMIS_VLR = RET.DS_COMIS_VLR
					, TP_NIVEL_PERC = RET.TP_NIVEL_PERC
					, TP_NIVEL_VLR = RET.TP_NIVEL_VLR
					, CD_TBL_COMIS_PERC = RET.CD_TBL_COMIS_PERC
					, CD_TBL_COMIS_VLR = RET.CD_TBL_COMIS_VLR
				FROM #VENDASPROCESSAR PROCES
					 INNER JOIN #RS_RET RET ON PROCES.CD_FILIAL = RET.CD_FILIAL
											   AND PROCES.CD_VEND = RET.CD_FUN
											   AND PROCES.CD_PROD = RET.CD_PROD
											   AND (	COALESCE(RET.DT_EVENT1,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT2,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT3,'2023-04-06') <= PROCES.dt_vd
													)
											   ;
			END;
		END
		ELSE
		BEGIN
			INSERT INTO #RS_RET
			SELECT
				 (CD_PROD) AS CD_PROD
				,CD_FUN
				,CD_FILIAL
				,MAX(CASE
					   WHEN ISNULL(FLAG_DESC_OUTR_TBL,0)=0
					   THEN CD_TBL_COMIS_PERC
					   ELSE 0
					 END) AS CD_TBL_COMIS_PERC
				,MIN(CASE
					   WHEN ISNULL(FLAG_DESC_OUTR_TBL,0)=0
					   THEN TP_NIVEL_PERC
					   ELSE 0
					 END) AS TP_NIVEL_PERC
				,MAX(CASE
					   WHEN(ISNULL(FLAG_DESC_OUTR_TBL,0))=0
					   THEN(PERC_COMIS)
					   ELSE 0
					 END) AS PERC_COMIS
				,MAX(CASE
					   WHEN(ISNULL(FLAG_DESC_OUTR_TBL,0))=0
					   THEN(PERC_COMIS_PRE_VENC)
					   ELSE 0
					 END) AS PERC_COMIS_PRE_VENC
				,(CASE
						WHEN MAX(ISNULL(FLAG_DESC_OUTR_TBL,0))=1 THEN 
							'COMISSAO ANULADA(%) PELO DESC. VALOR - TAB: '+CAST(MAX(CD_TBL_COMIS_VLR) AS VARCHAR)+' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N  WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_VLR))
						WHEN MAX(ISNULL(PERC_COMIS,0))=0 AND MAX(ISNULL(PERC_COMIS_PRE_VENC,0))=0 AND MAX(CD_TBL_COMIS_PERC)>0 THEN 
							'COMISSAO ANULADA(%) PELO NIVEL - TAB: '+CAST(MAX(CD_TBL_COMIS_PERC) AS VARCHAR)+' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_PERC) )
						WHEN MAX(ISNULL(PERC_COMIS,0))=0 AND MAX(ISNULL(PERC_COMIS_PRE_VENC,0))=0 AND MAX(CD_TBL_COMIS_PERC)=0 THEN 
							'SEM COMISSAO(%)'
						WHEN  (MAX(ISNULL(PERC_COMIS,0))>0 OR MAX(ISNULL(PERC_COMIS_PRE_VENC,0))>0) AND MAX(CD_TBL_COMIS_PERC)>0 THEN 
							'MELHOR COMISSAO(%) - TAB: '+CAST(MAX(CD_TBL_COMIS_PERC) AS VARCHAR)+' NIVEL: '+ ( SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_PERC))
					ELSE 'NAO DEFINIDO'
					END) AS DS_COMIS_PERC
				,MAX(FLAG_DESC_OUTR_TBL) AS FLAG_DESC_OUTR_TBL
				,MAX(CD_TBL_COMIS_VLR) AS CD_TBL_COMIS_VLR
				,MIN(TP_NIVEL_VLR) AS TP_NIVEL_VLR
				,MAX(VLR_COMIS) AS VLR_COMIS
				,MAX(VLR_COMIS_PRE_VENC) AS VLR_COMIS_PRE_VENC
				,(CASE WHEN MAX(ISNULL(VLR_COMIS,0))=0 AND MAX(ISNULL(VLR_COMIS_PRE_VENC,0))=0 AND MAX(CD_TBL_COMIS_VLR)>0 THEN 
					'COMISSAO ANULADA(R$) PELO NVEL - TAB: '+CAST(MAX(CD_TBL_COMIS_VLR) AS VARCHAR)+' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_VLR))
					WHEN MAX(ISNULL(VLR_COMIS,0))=0 AND MAX(ISNULL(VLR_COMIS_PRE_VENC,0))=0 AND MAX(CD_TBL_COMIS_VLR)=0 THEN 
						'SEM COMISSAO(R$)' 
					WHEN  (MAX(ISNULL(VLR_COMIS,0))>0 OR MAX(ISNULL(VLR_COMIS_PRE_VENC,0))>0) AND MAX(CD_TBL_COMIS_VLR)>0 THEN 
						'MELHOR COMISSAO(R$) - TAB: '+ CAST(MAX(CD_TBL_COMIS_VLR) AS VARCHAR) + ' NIVEL: '+ (SELECT DS_NIVEL FROM #TBL_NIVEL AS N WHERE N.TP_NIVEL=MIN(T.TP_NIVEL_VLR))
					ELSE 'NAO DEFINIDO'
				  END) AS DS_COMIS_VLR
				  , DT_EVENT1
				, DT_EVENT2
				, DT_EVENT3
			FROM
				 #RS_TAB_COMIS_2 AS T
			GROUP BY
				 CD_FUN
				,CD_PROD
				,CD_FILIAL
				, DT_EVENT1
				, DT_EVENT2
				, DT_EVENT3;
	  -------------------------------------------------------------------------------------------------------------------------------
		SET @ComissaoValor_AnulaPercentual = ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_EMP = 1 AND CD_CHAVE = 'COMISSAO_VALOR_ANULA_COMIS_PERC'), 0);
		IF @ComissaoValor_AnulaPercentual = 1
			BEGIN
				UPDATE PROCES
				  SET
					  PERC_COMIS_VENDA_NOVO = CASE
												  WHEN RET.VLR_COMIS > 0 OR RET.VLR_COMIS_PRE_VENC > 0 THEN 0
												  WHEN PROCES.FLAG_PRE_VENCIDOS = 1 THEN RET.PERC_COMIS_PRE_VENC 
												  ELSE RET.PERC_COMIS
											  END
					, VLR_COMISSAO_FABRIC_VENDA_NOVO = CASE WHEN PROCES.FLAG_PRE_VENCIDOS = 1 THEN RET.VLR_COMIS_PRE_VENC ELSE RET.VLR_COMIS END
					, DS_COMIS_PERC = CASE
										  WHEN RET.VLR_COMIS > 0 OR RET.VLR_COMIS_PRE_VENC > 0 THEN 'COMISSAO % ANULADA PELO NÍVEL (R$) - VALOR '
										  WHEN PROCES.FLAG_PRE_VENCIDOS = 1 AND SUBSTRING(RET.DS_COMIS_PERC,1,18) = 'MELHOR COMISSAO(%)' THEN REPLACE(RET.DS_COMIS_PERC,'MELHOR COMISSAO(%)', 'MELHOR COMISSAO P.V.(%)')
										  ELSE RET.DS_COMIS_PERC
									  END
					, DS_COMIS_VLR = CASE WHEN PROCES.FLAG_PRE_VENCIDOS = 1 AND SUBSTRING(RET.DS_COMIS_VLR,1,19) = 'MELHOR COMISSAO(R$)' THEN REPLACE(RET.DS_COMIS_VLR,'MELHOR COMISSAO(R$)', 'MELHOR COMISSAO P.V.(R$)')
										  ELSE RET.DS_COMIS_VLR
									  END
					, TP_NIVEL_PERC = RET.TP_NIVEL_PERC
					, TP_NIVEL_VLR = RET.TP_NIVEL_VLR
					, CD_TBL_COMIS_PERC = RET.CD_TBL_COMIS_PERC
					, CD_TBL_COMIS_VLR = RET.CD_TBL_COMIS_VLR
				FROM #VENDASPROCESSAR PROCES
					 INNER JOIN #RS_RET RET ON PROCES.CD_FILIAL = RET.CD_FILIAL
											   AND PROCES.CD_VEND = RET.CD_FUN
											   AND PROCES.CD_PROD = RET.CD_PROD
											   AND (	COALESCE(RET.DT_EVENT1,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT2,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT3,'2023-04-06') <= PROCES.dt_vd
													);
			END;
			ELSE
			BEGIN
				UPDATE PROCES
				  SET
					  PERC_COMIS_VENDA_NOVO = CASE WHEN PROCES.FLAG_PRE_VENCIDOS = 1 THEN RET.PERC_COMIS_PRE_VENC ELSE RET.PERC_COMIS END
					, VLR_COMISSAO_FABRIC_VENDA_NOVO = CASE WHEN PROCES.FLAG_PRE_VENCIDOS = 1 THEN RET.VLR_COMIS_PRE_VENC ELSE RET.VLR_COMIS END
					, DS_COMIS_PERC = CASE WHEN PROCES.FLAG_PRE_VENCIDOS = 1 AND SUBSTRING(RET.DS_COMIS_PERC,1,18) = 'MELHOR COMISSAO(%)' THEN REPLACE(RET.DS_COMIS_PERC,'MELHOR COMISSAO(%)', 'MELHOR COMISSAO P.V.(%)')
										   ELSE RET.DS_COMIS_PERC
									  END 
					, DS_COMIS_VLR = CASE WHEN PROCES.FLAG_PRE_VENCIDOS = 1 AND SUBSTRING(RET.DS_COMIS_VLR,1,19) = 'MELHOR COMISSAO(R$)' THEN REPLACE(RET.DS_COMIS_VLR,'MELHOR COMISSAO(R$)', 'MELHOR COMISSAO P.V.(R$)')
										  ELSE RET.DS_COMIS_VLR
									  END
					, TP_NIVEL_PERC = RET.TP_NIVEL_PERC
					, TP_NIVEL_VLR = RET.TP_NIVEL_VLR
					, CD_TBL_COMIS_PERC = RET.CD_TBL_COMIS_PERC
					, CD_TBL_COMIS_VLR = RET.CD_TBL_COMIS_VLR
				FROM #VENDASPROCESSAR PROCES
					 INNER JOIN #RS_RET RET ON PROCES.CD_FILIAL = RET.CD_FILIAL
											   AND PROCES.CD_VEND = RET.CD_FUN
											   AND PROCES.CD_PROD = RET.CD_PROD
											   AND (	COALESCE(RET.DT_EVENT1,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT2,'2023-04-06') <= PROCES.dt_vd
														and COALESCE(RET.DT_EVENT3,'2023-04-06') <= PROCES.dt_vd
													);
			END;		
		END

	SELECT CD_FUN, CD_PROD, CD_FILIAL, TP_NIVEL, PERC_COMIS , MAX(CD_TBL_COMIS) AS CD_TBL_COMIS, TP_VALOR, 0 AS TIPO
	INTO #COD_TAB_COMISSAO
	FROM #RS_TAB_COMIS
	WHERE PERC_COMIS <> 0
	GROUP BY CD_PROD, PERC_COMIS,  TP_VALOR, TP_NIVEL, CD_FILIAL, CD_FUN
	UNION
	SELECT CD_FUN, CD_PROD, CD_FILIAL, TP_NIVEL, PERC_COMIS_PRE_VENC, MAX(CD_TBL_COMIS) AS CD_TBL_COMIS, TP_VALOR, 1 AS TIPO
	FROM #RS_TAB_COMIS
	WHERE PERC_COMIS_PRE_VENC <> 0
	GROUP BY CD_PROD, PERC_COMIS_PRE_VENC,  TP_VALOR, TP_NIVEL, CD_FILIAL, CD_FUN

	UPDATE A
	SET A.DS_COMIS_PERC = REPLACE(A.DS_COMIS_PERC,A.CD_TBL_COMIS_PERC,B.CD_TBL_COMIS)
	-- SELECT REPLACE(A.DS_COMIS_PERC,A.CD_TBL_COMIS_PERC,B.CD_TBL_COMIS_PERC), *
	FROM #VENDASPROCESSAR A
	JOIN #COD_TAB_COMISSAO B ON
		B.CD_FUN = A.CD_VEND AND
		B.CD_PROD = A.CD_PROD AND
		B.CD_FILIAL = A.CD_FILIAL AND
		B.TP_NIVEL = A.TP_NIVEL_PERC AND B.TP_VALOR = 0 AND
		B.PERC_COMIS = A.PERC_COMIS_VENDA_NOVO AND
		B.TIPO = ISNULL(A.FLAG_PRE_VENCIDOS,0)

	UPDATE A
	SET A.DS_COMIS_VLR = REPLACE(A.DS_COMIS_VLR,A.CD_TBL_COMIS_VLR,B.CD_TBL_COMIS)
	-- SELECT REPLACE(A.DS_COMIS_PERC,A.CD_TBL_COMIS_PERC,B.CD_TBL_COMIS_PERC), *
	FROM #VENDASPROCESSAR A
	JOIN #COD_TAB_COMISSAO B ON
		B.CD_FUN = A.CD_VEND AND
		B.CD_PROD = A.CD_PROD AND
		B.CD_FILIAL = A.CD_FILIAL AND
		B.TP_NIVEL = A.TP_NIVEL_VLR AND B.TP_VALOR = 1 AND
		B.PERC_COMIS = A.VLR_COMISSAO_FABRIC_VENDA_NOVO AND
		B.TIPO = ISNULL(A.FLAG_PRE_VENCIDOS,0)

	DROP TABLE #COD_TAB_COMISSAO
-------------------------------------------------------------------------------------------------------------------------------
	if @consulta=1
	begin
		select * from #VENDASPROCESSAR
		select * from #RS_RET
		select * from #RS_TAB_COMIS_2
		return;
	end
-------------------------------------------------------------------------------------------------------------------------------
	--Remove os valores iguais, pois nao precisa atualizar
	IF @CD_PROD=0
	BEGIN
		DELETE FROM #VENDASPROCESSAR
		WHERE
			 PERC_COMIS_VENDA=PERC_COMIS_VENDA_NOVO
			 AND VLR_COMISSAO_FABRIC_VENDA=VLR_COMISSAO_FABRIC_VENDA_NOVO;
	END
-------------------------------------------------------------------------------------------------------------------------------
	DECLARE @movimento_vendas_prod 
			TABLE(dt_vd            datetime
						,cd_vend          int
						,cd_prod          int
						,tot_it           money
						,vlr_desc_tot_rat money);
    PRINT 'COMISSAO VENDAS' 
	DECLARE Curitens CURSOR FAST_FORWARD READ_ONLY
	FOR SELECT
			   A.CD_EMP
			 , A.CD_FILIAL
			 , A.CD_VD
			 , A.CD_IT
			 , A.CD_PROD
			 , A.CD_VEND
			 , A.PERC_COMIS_VENDA_NOVO
			 , A.DS_COMIS_PERC
			 , A.VLR_COMISSAO_FABRIC_VENDA_NOVO
			 , A.DS_COMIS_VLR 
		FROM
			#VENDASPROCESSAR A  
	  OPEN CURITENS  
	  FETCH NEXT FROM CURITENS INTO @CD_EMP_RS, @CD_FILIAL_RS, @CD_VD_RS, 
									@CD_IT_RS, @CD_PROD_RS, @CD_VEND_RS,
									@PERC_COMIS,@DS_PERC_COMIS,
									@VLR_COMISSAO_FABRIC,@DS_VLR_COMIS 
	WHILE @@FETCH_STATUS=0
	BEGIN
		PRINT 'FILIAL.: '+CONVERT(VARCHAR(100),@CD_FILIAL_RS)+' VENDEDOR.: '+CONVERT(VARCHAR(100),@CD_VEND_RS)
				+' PRODUTO.: '+CONVERT(VARCHAR(100),@CD_PROD_RS)+' TIPO COMISSAO.:  '+@DS_PERC_COMIS+' DESCRI. COMISSAO.:  '+@DS_VLR_COMIS;
		DELETE FROM @movimento_vendas_prod;
		-----------------------------------------------------------------
		UPDATE I
		SET
			I.PERC_COMIS=@PERC_COMIS
			,I.PERC_COMI=@PERC_COMIS
			,I.DS_PERC_COMIS=@DS_PERC_COMIS
			,I.VLR_COMISSAO_FABRIC=@VLR_COMISSAO_FABRIC
			,I.DS_VLR_COMIS=@DS_VLR_COMIS
		OUTPUT
				INSERTED.dt_vd
			,INSERTED.cd_vend
			,INSERTED.cd_prod
			,INSERTED.TOT_IT
			,INSERTED.VLR_DESC_TOT_RAT
			INTO @movimento_vendas_prod
		FROM PDV_VD_IT I
		WHERE
				I.CD_EMP=@CD_EMP_RS
				AND I.CD_FILIAL=@CD_FILIAL_RS
				AND I.CD_VD=@CD_VD_RS
				AND I.CD_VEND=@CD_VEND_RS
				AND I.CD_IT=@CD_IT_RS;
		-----------------------------------------------------------------
		--PRINT 'update EST_MOVIMENTO_VENDAS_PRODUTOS time: '+CONVERT(VARCHAR,GETDATE(),108);
--Tag #A001
		UPDATE PROD
		SET
			VLR_COMISSAO=(((TMP.TOT_IT-TMP.VLR_DESC_TOT_RAT)*@PERC_COMIS)/100)
			,VLR_COMISSAO_FABRIC=@VLR_COMISSAO_FABRIC
		FROM 
			@MOVIMENTO_VENDAS_PROD TMP
			INNER JOIN GLB_DT_MOVIMENTO DT ON TMP.DT_VD=DT.DT_MOVIMENTO
			INNER JOIN EST_MOVIMENTO_VENDAS VD ON VD.CD_CTR_DT_MOVIMENTO=DT.CD_CTR_DT_MOVIMENTO
			INNER JOIN EST_MOVIMENTO_VENDAS_PRODUTOS PROD ON VD.CD_EMP        = PROD.CD_EMP	
														 and VD.CD_CTR_VENDAS = PROD.CD_CTR_VENDAS
														 AND PROD.CD_VEND     = TMP.CD_VEND
														 AND PROD.CD_PROD     = TMP.CD_PROD
		WHERE
			vd.CD_EMP=@CD_EMP_RS
			AND vd.CD_FILIAL=@CD_FILIAL_RS
			AND vd.tipo_venda=0;
		-----------------------------------------------------------------

		--PRÓXIMA LINHA DO CURSOR
		FETCH NEXT FROM Curitens INTO @CD_EMP_RS
										,@CD_FILIAL_RS
										,@CD_VD_RS
										,@CD_IT_RS
										,@CD_PROD_RS
										,@CD_VEND_RS
										,@PERC_COMIS
										,@DS_PERC_COMIS
										,@VLR_COMISSAO_FABRIC
										,@DS_VLR_COMIS;
	END;
	CLOSE Curitens; 
	DEALLOCATE Curitens;
/*********************************************************************************************************************/
/*********************************************************************************************************************/
	PRINT 'Comissao devolucao' 
/*********************************************************************************************************************/
	TRUNCATE TABLE #VENDASPROCESSAR
	INSERT INTO #VENDASPROCESSAR 
	SELECT DISTINCT
		   A.CD_EMP
		 , A.CD_FILIAL
		 , A.CD_VD
		 , A.CD_IT
		 , A.CD_PROD
		 , A.CD_VEND
		 , A.PERC_COMIS
		 , ISNULL(A.VLR_COMISSAO_FABRIC, 0)
		 , 0 PERC_NOVO
		 , 0 VLR_NOVO
		 , 'NAO DEFINIDO' DS_COMIS_PERC
		 , 'NAO DEFINIDO' DS_COMIS_VLR
		 , CASE WHEN @PRE_VENC_NOVO_MODELO = 1 THEN VD.FLAG_PRE_VENCIDOS ELSE 0 END
		 , 0
		 , 0
		 , 0
		 , 0
		 , a.DT_DEVO
	FROM
		PDV_VD_DEV_EST_PROD_IMP A
		INNER JOIN #TMP_FILIAL L ON A.CD_FILIAL = L.CD_FILIAL
									AND A.CD_EMP = L.CD_EMP
		INNER JOIN FP_FUNC ON A.CD_EMP = FP_FUNC.CD_EMP
							  AND A.CD_VEND = FP_FUNC.CD_FUN
		INNER JOIN FP_CARGO_EST_PROD_TBL_COMIS CC ON FP_FUNC.CD_EMP = CC.CD_EMP
													 AND FP_FUNC.CD_CARGO = CC.CD_CARGO
		INNER JOIN #V_EST_PROD_TBL_COMIS_POSSUI PC ON A.CD_EMP = PC.CD_EMP
													 AND A.CD_FILIAL = PC.CD_FILIAL
													 AND A.CD_PROD = PC.CD_PROD
													 AND PC.TIPO_COMISSAO = 0
		INNER JOIN PDV_VD_IT VD ON VD.CD_EMP = A.CD_EMP
								AND VD.CD_FILIAL = A.CD_FILIAL
								AND VD.CD_VD = A.CD_VD
								AND VD.CD_IT = A.CD_IT
	WHERE  A.CD_EMP = @CD_EMP
		   AND A.DT_DEVO BETWEEN @DT_INI AND @DT_FIM
		   AND A.CD_PROD = CASE
							   WHEN @CD_PROD = 0 THEN A.CD_PROD
							   ELSE @CD_PROD
						   END;
/********************************************************************************************************/
	UPDATE A
	SET
		PERC_COMIS_VENDA_NOVO			= PERC_COMIS,
		VLR_COMISSAO_FABRIC_VENDA_NOVO  = VLR_COMIS,
		DS_COMIS_PERC					= F.DS_COMIS_PERC,
		DS_COMIS_VLR					= F.DS_COMIS_VLR
	FROM 
		#VENDASPROCESSAR A  
		CROSS APPLY UFD_EST_PROD_COMIS_HISTORICO(A.CD_EMP, A.CD_FILIAL, A.CD_PROD, A.CD_VEND, A.FLAG_PRE_VENCIDOS, A.DT_VD) F 
	--REMOVE OS VALORES IGUAIS, POIS NAO PRECISA ATUALIZAR
	DELETE FROM #VENDASPROCESSAR
	WHERE
			 PERC_COMIS_VENDA		   = PERC_COMIS_VENDA_NOVO
		 AND VLR_COMISSAO_FABRIC_VENDA = VLR_COMISSAO_FABRIC_VENDA_NOVO
/********************************************************************************************************/
	DECLARE CURITENSDEV CURSOR FAST_FORWARD READ_ONLY
	FOR SELECT  
			   A.CD_EMP
			 , A.CD_FILIAL
			 , A.CD_VD
			 , A.CD_IT
			 , A.CD_PROD
			 , A.CD_VEND
			 , A.PERC_COMIS_VENDA_NOVO
			 , A.DS_COMIS_PERC
			 , A.VLR_COMISSAO_FABRIC_VENDA_NOVO
			 , A.DS_COMIS_VLR 
		FROM
			#VENDASPROCESSAR A;
	OPEN CURITENSDEV 
	FETCH NEXT FROM CURITENSDEV INTO @CD_EMP_RS, @CD_FILIAL_RS, @CD_VD_RS, 
													@CD_IT_RS, @CD_PROD_RS, @CD_VEND_RS,
													@PERC_COMIS,@DS_PERC_COMIS,
													@VLR_COMISSAO_FABRIC,@DS_VLR_COMIS 
  WHILE @@FETCH_STATUS = 0
   BEGIN   
		PRINT 'FILIAL.: ' + CONVERT(VARCHAR(100), @CD_FILIAL_RS) +  ' VENDEDOR.: ' + CONVERT(VARCHAR(100), @CD_VEND_RS) + ' PRODUTO.: ' + CONVERT(VARCHAR(100), @CD_PROD_RS) 
								+ ' TIPO COMISSAO.:  ' + @DS_PERC_COMIS + ' DESCRI. COMISSAO.:  ' + @DS_VLR_COMIS
		UPDATE I
		  SET
			  I.PERC_COMIS = @PERC_COMIS
			, I.DS_PERC_COMIS = @DS_PERC_COMIS
			, I.VLR_COMISSAO_FABRIC = @VLR_COMISSAO_FABRIC
			, I.DS_VLR_COMIS = @DS_VLR_COMIS
		FROM   PDV_VD_DEV_EST_PROD_IMP I
		WHERE
			  I.CD_EMP = @CD_EMP_RS
			  AND I.CD_FILIAL = @CD_FILIAL_RS
			  AND I.CD_VD	= @CD_VD_RS
			  AND I.CD_VEND = @CD_VEND_RS
			  AND I.CD_IT	= @CD_IT_RS;				
					 
		--PRÓXIMA LINHA DO CURSOR
		FETCH NEXT FROM CURITENSDEV INTO @CD_EMP_RS
									   , @CD_FILIAL_RS
									   , @CD_VD_RS
									   , @CD_IT_RS
									   , @CD_PROD_RS
									   , @CD_VEND_RS
									   , @PERC_COMIS
									   , @DS_PERC_COMIS
									   , @VLR_COMISSAO_FABRIC
									   , @DS_VLR_COMIS;
   END
  CLOSE CURITENSDEV
  DEALLOCATE CURITENSDEV 
END