IF EXISTS (SELECT * FROM SYS.triggers WHERE NAME = 'TRG_EST_SNGPC_ENTRADA_EXCLUSAO') 
BEGIN
	DROP TRIGGER TRG_EST_SNGPC_ENTRADA_EXCLUSAO
END


SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

/* GATILHOS (TRIGGERS) */
-- ENTRADA
CREATE TRIGGER dbo.TRG_EST_SNGPC_ENTRADA_EXCLUSAO ON dbo.EST_SNGPC_ENTRADA
WITH EXECUTE AS CALLER
FOR INSERT, UPDATE, DELETE
AS
BEGIN

	-- VERIFICA A QUANTIDADE JÁ INSERIDA E A QUANTIDADE CANCELADA
	DECLARE @QTDE INTEGER;
	DECLARE @QTDECANCEL INTEGER;

	SET @QTDE = (
		SELECT
			COALESCE(SUM(A.QT_LOTE), 0)
		FROM
			EST_SNGPC_ENTRADA (NOLOCK) A
			INNER JOIN INSERTED I ON
				A.CD_EMP = I.CD_EMP
				AND A.CD_FILIAL = I.CD_FILIAL
				AND A.CD_NF = I.CD_NF
				AND A.CD_PROD = I.CD_PROD
	);

	SET @QTDECANCEL = (
		SELECT
			COALESCE(SUM(A.QT_CANCEL), 0)
		FROM
			EST_NF_ENT_IT_EST_SNGPC_PENDENTE_CANCELADO (NOLOCK) A
			INNER JOIN INSERTED I ON
				A.CD_EMP = I.CD_EMP
				AND A.CD_FILIAL = I.CD_FILIAL
				AND A.CD_NF = I.CD_NF
				AND A.CD_PROD = I.CD_PROD
	);

	-- VERIFICA SE A QUANTIDADE INSERIDA BATE COM A DIFERENÇA ENTRA A QUANTIDADE DA NOTA E A QUANTIDADE CANCELADA
	IF EXISTS (
		SELECT 
			A.QT_IT
		FROM
			EST_NF_ENT_IT (NOLOCK) A
			INNER JOIN INSERTED I ON
				A.CD_EMP = I.CD_EMP
				AND A.CD_FILIAL = I.CD_FILIAL
				AND A.CD_NF = I.CD_NF
				AND A.CD_PROD = I.CD_PROD
		WHERE
			(A.QT_IT - @QTDECANCEL) = @QTDE
	)
		BEGIN
			-- REMOVE A PENDÊNCIA DE ENTRADA NO SNGPC
			DELETE 
					E
			FROM 
				EST_NF_ENT_IT_EST_SNGPC_PENDENTE E INNER JOIN INSERTED I ON
				E.CD_EMP = I.CD_EMP AND	
				E.CD_FILIAL = I.CD_FILIAL AND
				E.CD_NF = I.CD_NF AND
				E.CD_PROD = I.CD_PROD;
		END

	ELSE
		BEGIN
			-- VERIFICA SE A PENDÊNCIA AINDA EXISTE
			IF NOT EXISTS (
				SELECT 
					A.CD_EMP
				FROM
					EST_NF_ENT_IT_EST_SNGPC_PENDENTE (NOLOCK) A
					INNER JOIN DELETED D ON
						A.CD_EMP = D.CD_EMP
						AND A.CD_FILIAL = D.CD_FILIAL
						AND A.CD_NF = D.CD_NF
						AND A.CD_PROD = D.CD_PROD
				)
				BEGIN
					-- INSERE A PENDÊNCIA NOVAMENTE
					INSERT INTO EST_NF_ENT_IT_EST_SNGPC_PENDENTE
						SELECT 
							CD_EMP, 
							CD_FILIAL,
							CD_NF,
							CD_PROD,
							GETDATE()
						FROM 
							DELETED;
				END;
		END;
END
GO