IF OBJECT_ID ('TRG_EST_PROD_PDV_PEND', 'TR') IS NOT NULL
BEGIN
	DROP TRIGGER TRG_EST_PROD_PDV_PEND
END
GO

CREATE TRIGGER [dbo].[TRG_EST_PROD_PDV_PEND] ON [dbo].[EST_PROD] FOR INSERT,UPDATE AS
BEGIN	

	IF UPDATE(LISTA_PROD) OR UPDATE(TIPO_TRIBUTACAO_PIS_COFINS) OR UPDATE(FLAG_TRIB_PIS_COFINS_PROD)
    BEGIN
        BEGIN TRY

		 INSERT INTO EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND
		 SELECT DISTINCT A.CD_EMP, REG.CD_REGIAO_FISCAL, A.CD_PROD, 0 AS CD_CTR, GETDATE()
		 FROM INSERTED A
		 CROSS APPLY (SELECT DISTINCT CD_REGIAO_FISCAL 
		 			 FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST) REG
		 WHERE A.STS_PROD <> 1
		 --AND A.TIPO_TRIBUTACAO_PIS_COFINS IN (0,1,2) /*Saída*/
		 AND NOT EXISTS (SELECT 1 
		 				FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND P
		 				WHERE P.CD_EMP = A.CD_EMP
		 						AND P.CD_REGIAO_FISCAL = REG.CD_REGIAO_FISCAL
		 						AND P.CD_PROD = A.CD_PROD
		 						AND P.CD_CTR  = 0)
		END TRY
		BEGIN CATCH
			PRINT 1
		END CATCH
    END
END



