--Atualiza_Insert_ItLanctoEst
CREATE OR REPLACE TRIGGER ATUALIZA_INSERT_ITLANCTOEST BEFORE INSERT ON ITLANCTOEST
FOR EACH ROW
DECLARE
   V_COUNT      NUMBER;
   V_DTLANCMOVI DATE;
BEGIN
   SELECT MAX(DTLANCESTQ), MAX(IDALTCUSMED),
          MAX(IDENTRSAIDOP), MAX(CDTIPOOPER),
          MAX(DSLANCESTQ), MAX(CDOPERADOR)
   INTO V_DTLANCMOVI, :NEW.IDALTCMEDMV,
        :NEW.IDENTRSAIDOP, :NEW.CDTIPOOPER,
        :NEW.DSLANCESTIT, :NEW.CDOPERADOR
   FROM LANCTOESTOQ
   WHERE CDFILIAL   = :NEW.CDFILIAL AND
         NRLANCESTQ = :NEW.NRLANCESTQ;

   IF :NEW.DTLANCMOVI IS NULL THEN
      :NEW.DTLANCMOVI := V_DTLANCMOVI;
   END IF;

   SELECT COUNT(*)
   INTO V_COUNT
   FROM LOTE
   WHERE  CDFILIAL   = :NEW.CDFILIMOVI  AND
          NRLOTEESTQ = :NEW.NRLOTEESTQ  AND
          NRSUBLOTE  = :NEW.NRSUBLOTE   AND
          CDPRODUTO  = :NEW.CDPRODMOVI;

   IF V_COUNT = 0 THEN
      INSERT INTO LOTE
      (CDFILIAL, NRLOTEESTQ, NRSUBLOTE,   CDPRODUTO, IDSTATLOTE, DTENTRLOTE)
      VALUES
      (:NEW.CDFILIMOVI, :NEW.NRLOTEESTQ, :NEW.NRSUBLOTE, :NEW.CDPRODMOVI, 'L', SYSDATE);
   END IF;

   SELECT COUNT(*)
   INTO V_COUNT
   FROM MOVILOTE
   WHERE NRMOVILOTE   = :NEW.CDFILIAL || :NEW.NRLANCESTQ AND
         CDFILIAL     = :NEW.CDFILIMOVI                  AND
         CDALMOXARIFE = :NEW.CDALMOXARIFE                AND
         CDLOCALESTOQ = :NEW.CDLOCALESTOQ                AND
         NRLOTEESTQ   = :NEW.NRLOTEESTQ                  AND
         NRSUBLOTE    = :NEW.NRSUBLOTE                   AND
         CDPRODUTO    = :NEW.CDPRODMOVI;

   IF V_COUNT = 0 THEN
      IF (:NEW.IDTIPOMOVI IN ('0', '1')) OR (:NEW.QTTOTLANCTO > 0) OR (:NEW.CDTIPOOPER = '03') THEN
         INSERT INTO MOVILOTE
            (NRMOVILOTE, CDFILIAL, CDALMOXARIFE, CDLOCALESTOQ,
             CDPRODUTO, NRLOTEESTQ, NRSUBLOTE, NRLANCTOORIG, DTMOVILOTE, DTMOVILOTEANT, CDSITUTRIBMOV)
         VALUES
            (:NEW.CDFILIAL || :NEW.NRLANCESTQ, :NEW.CDFILIMOVI, :NEW.CDALMOXARIFE, :NEW.CDLOCALESTOQ,
             :NEW.CDPRODMOVI, :NEW.NRLOTEESTQ, :NEW.NRSUBLOTE, :NEW.NRLANCORIGRP, :NEW.DTLANCMOVI, :NEW.DTLANCMOVI, :NEW.CDSITUTRIBEST);
      END IF;
   END IF;

   IF :NEW.IDTIPOMOVI = '3' THEN
      :NEW.IDORDEMCLC := '9';
   ELSIF :NEW.IDTIPOMOVI = '4' THEN
      :NEW.IDORDEMCLC := '8';
   ELSIF :NEW.IDTIPOMOVI = '5' THEN
      :NEW.IDORDEMCLC := '7';
   END IF;
END;
/
