CREATE OR REPLACE PROCEDURE INSERE_AJUSTE_CIAP(
  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)
IS
  V_CDAJUSTCIAPOC   PARAMESTSPED.CDAJUSTCIAPOC%TYPE;
  V_DSAJUSTCIAPOC   PARAMESTSPED.DSAJUSTCIAPOC%TYPE;
  V_TOTALCREDAPROP  NUMBER;
  V_NRSEQITMAPR    VARCHAR2(10);

BEGIN
  --Verifica se existe parametro para CIAP - Cod Ajuste - Outros Creditos
  BEGIN
    SELECT CDAJUSTCIAPOC,DSAJUSTCIAPOC
    INTO V_CDAJUSTCIAPOC, V_DSAJUSTCIAPOC
    FROM PARAMESTSPED
    WHERE cdempresa = P_CDEMPRESA
    AND cdinscesta = P_CDINSCRICAO;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
         V_CDAJUSTCIAPOC := '';
         V_DSAJUSTCIAPOC := '';
  END;

  /******** Deleta os itens de ajuste referente ao valor do CIAP gerado pela rotina, evitando erro na reapuracao de mapas ********/
           DELETE FROM ITMAPARECUP
            WHERE NRSEQUMAPAPU  = P_NRSEQUMAPAPU
            AND IDAJCIAP      = 'S';


  IF V_CDAJUSTCIAPOC IS NOT NULL THEN
   /*Base CIAP apropriada*/
           BEGIN
              SELECT ROUND(SUM(VRCREDAPROPCIAP),2)
                INTO V_TOTALCREDAPROP
                FROM CONTROLECIAP, IMPOSTO
                WHERE CONTROLECIAP.CDEMPRESA = P_CDEMPRESA
                   AND CONTROLECIAP.CDIMPOSTO = P_CDIMPOSTO
                   AND (CONTROLECIAP.DTCOMPETECIAP BETWEEN P_DTINICIAL AND P_DTFINAL)
                   AND CONTROLECIAP.CDIMPOSTO = IMPOSTO.CDIMPOSTO
                   AND (CONTROLECIAP.CDINSCESTA = P_CDINSCRICAO)
                   AND CONTROLECIAP.IDSITCOMPETCIAP = 'A'
                   AND ROUND(NVL(CONTROLECIAP.VRCREDAPROPCIAP,0),2) > 0;
           EXCEPTION
              WHEN NO_DATA_FOUND THEN
               V_TOTALCREDAPROP := 0;
           END;
            V_TOTALCREDAPROP := ROUND(NVL(V_TOTALCREDAPROP,0),2);



       /*Verifica se ja existe Sequencial*/
            BEGIN
               SELECT MAX(NRSEQITMAPR)
                INTO V_NRSEQITMAPR
                FROM ITMAPARECUP
                WHERE IDTIPOITMAPR = 'OC'
                AND  NRSEQUMAPAPU = P_NRSEQUMAPAPU;
            EXCEPTION
              WHEN NO_DATA_FOUND THEN
               V_NRSEQITMAPR := 0;
            END;


       /*Insere Valor referente ao Cod Ajuste - Outros Creditos */
            IF NVL(V_TOTALCREDAPROP,0) > 0 THEN
               V_NRSEQITMAPR := TO_CHAR(TO_NUMBER(NVL(V_NRSEQITMAPR,'0')) +1) ;
            INSERT INTO ITMAPARECUP
               (NRSEQUMAPAPU,NRSEQITMAPR,DSITEMMAPR,VRITEMMAPR,CDAJUSTEITMAPA,IDTIPOITMAPR,IDAJCIAP)
                VALUES
                (P_NRSEQUMAPAPU,LPAD(V_NRSEQITMAPR,10,'0'),NVL(V_DSAJUSTCIAPOC,'AJUSTE APUR CIAP'),V_TOTALCREDAPROP,V_CDAJUSTCIAPOC,'OC','S');
            END IF;
    END IF;
END;
/