 /****** Object:  Trigger [dbo].[TRG_EST_PROD_CPL_MEDIA_F_MEDIA_P]    Script Date: 23/03/2017 15:12:04 ******/
IF EXISTS( SELECT * FROM SYS.OBJECTS 
			WHERE NAME ='TRG_EST_PROD_CPL_MEDIA_F_MEDIA_P'AND TYPE = 'TR')
BEGIN
	DROP TRIGGER DBO.TRG_EST_PROD_CPL_MEDIA_F_MEDIA_P
END
GO
---
CREATE TRIGGER [dbo].[TRG_EST_PROD_CPL_MEDIA_F_MEDIA_P] ON [dbo].[EST_PROD_CPL] 
FOR INSERT
AS

	create table #TmpProd (CD_EMP INT, CD_FILIAL INT, CD_PROD INT);

	INSERT INTO #TmpProd 
	SELECT 
		I.CD_EMP,
		I.CD_FILIAL,
		I.CD_PROD
	FROM
		INSERTED i
		LEFT JOIN EST_PROD_CPL_MEDIAF f ON 
		i.CD_EMP = f.CD_EMP AND
		i.CD_FILIAL = f.CD_FILIAL AND
		i.CD_PROD = f.CD_PROD
		AND F.CD_EMP=1
	WHERE
		F.CD_EMP IS NULL

	--Inserindo automaticamente a media F somente jogando a curva padrao
	INSERT INTO EST_PROD_CPL_MEDIAF	
			(CD_EMP, CD_FILIAL,  CD_PROD,  CD_SIGLA, 
			QTDE_MEDIAF,  QTDE_FINANCIADO,  QTDE_FACEAMENTO,  QTDE_LIMITADOR,  VALID_QTDE_FACEAMENTO, 
			QT_VD_ATUAL, QT_VD_MES1, QT_VD_MES2, QT_VD_MES3, LIMITP, LIMITV, CD_USU, DT_CAD, DT_ULT_ALT, SAZ, DT_NASC)
	SELECT 
		i.CD_EMP, 
		i.CD_FILIAL, 
		i.CD_PROD, 
		4,
		0 AS QTDE_MEDIAF, 
		0 AS QTDE_FINANCIADO, 
		0 AS QTDE_FACEAMENTO, 
		0 AS QTDE_LIMITADOR, 
		NULL AS VALID_QTDE_FACEAMENTO, 
		0 AS QT_VD_ATUAL, 
		0 AS QT_VD_MES1, 
		0 AS QT_VD_MES2, 
		0 AS QT_VD_MES3, 
		0 AS LIMITP, 
		0 AS LIMITV, 
		1 AS CD_USU, 
		CONVERT(CHAR(10),GETDATE(),112) AS DT_CAD, 
		NULL AS DT_ULT_ALT, 
		0 AS SAZ,
		NULL AS DT_NASC
	FROM
		#TmpProd i ;

	TRUNCATE TABLE #TmpProd ;
	
	INSERT INTO #TmpProd 
	SELECT 
		I.CD_EMP,
		I.CD_FILIAL,
		I.CD_PROD
	FROM
		INSERTED i
		LEFT JOIN EST_PROD_CPL_MEDIAP f ON 
		i.CD_EMP = f.CD_EMP AND
		i.CD_FILIAL = f.CD_FILIAL AND
		i.CD_PROD = f.CD_PROD
		AND F.CD_EMP=1
	WHERE
		F.CD_EMP IS NULL


--Inserindo automaticamente a media prevista de vendas zerada
	INSERT INTO EST_PROD_CPL_MEDIAP
		(CD_EMP,
		CD_FILIAL,
		CD_PROD,
		QTDE_MEDIAP,
		CD_USU,
		DT_CAD,
		DT_ULT_ALT)
	SELECT
		i.CD_EMP,
		i.CD_FILIAL,
		i.CD_PROD,
		0,
		1,
		CONVERT(CHAR(10),GETDATE(),112) AS DT_CAD, 
		NULL
	FROM
		#TmpProd i ;

	INSERT INTO EST_PROD_CPL_EST_PROD_PRECO_SEM_CADASTRO
	(
		   CD_EMP
		 , CD_FILIAL
		 , CD_PROD
		 , DT_CAD
	)
	SELECT
			CD_EMP
		, CD_FILIAL
		, CD_PROD
		, GETDATE()
	FROM
		INSERTED;