---------------------------------------------
CREATE OR REPLACE TRIGGER ATUALIZA_UPDATE_LOGMOVIEST BEFORE UPDATE ON ITLANCTOEST
FOR EACH ROW
DECLARE
   DTATUAL        DATE;
   V_IDCTRLESTQLG VARCHAR2(1);
   V_IDESONLINELG VARCHAR2(1);
   V_IDPESTNEGALG VARCHAR2(1);
   V_COUNT        NUMBER;

BEGIN
   DTATUAL := TO_DATE(TO_CHAR(SYSDATE,'DD/MM/YYYY HH24MISS'),'DD/MM/YYYY HH24MISS');


   IF :OLD.DTLANCMOVI <> :NEW.DTLANCMOVI THEN
      :NEW.DTLANCMOVANT := NVL(:OLD.DTLANCMOVI,:NEW.DTLANCMOVI);
   END IF;

   IF (:NEW.CDFILIMOVI   <> :OLD.CDFILIMOVI)   OR (:NEW.CDPRODMOVI   <> :OLD.CDPRODMOVI)   OR
      (:NEW.CDALMOXARIFE <> :OLD.CDALMOXARIFE) OR (:NEW.CDLOCALESTOQ <> :OLD.CDLOCALESTOQ) OR
      (:NEW.NRLOTEESTQ   <> :OLD.NRLOTEESTQ)   OR (:NEW.NRSUBLOTE    <> :OLD.NRSUBLOTE)    THEN

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

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