CREATE OR REPLACE PROCEDURE GRAVA_PARCELA(
   P_CDEMPRESA    IN MAPAAPURAC.CDEMPRESA%TYPE,
   P_CDINSCRICAO  IN MAPAAPURAC.CDINSCESTA%TYPE,
   P_DTINICIAL    IN MAPAAPURAC.DTINIPERIODO%TYPE,
   P_DTFINAL      IN MAPAAPURAC.DTFIMPERIODO%TYPE,
   P_NRSEQUMAPAPU IN MAPAAPURAC.NRSEQUMAPAPU%TYPE,
   P_CDIMPOSTO    IN MAPAAPURAC.CDIMPOSTO%TYPE)
AS
   V_STFILIAL           VARCHAR2(04);
   V_STLANC             VARCHAR2(10);
   V_STSEQU             VARCHAR2(10);
   V_CDIMPATIVPER       VARCHAR2(02);
   V_FORMULAATIVO       NUMBER;
   V_FORMULAATIVOTOTAL  NUMBER;
   V_CONTA1             NUMBER;
   V_CONTA2             NUMBER;
   V_VRTOTAITEM         NUMBER;
   V_QTDPARC            NUMBER;
   V_VRCONTABIL         NUMBER;
   V_VRBASECALC         NUMBER;
   V_ITMAPARECUP        NUMBER;
   V_IDSOMAFECP         VARCHAR2(1);
