create or replace TRIGGER GERA_PARCNEGOCIO_CLIENTE
BEFORE INSERT OR UPDATE ON CLIENTE
FOR EACH ROW

DECLARE

   V_NOVOCODIGO    VARCHAR2(20);
   V_INSCJUR       VARCHAR2(20);
   V_NRPARCNEGOCIO VARCHAR2(20);
   V_COUNT 	       NUMBER;
   V_TIPOINSC 	   VARCHAR2(10);
   V_IDATIVO       VARCHAR2(1);

BEGIN

	V_TIPOINSC :=
    CASE :NEW.IDTPIJURCLIE
		WHEN 'J' THEN 'CNPJ'
		WHEN 'F' THEN 'CPF'
		WHEN 'O' THEN 'CODIGO'
		ELSE 'LIVRE'
    END;

	V_IDATIVO :=
	CASE :NEW.IDCLIEATIV
		WHEN 'N' THEN 'N'
		ELSE 'S'
	END;

   IF :NEW.NRPARCNEGOCIO IS NULL THEN

      SELECT MAX(NRINSCRICAOPARC), MAX(NRPARCNEGOCIO) INTO V_INSCJUR, V_NRPARCNEGOCIO
      FROM PARCNEGOCIO
      WHERE NRINSCRICAOPARC = :NEW.NRINSJURCLIE
	  AND NRORG = :NEW.NRORG;

      IF V_INSCJUR IS NULL THEN
         NOVO_CODIGO_SC('PARCNEGOCIO',V_NOVOCODIGO);
         V_NOVOCODIGO := SUBSTR(V_NOVOCODIGO, 11, 10);

         INSERT INTO PARCNEGOCIO
           (NRPARCNEGOCIO, NRORG, CDTIPOPARCPRINCIPAL, CDSEGMER, NMPRINCIPALPARC, NMSECUNDARIPARC,
		    CDTIPOINSCRICAO, NRINSCRICAOPARC, IDATIVO, DTINCLUSAO, IDINSTITUICAO, DTNASCIFUNDPARC,
			NRORGINCLUSAO, CDOPERINCLUSAO, NRINSCESTADUAL)
         VALUES
           (V_NOVOCODIGO, :NEW.NRORG, 'CLIENTE', :NEW.CDSEGMER, :NEW.NMRAZSOCCLIE, :NEW.NMFANTCLIE,
		    V_TIPOINSC, :NEW.NRINSJURCLIE, V_IDATIVO, SYSDATE, 'S', :NEW.DTNASCCLIE,
			:NEW.NRORGINCLUSAO, :NEW.CDOPERINCLUSAO, :NEW.NRINSESTCLIE);

         :NEW.NRPARCNEGOCIO := V_NOVOCODIGO;
      ELSE
         :NEW.NRPARCNEGOCIO := V_NRPARCNEGOCIO;

		 UPDATE PARCNEGOCIO SET CDTIPOPARCPRINCIPAL =  'CLIENTE', CDOPERULTATU = :NEW.CDOPERULTATU
         WHERE NRPARCNEGOCIO = V_NRPARCNEGOCIO
	     AND NRORG = :NEW.NRORG;

      END IF;
   ELSE
      UPDATE PARCNEGOCIO SET CDTIPOINSCRICAO = V_TIPOINSC, DTULTATU = SYSDATE,
			 IDATIVO = V_IDATIVO,
			 CDTIPOPARCPRINCIPAL =  'CLIENTE', IDINSTITUICAO = 'S', CDSEGMER = :NEW.CDSEGMER,
			 NMPRINCIPALPARC = :NEW.NMRAZSOCCLIE, NMSECUNDARIPARC = :NEW.NMFANTCLIE,
			 NRINSCRICAOPARC = :NEW.NRINSJURCLIE, NRORGULTATU = :NEW.NRORGULTATU,
			 CDOPERULTATU = :NEW.CDOPERULTATU, DTNASCIFUNDPARC = :NEW.DTNASCCLIE, NRINSCESTADUAL = :NEW.NRINSESTCLIE
       WHERE NRPARCNEGOCIO = :NEW.NRPARCNEGOCIO
	   AND NRORG = :NEW.NRORG;
   END IF;

   SELECT COUNT(*) INTO V_COUNT
   FROM PARCERIA
   WHERE NRPARCNEGOCIO = :NEW.NRPARCNEGOCIO
   AND CDTIPOPARCEIRO = 'CLIENTE'
   AND NRORG = :NEW.NRORG;

   IF V_COUNT = 0 THEN
      NOVO_CODIGO_SC('PARCERIA', V_NOVOCODIGO);
      V_NOVOCODIGO := SUBSTR(V_NOVOCODIGO, 11, 10);

	  INSERT INTO PARCERIA
        (NRPARCERIA, NRPARCNEGOCIO, CDTIPOPARCEIRO, NRORG)
      VALUES
        (V_NOVOCODIGO, :NEW.NRPARCNEGOCIO, 'CLIENTE', :NEW.NRORG);

   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('GERA_PARCNEGOCIO_CLIENTE','0.00.000'); END;
/
