CREATE OR REPLACE TRIGGER INSERE_DOC_ARRECADACAO_MAPA
AFTER UPDATE ON MAPAAPURAC
FOR EACH ROW
DECLARE
   V_SEQUENCIAL VARCHAR2(20);
   V_EXISTE VARCHAR2(01);
BEGIN
   V_EXISTE := 'N';
   BEGIN
      SELECT NVL(MAX('S'), 'N')
       INTO V_EXISTE
       FROM DOCARRECADPAG
      WHERE IDTIPOGUIA = 'M'
        AND NRSEQUMAPAPU = :NEW.NRSEQUMAPAPU;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_EXISTE := 'N';
   END;

   IF :NEW.NRLANCTONF IS NOT NULL THEN
      IF V_EXISTE = 'N' THEN
         NOVO_CODIGO_NT('DOCARRECADPAG', V_SEQUENCIAL);
         INSERT INTO DOCARRECADPAG
            (NRSEQDOCARRECAD, NRSEQUMAPAPU, NRSEQUMAPAPUSN, NRSEQGUIACOMPL, CDFILIAL, NRLANCTONF, CDIMPOSTO, DTVENCIMENTO,
             CDRECEITA, CDFILIALPAG, NRLANCTONFPAG, IDTIPOGUIA, DSINFOCOMPL)
         VALUES
            (TO_NUMBER(V_SEQUENCIAL), :NEW.NRSEQUMAPAPU, '', '', '', '', :NEW.CDIMPOSTO, :NEW.DTVENCGUIA,
             DECODE(:NEW.CDIMPOSTO, '50', NVL(:NEW.CDRECECUMU, :NEW.CDRECENCUMU),
                                    '60', NVL(:NEW.CDRECECUMU, :NEW.CDRECENCUMU), :NEW.CDRECEGUIA),
             :NEW.CDFILIAL, :NEW.NRLANCTONF, 'M', NVL(:NEW.DSHISTGUIA,:NEW.NMMAPAAPUR));
      ELSE
         UPDATE DOCARRECADPAG SET CDFILIALPAG = :NEW.CDFILIAL, NRLANCTONFPAG = :NEW.NRLANCTONF
          WHERE NRSEQUMAPAPU  = :NEW.NRSEQUMAPAPU
            AND IDTIPOGUIA    = 'M';
      END IF;
  ELSE
     UPDATE DOCARRECADPAG SET CDFILIALPAG   = NULL, NRLANCTONFPAG = NULL
      WHERE NRSEQUMAPAPU  = :NEW.NRSEQUMAPAPU
        AND IDTIPOGUIA    = 'M';
  END IF;
END;