CREATE OR REPLACE PROCEDURE CALCULA_LUCRO_PRESUMIDO(
   P_CDIMPOSTO      IN   IMPOSTONF.CDIMPOSTO%TYPE,
   P_NRSEQUMAPAPU   IN   IMPOSTONF.NRSEQUMAPAPU%TYPE)
AS
   V_VRIMPOSTONF    NUMBER;
   V_NRSEQITMAPR    VARCHAR2(04);
   V_SEQUENCIAL     NUMBER;
   V_VRSALDODEBI    NUMBER;
   V_VROUTRCRED     NUMBER;
   V_VRTOTACRED     NUMBER;
BEGIN

  /* totaliza o valor do imposto Lucro presumido, que foi apurado com o ICMS  */
  SELECT SUM(VRIMPOSTONF)
    INTO V_VRIMPOSTONF
    FROM IMPOSTONF I, (SELECT DISTINCT CDFILIAL, NRLANCTONF
                         FROM IMPOSTONF
                        WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
                          AND CDIMPOSTO = P_CDIMPOSTO) IM
   WHERE I.CDFILIAL = IM.CDFILIAL
     AND I.NRLANCTONF = IM.NRLANCTONF
     AND CDIMPOSTO = (SELECT MAX(CDLUCROPRESUMI)
                        FROM IMPOSTO
                       WHERE CDIMPOSTO = P_CDIMPOSTO);

   IF V_VRIMPOSTONF > 0 THEN

      SELECT MAX(NRSEQITMAPR)
        INTO V_NRSEQITMAPR
        FROM ITMAPARECUP
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
         AND IDTIPOITMAPR = 'OC'
         AND DSITEMMAPR LIKE 'CREDITO PRESUMIDO OPERACOES INTERNAS';

      IF V_NRSEQITMAPR IS NULL THEN
         SELECT MAX(NRSEQITMAPR)
           INTO V_SEQUENCIAL
           FROM ITMAPARECUP
          WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
            AND IDTIPOITMAPR = 'OC';

         INSERT INTO ITMAPARECUP
           (NRSEQUMAPAPU, IDTIPOITMAPR, NRSEQITMAPR, DSITEMMAPR, VRITEMMAPR)
         VALUES
           (P_NRSEQUMAPAPU, 'OC', LPAD(TO_CHAR(NVL(V_SEQUENCIAL,0)+1), 3, '0'), 'CREDITO PRESUMIDO OPERACOES INTERNAS', ROUND(V_VRIMPOSTONF,2));

           UPDATE MAPARECUP
              SET VROUTRCRED = NVL(VROUTRCRED,0) + ROUND(V_VRIMPOSTONF,2),
                  VRTOTACRED = NVL(VRTOTACRED,0) + ROUND(V_VRIMPOSTONF,2),
                  VRSALDODEBI = ABS(VRTOTADEBI - VRTOTACRED)
            WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

           SELECT SUM(VROUTRCRED), SUM(VRTOTACRED)
             INTO V_VROUTRCRED, V_VRTOTACRED
             FROM MAPARECUP
            WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

           SELECT SUM(VRSALDODEBI)
             INTO V_VRSALDODEBI
             FROM MAPARECUP
            WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

           /* atualiza o valor do imposto a recolher */
           UPDATE MAPAAPURAC
              SET VRTOTAIMPOS = ROUND(V_VRSALDODEBI,2) - ROUND(V_VRTOTACRED,2)
            WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

           UPDATE MAPARECUP
              SET VRSALDODEBI = ROUND(V_VRSALDODEBI,2) - ROUND(V_VRTOTACRED,2)
            WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;
 
      ELSE
         UPDATE ITMAPARECUP
            SET VRITEMMAPR = ROUND(V_VRIMPOSTONF,2)
          WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
            AND IDTIPOITMAPR = 'OC'
            AND DSITEMMAPR LIKE 'CREDITO PRESUMIDO OPERACOES INTERNAS'
            AND NRSEQITMAPR = V_NRSEQITMAPR;
          COMMIT;
      END IF;
   END IF;
END;
/