BEGIN
   
   V_FORMULAATIVOTOTAL := 0;
   V_FORMULAATIVO      := 0;

   BEGIN
      SELECT CDIMPATIVPER
        INTO V_CDIMPATIVPER
        FROM PARAMFISCAL P, IMPOSTO I
       WHERE P.CDIMPATIVPER = I.CDIMPOSTO
         AND I.CDIMPOSTONFE = P_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDIMPATIVPER := NULL;
   END;

   V_STFILIAL := ' ';
   V_STLANC   := ' ';
   V_STSEQU   := ' ';
   
   BEGIN 
      SELECT IDSOMAFECP 
        INTO V_IDSOMAFECP
        FROM AJUSTEFECP
       WHERE CDEMPRESA    = P_CDEMPRESA
         AND CDINSCESTA   = P_CDINSCRICAO
         AND CDIMPOSTO    = P_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDSOMAFECP := 'S';
   END;    
   V_IDSOMAFECP := NVL(V_IDSOMAFECP,'S');
   
   IF V_CDIMPATIVPER IS NOT NULL THEN
      FOR C_ATIVOPER IN (SELECT PL.CDFILIAL, PL.NRLANCTONF, PL.NRSEQITPROD, TO_NUMBER(PL.NRPARCATIV) AS ORDPARCELAS,
                                PL.NRPARCATIV, PL.IDTRANSATIV, PL.NRSEQUMAPAPU, PL.VRPARCATIV
                           FROM NOTAFISCAL NF, ITEMPRODUTO IT, PARCLANCATIV PL
                          WHERE NF.CDEMPRESA    = P_CDEMPRESA
                            AND (P_CDINSCRICAO IS NULL OR NF.CDINSCESTA = P_CDINSCRICAO)
                            AND NF.IDENTRSAIDOP = 'E'
                            AND NF.CDFILIAL     = IT.CDFILIAL
                            AND NF.NRLANCTONF   = IT.NRLANCTONF
                            AND IT.QTPARCATIV   > 0
                            AND IT.CDFILIAL     = PL.CDFILIAL
                            AND IT.NRLANCTONF   = PL.NRLANCTONF
                            AND IT.NRSEQITPROD  = PL.NRSEQITPROD
                            AND (PL.IDTRANSATIV  IS NULL OR PL.IDTRANSATIV = 'N')
                            AND ((ADD_MONTHS(NF.DTENTRSAID, TO_NUMBER(PL.NRPARCATIV) - 1)) BETWEEN P_DTINICIAL AND P_DTFINAL)
                          ORDER BY PL.CDFILIAL, PL.NRLANCTONF, PL.NRSEQITPROD, ORDPARCELAS) LOOP

         IF (C_ATIVOPER.CDFILIAL <> V_STFILIAL) OR (C_ATIVOPER.NRLANCTONF <> V_STLANC) OR (C_ATIVOPER.NRSEQITPROD <> V_STSEQU) THEN
            IF C_ATIVOPER.NRSEQUMAPAPU IS NULL THEN
               /******* Busca o valor do Item **********/
               BEGIN
                  SELECT SUM(I.VRIMPOSTOIT + DECODE(V_IDSOMAFECP,'N',0,NVL(I.VRADICFECP,0))) AS VRTOTAITEM
                    INTO V_VRTOTAITEM
                    FROM ITEMPROIMPOS I, NOTAFISCAL N , PARCLANCATIV P, IMPOSTO IP
                   WHERE N.CDEMPRESA     = P_CDEMPRESA
                     AND N.CDINSCESTA    = P_CDINSCRICAO
                     AND N.IDENTRSAIDOP  = 'E'
                     AND N.IDSTATUS      IN ('A','E')
                     AND N.CDFILIAL      = I.CDFILIAL
                     AND N.NRLANCTONF    = I.NRLANCTONF
                     AND IP.CDIMPOSTONFE = P_CDIMPOSTO
                     AND IP.CDIMPOSTO    = I.CDIMPOSTO
                     AND (I.VRIMPOSTOIT + DECODE(V_IDSOMAFECP,'N',0,NVL(I.VRADICFECP,0))) > 0
                     AND I.NRSEQITPROD   = C_ATIVOPER.NRSEQITPROD
                     AND N.CDFILIAL      = C_ATIVOPER.CDFILIAL
                     AND N.NRLANCTONF    = C_ATIVOPER.NRLANCTONF
                     AND N.CDFILIAL      = P.CDFILIAL
                     AND N.NRLANCTONF    = P.NRLANCTONF
                     AND I.NRSEQITPROD   = P.NRSEQITPROD
                     AND P.NRSEQUMAPAPU IS NULL
                     AND NRPARCATIV      = (SELECT MIN(TO_NUMBER(NRPARCATIV))
                                              FROM PARCLANCATIV
                                             WHERE NRLANCTONF   = C_ATIVOPER.NRLANCTONF
                                               AND CDFILIAL     = C_ATIVOPER.CDFILIAL
                                               AND NRSEQITPROD  = C_ATIVOPER.NRSEQITPROD
                                               AND NRSEQUMAPAPU IS NULL);
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_VRTOTAITEM := 0;
               END;

               /******* Atualiza o numero do Mapa na Parcela ***********/
               UPDATE PARCLANCATIV
                  SET NRSEQUMAPAPU = P_NRSEQUMAPAPU
                WHERE CDFILIAL     = C_ATIVOPER.CDFILIAL
                  AND NRLANCTONF   = C_ATIVOPER.NRLANCTONF
                  AND NRSEQITPROD  = C_ATIVOPER.NRSEQITPROD
                  AND NRPARCATIV   = C_ATIVOPER.NRPARCATIV;

                /****** Busca o valor contabil e a base de calculo **********/
               BEGIN
                  SELECT ROUND(SUM(DECODE(N.IDENTRSAIDOP,'S',ROUND(I.VRCONTABILNF,2),0)),2) AS VRCONTABIL,
                         ROUND(SUM(DECODE(I.CDFISCALNF,'1',DECODE(N.IDENTRSAIDOP,'S',ROUND(I.VRBASECALCNF,2),0),0)),2) AS VRBASECALC
                    INTO V_VRCONTABIL, V_VRBASECALC
                    FROM IMPOSTONF I, NOTAFISCAL N, IMPOSTO IP
                   WHERE I.CDFILIAL      = N.CDFILIAL
                     AND I.NRLANCTONF    = N.NRLANCTONF
                     AND (N.IDENTRSAIDOP = 'S' AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL)
                     AND N.IDSTATUS      IN ('A','E')
                     AND IP.CDIMPOSTONFE = P_CDIMPOSTO
                     AND IP.CDIMPOSTO    = I.CDIMPOSTO
                     AND (N.CDINSCESTA   = P_CDINSCRICAO OR P_CDINSCRICAO IS NULL)
                     AND N.CDEMPRESA     = P_CDEMPRESA;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_VRCONTABIL := 0;
                     V_VRBASECALC := 0;
               END;

               /********* Busca o numero de parcelas ********/
               BEGIN
                  SELECT COUNT(NRPARCATIV) AS QTDPARC
                    INTO V_QTDPARC
                    FROM PARCLANCATIV
                   WHERE CDFILIAL     = C_ATIVOPER.CDFILIAL
                     AND NRLANCTONF   = C_ATIVOPER.NRLANCTONF
                     AND NRSEQITPROD  = C_ATIVOPER.NRSEQITPROD;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_QTDPARC := 0;
               END;

                /******** Calcula o valor do ativo que pode ser aproveitado como credito ************/
               IF (V_QTDPARC <> 0) AND (V_VRCONTABIL <> 0) THEN
                  IF C_ATIVOPER.IDTRANSATIV <> 'S' THEN
                     V_CONTA1 := V_VRTOTAITEM / V_QTDPARC;
                     V_CONTA2 := V_VRBASECALC / V_VRCONTABIL;
                     V_FORMULAATIVO      := V_CONTA1 * V_CONTA2;
                     V_FORMULAATIVOTOTAL := V_FORMULAATIVOTOTAL + V_FORMULAATIVO;
                  ELSE
                     V_FORMULAATIVO      := 0;
                     V_FORMULAATIVOTOTAL := 0;
                  END IF;
               ELSE
                  V_FORMULAATIVO      := 0;
                  V_FORMULAATIVOTOTAL := 0;
               END IF;

               /******** Atualiza o valor de credito aproveitado na parcela ************/
               UPDATE PARCLANCATIV
                  SET VRCRAPRPARCLAN = V_FORMULAATIVO
                WHERE CDFILIAL       = C_ATIVOPER.CDFILIAL
                  AND NRLANCTONF     = C_ATIVOPER.NRLANCTONF
                  AND NRSEQITPROD    = C_ATIVOPER.NRSEQITPROD
                  AND NRPARCATIV     = C_ATIVOPER.NRPARCATIV;

               /******** Busca o maior sequencial de outros creditos ************/
               BEGIN
                  SELECT NVL(MAX(NRSEQITMAPR),0) AS NRSEQITMAPR
                    INTO V_ITMAPARECUP
                    FROM ITMAPARECUP
                   WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
                     AND IDTIPOITMAPR = 'OC';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_ITMAPARECUP := 0;
               END;

               V_ITMAPARECUP := NVL(V_ITMAPARECUP,0) + 1;

               /******** Insere o item de outros creditos referentes ao ativo permanente ************/
               INSERT INTO ITMAPARECUP
                  (NRSEQUMAPAPU, IDTIPOITMAPR, NRSEQITMAPR, DSITEMMAPR, VRITEMMAPR, CDITEMOCOR, DSITEMOCOR,
                   DSFLEGALOCOR, NRLANCTONF, CDFILIAL, CDAJUSTEITMAPA, CDAJUSTEITSEF, CDITPROCEDENCIA,
                   IDCREDPRESUMIDO, IDDIFALMANUAL, IDCARGATRIBUTARIA)
               VALUES
                  (P_NRSEQUMAPAPU, 'OC', LPAD(V_ITMAPARECUP,10,'0'), 'ATIVO PERMANENTE', V_FORMULAATIVO, '', '', '',
                   C_ATIVOPER.NRLANCTONF, C_ATIVOPER.CDFILIAL, '', '', '', 'N', 'N', 'N');

               /******** Atualiza os dados da nota atual, para evitar nao realizar o calculo novamente para a mesma nota ************/
               V_STFILIAL := C_ATIVOPER.CDFILIAL;
               V_STLANC   := C_ATIVOPER.NRLANCTONF;
               V_STSEQU   := C_ATIVOPER.NRSEQITPROD;
            END IF;
         END IF;
      END LOOP;
   END IF;
END;
/