CREATE OR REPLACE PROCEDURE GERA_GUIA_ICMS_ST(
   P_NRSEQUMAPAPU IN MAPAAPURAC.NRSEQUMAPAPU%TYPE,
   P_IDTIPOAPURA  IN MAPAAPURAC.IDBLOQMAPAPU%TYPE DEFAULT 'D')
AS
   V_VRIMPORECO             NUMBER;
   V_VRSALDCRED             NUMBER;
   V_NRSEQMAPAEST           NUMBER;
   V_SGESTADO               VARCHAR2(02);
   V_VRTOTADEBI             NUMBER;
   V_VRTOTACRED             NUMBER;
   V_CDEMPRESA              VARCHAR2(02);
   V_CDIMPOSTO              VARCHAR2(02);
   V_CDINSCESTA             VARCHAR2(16);
   V_IDGERAJUST             VARCHAR2(1);
   V_VRSAIDA                NUMBER; 
   V_VRSTNFENTR             NUMBER; 
   V_DIFF                   NUMBER;
   V_CDPAISIE               VARCHAR2(4);
   V_SGESTADOIE             VARCHAR2(2);
   V_CDAJUSTEE220VRREST     VARCHAR2(10); 
   V_DSAJUSTEE220VRREST     VARCHAR2(400); 
   V_CDAJUSTEE220VRCOMP     VARCHAR2(10);
   V_DSAJUSTEE220VRCOMP     VARCHAR2(400);
   V_NRSEQAJUSAPURSG        NUMBER;
   V_VRFECP                 NUMBER;
   V_TPAJUSTEFECP           VARCHAR2(3); 
   V_CDAJUSTEDDUE           VARCHAR2(10);
   V_DSAJUSTEDDUE           VARCHAR2(400);  
   V_CDAJUSTDEBESP          VARCHAR2(10); 
   V_DSAJUSTDEBESP          VARCHAR2(400);  
   V_CDAJUSTOUTDEB          VARCHAR2(10);  
   V_DSAJUSTOUTDEB          VARCHAR2(400);
   V_IDGERAREGC191          VARCHAR2(3);
   V_IDSOMAFECP             VARCHAR2(1);
   V_VRDEBESPFECP           NUMBER;
   V_VRDEDUZFECP            NUMBER;
   V_VROUTROSCREDITOS       NUMBER;
   V_VROUTROSDEBITOS        NUMBER;
BEGIN

   /******** Deleta os registros na tabela, devido a regeracao da guia ********/
   DELETE FROM MAPAAPURESTADO
    WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;

   V_VRIMPORECO := 0;
   V_VRSALDCRED := 0;
   V_SGESTADO   := '';
   V_VRTOTADEBI := 0;
   V_VRTOTACRED := 0;

   BEGIN
      SELECT M.CDEMPRESA, M.CDINSCESTA, M.CDIMPOSTO, I.CDPAIS, I.SGESTADO
        INTO V_CDEMPRESA, V_CDINSCESTA, V_CDIMPOSTO, V_CDPAISIE, V_SGESTADOIE
        FROM MAPAAPURAC M, INSCRESTAD I
       WHERE M.NRSEQUMAPAPU = P_NRSEQUMAPAPU
         AND M.CDEMPRESA = I.CDEMPRESA(+)
         AND M.CDINSCESTA = I.CDINSCESTA(+);
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDEMPRESA  := '';
         V_CDINSCESTA := '';
         V_CDIMPOSTO  := '';
         V_CDPAISIE   := '';
         V_SGESTADOIE := '';
   END;

   BEGIN 
      SELECT IDSOMAFECP, TPAJUSTEFECP, CDAJUSTEDDUE, DSAJUSTEDDUE, CDAJUSTDEBESP,
             DSAJUSTDEBESP, CDAJUSTOUTDEB, DSAJUSTOUTDEB, IDGERAREGC191
        INTO V_IDSOMAFECP, V_TPAJUSTEFECP, V_CDAJUSTEDDUE, V_DSAJUSTEDDUE, V_CDAJUSTDEBESP,
             V_DSAJUSTDEBESP, V_CDAJUSTOUTDEB, V_DSAJUSTOUTDEB, V_IDGERAREGC191
        FROM AJUSTEFECP
       WHERE CDEMPRESA    = V_CDEMPRESA
         AND CDINSCESTA   = V_CDINSCESTA
         AND CDIMPOSTO    = V_CDIMPOSTO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDSOMAFECP    := 'S';
         V_TPAJUSTEFECP  := 'DDE';
         V_CDAJUSTEDDUE  := '';
         V_DSAJUSTEDDUE  := '';
         V_CDAJUSTDEBESP := '';
         V_DSAJUSTDEBESP := '';
         V_CDAJUSTOUTDEB := '';
         V_DSAJUSTOUTDEB := '';
         V_IDGERAREGC191 := '';
   END;
        
   IF V_IDSOMAFECP IS NULL THEN
      V_IDSOMAFECP := 'S';
   END IF;

   DELETE FROM AJUSTMAPAAPURSG
    WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
      AND IDGERAUTO = 'FECP';

   DELETE FROM AJUSTMAPAAPURSG
    WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
      AND IDGERAUTO = 'CRST';   

   BEGIN
      SELECT MAX(NRSEQAJUSAPURSG)
        INTO V_NRSEQAJUSAPURSG
        FROM AJUSTMAPAAPURSG
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_NRSEQAJUSAPURSG := 0;
   END;

   /******** Busca os valores para geracao da Guia por Estado - Para o Mobile (P_IDTIPOAPURA = M) as informacoes sao
             quebradas por inscricao do substituto tributario tambem, no Delphi (P_IDTIPOAPURA = D) apenas por estado ********/
   FOR C_DADOS IN (SELECT REG.CDPAIS, REG.SGESTADO, DECODE(P_IDTIPOAPURA,'D','','M',REG.CDINSCESTAST) AS CDINSCESTAST,
                          SUM(DECODE(REG.IDENTRSAIDOP,'S',ROUND(VRCONTABILNF,2),0)) AS VRCTBLDEB,
                          SUM(DECODE(REG.IDENTRSAIDOP,'S',ROUND(VRBASECALC,2),0)) AS VRBASECALCDEB,
                          SUM(DECODE(REG.IDENTRSAIDOP,'E',ROUND(VRCONTABILNF,2),0)) AS VRCTBLCRED,
                          SUM(DECODE(REG.IDENTRSAIDOP,'E',ROUND(VRBASECALC,2),0)) AS VRBASECALCCRED,
                          SUM(DECODE(REG.IDENTRSAIDOP,'S',ROUND(VRIMPOSTONF,2),0)) AS VRDEBITO,
                          SUM(DECODE(REG.IDENTRSAIDOP,'S',ROUND(VRADICFECP,2),0)) AS VRADICFECP,
                          SUM(DECODE(E.IDREGIMEICMSST,'1',DECODE(REG.IDENTRSAIDOP,'E',ROUND(VRCREDITO,  2),0),0)) AS VRCREDITO,
                          SUM(DECODE(E.IDREGIMEICMSST,'1',DECODE(REG.IDENTRSAIDOP,'E',ROUND(VRDEVMAPA,  2),0),0)) AS VRDEVMAPA,
                          SUM(DECODE(E.IDREGIMEICMSST,'1',DECODE(REG.IDENTRSAIDOP,'E',ROUND(VRRESSAMAPA,2),0),0)) AS VRRESSAMAPA
                     FROM EMPRESA E,
                          (SELECT DECODE(NF.IDORIGDESTNF,'L',EL.CDPAIS,  'C',EC.CDPAIS,  'F',EF.CDPAIS)   AS CDPAIS,
                                  DECODE(NF.IDORIGDESTNF,'L',EL.SGESTADO,'C',EC.SGESTADO,'F',EF.SGESTADO) AS SGESTADO,
                                  NF.IDENTRSAIDOP, NF.CDEMPRESA, NF.CDINSCESTAST,  IP.VRCONTABILNF AS VRCONTABILNF,
                                  DECODE(IP.CDFISCALNF,'1',IP.VRBASECALCNF,0) AS VRBASECALC,
                                  CASE WHEN CDFISCOPERNF NOT IN ('1410','1411','1414','1415','1660','1661','1662','2410','2411','2414','2415','2660','2661','2662','1603','2603')
                                       THEN DECODE(IP.CDFISCALNF,'1',IP.VRIMPOSTONF + NVL(IP.VRADICFECP,0),0) ELSE 0 END AS VRCREDITO,
                                  CASE WHEN CDFISCOPERNF NOT IN ('1401','1406','1407','1410','1411','1414','1415','1660','1661','1662','2401','2406','2407','2410','2411','2414','2415','2660','2661','2662')
                                       THEN DECODE(IP.CDFISCALNF,'1',IP.VRIMPOSTONF+DECODE(V_IDSOMAFECP,'S',NVL(IP.VRADICFECP,0),0),0) ELSE 0 END AS VRIMPOSTONF,
                                  CASE WHEN CDFISCOPERNF IN ('1410','1411','1414','1415','1660','1661','1662','2410','2411','2414','2415','2660','2661','2662')
                                       THEN DECODE(IP.CDFISCALNF,'1',IP.VRIMPOSTONF + NVL(IP.VRADICFECP,0),0) ELSE 0 END AS VRDEVMAPA,
                                  CASE WHEN CDFISCOPERNF IN ('1603', '2603')
                                       THEN DECODE(IP.CDFISCALNF,'1',IP.VRIMPOSTONF + NVL(IP.VRADICFECP,0),0) ELSE 0 END AS VRRESSAMAPA,
                                  DECODE(IP.CDFISCALNF,'1',NVL(IP.VRADICFECP,0),0) AS VRADICFECP
                             FROM IMPOSTONF IP, NOTAFISCAL NF, ENDECLIE EC, ENDEFORN EF, ENDEFILI EL
                            WHERE IP.NRSEQUMAPAPU    = P_NRSEQUMAPAPU
                              AND NF.CDFILIAL        = IP.CDFILIAL
                              AND NF.NRLANCTONF      = IP.NRLANCTONF
                              AND EC.CDCLIENTE(+)    = NF.CDCLIENTE
                              AND EC.IDTPENDECLIE(+) = 'P'
                              AND EF.CDFORNECED(+)   = NF.CDFORNECED
                              AND EF.IDTPENDEFORN(+) = 'P'
                              AND EL.CDFILIAL(+)     = DECODE(NF.IDENTRSAIDOP,'E',NF.CDFILIEMIT,NF.CDFILIRECE)
                              AND EL.IDTPENDEFILI(+) = 'P') REG
                    WHERE E.CDEMPRESA    = REG.CDEMPRESA
                    GROUP BY REG.CDPAIS, REG.SGESTADO, DECODE(P_IDTIPOAPURA,'D','','M',REG.CDINSCESTAST)
                    ORDER BY REG.SGESTADO) LOOP

      V_VRTOTADEBI := NVL(C_DADOS.VRDEBITO,0);
      V_VRTOTACRED := NVL(C_DADOS.VRCREDITO,0) + NVL(C_DADOS.VRRESSAMAPA,0) + NVL(C_DADOS.VRDEVMAPA,0);

      V_VRIMPORECO := NVL(V_VRTOTADEBI,0) - NVL(V_VRTOTACRED,0);

      IF V_VRIMPORECO < 0 THEN
         V_VRSALDCRED := ABS(V_VRIMPORECO);
         V_VRIMPORECO := 0;
      ELSE
         V_VRSALDCRED := 0;
      END IF;

      IF NVL(V_SGESTADO,' ') <> C_DADOS.SGESTADO THEN
         V_NRSEQMAPAEST := 1;
      END IF;

      /******** Insere o item ********/
      INSERT INTO MAPAAPURESTADO
         (NRSEQUMAPAPU, NRSEQMAPAAPUREST, CDPAIS, SGESTADO, CDINSCESTAST, CDRECESUBTRIB, DTVENCSUBTRIB,
          VRCTBLDEB, VRBASECALCDEB, VRDEBITONORMAL, VROUTROSDEBITOS, VRTOTADEBI,
          VRCTBLCRED, VRBASECALCCRED, VRCREDITONORMAL, VRDEVMAPA, VRRESSAMAPA, VROUTROSCREDITOS, VRTOTACRED,
          VRCREDANTERIOR, VRIMPARECOLHER, VRSALDOCREDOR, VRFECP, VRSTNFSAID, VRSTNFENTR, VRSTNFCOMP, VRSTNFRESS)
      VALUES
         (P_NRSEQUMAPAPU, V_NRSEQMAPAEST, C_DADOS.CDPAIS, C_DADOS.SGESTADO, C_DADOS.CDINSCESTAST, '', '',
          C_DADOS.VRCTBLDEB, C_DADOS.VRBASECALCDEB, C_DADOS.VRDEBITO, 0, V_VRTOTADEBI,
          C_DADOS.VRCTBLCRED, C_DADOS.VRBASECALCCRED, C_DADOS.VRCREDITO, C_DADOS.VRDEVMAPA, C_DADOS.VRRESSAMAPA, 0, V_VRTOTACRED,
          0, V_VRIMPORECO, V_VRSALDCRED, C_DADOS.VRADICFECP, 0, 0, 0, 0);

      V_SGESTADO     := C_DADOS.SGESTADO;
      V_NRSEQMAPAEST := V_NRSEQMAPAEST + 1;

      IF (V_TPAJUSTEFECP = 'DDE') AND (C_DADOS.VRADICFECP > 0) THEN

         V_NRSEQAJUSAPURSG := NVL(V_NRSEQAJUSAPURSG,0) + 1;
         INSERT INTO AJUSTMAPAAPURSG
            (NRSEQUMAPAPU, CDPAIS, SGESTADO, NRSEQAJUSAPURSG, DSAJUSTEAPURSG, VRAJUSTEAPURSG, CDAJUSTEAPURSG, IDTPAJUSTEAPSG, IDGERAUTO, IDTPAJUSTE )
         VALUES
            (P_NRSEQUMAPAPU , C_DADOS.CDPAIS, C_DADOS.SGESTADO, V_NRSEQAJUSAPURSG, V_DSAJUSTEDDUE, C_DADOS.VRADICFECP, V_CDAJUSTEDDUE, 'C', 'FECP', 'DD');

         V_NRSEQAJUSAPURSG := NVL(V_NRSEQAJUSAPURSG,0) + 1;
         INSERT INTO AJUSTMAPAAPURSG
            (NRSEQUMAPAPU, CDPAIS, SGESTADO, NRSEQAJUSAPURSG, DSAJUSTEAPURSG, VRAJUSTEAPURSG, CDAJUSTEAPURSG, IDTPAJUSTEAPSG, IDGERAUTO, IDTPAJUSTE )
         VALUES
            (P_NRSEQUMAPAPU , C_DADOS.CDPAIS, C_DADOS.SGESTADO, V_NRSEQAJUSAPURSG, V_DSAJUSTDEBESP, C_DADOS.VRADICFECP, V_CDAJUSTDEBESP, 'D', 'FECP', 'DE');

      ELSIF (V_TPAJUSTEFECP = 'DE') AND (C_DADOS.VRADICFECP > 0) THEN

         V_NRSEQAJUSAPURSG := NVL(V_NRSEQAJUSAPURSG,0) + 1;
         INSERT INTO AJUSTMAPAAPURSG
            (NRSEQUMAPAPU, CDPAIS, SGESTADO, NRSEQAJUSAPURSG, DSAJUSTEAPURSG, VRAJUSTEAPURSG, CDAJUSTEAPURSG, IDTPAJUSTEAPSG, IDGERAUTO, IDTPAJUSTE )
         VALUES
            (P_NRSEQUMAPAPU , C_DADOS.CDPAIS, C_DADOS.SGESTADO, V_NRSEQAJUSAPURSG, V_DSAJUSTDEBESP, C_DADOS.VRADICFECP, V_CDAJUSTDEBESP, 'D', 'FECP', 'DE');

      ELSIF (V_TPAJUSTEFECP = 'OD') AND (C_DADOS.VRADICFECP > 0) THEN

         V_NRSEQAJUSAPURSG := NVL(V_NRSEQAJUSAPURSG,0) + 1;
         INSERT INTO AJUSTMAPAAPURSG
            (NRSEQUMAPAPU, CDPAIS, SGESTADO, NRSEQAJUSAPURSG, DSAJUSTEAPURSG, VRAJUSTEAPURSG, CDAJUSTEAPURSG, IDTPAJUSTEAPSG, IDGERAUTO, IDTPAJUSTE )
         VALUES
            (P_NRSEQUMAPAPU , C_DADOS.CDPAIS, C_DADOS.SGESTADO, V_NRSEQAJUSAPURSG, V_DSAJUSTOUTDEB, C_DADOS.VRADICFECP, V_CDAJUSTOUTDEB, 'D', 'FECP', 'OD' );
      END IF;

      /******** Atualiza a MAPAAPURESTADO com o valor dos ajustes  ********/
      BEGIN
         SELECT SUM(DECODE(IDTPAJUSTE,'DE',VRAJUSTEAPURSG,0)) AS VRDEBESPECIAL,
                SUM(DECODE(IDTPAJUSTE,'DD',VRAJUSTEAPURSG,0)) AS VRDEDUCAO,
                SUM(DECODE(NVL(IDTPAJUSTE,DECODE(IDTPAJUSTEAPSG,'C','OC','OD')),'OC',VRAJUSTEAPURSG,0)) AS VROUTROSCRED,
                SUM(DECODE(NVL(IDTPAJUSTE,DECODE(IDTPAJUSTEAPSG,'C','OC','OD')),'OD',VRAJUSTEAPURSG,0)) AS VROUTROSDEB
           INTO V_VRDEBESPFECP, V_VRDEDUZFECP, V_VROUTROSCREDITOS, V_VROUTROSDEBITOS
           FROM AJUSTMAPAAPURSG
          WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
            AND CDPAIS       = C_DADOS.CDPAIS
            AND SGESTADO     = C_DADOS.SGESTADO;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRDEBESPFECP := 0;
            V_VRDEDUZFECP  := 0;
            V_VROUTROSCREDITOS := 0;
            V_VROUTROSDEBITOS := 0;
      END;

      UPDATE MAPAAPURESTADO
         SET VRDEBESPFECP     = NVL(V_VRDEBESPFECP,0),
             VRDEDUZFECP      = NVL(V_VRDEDUZFECP,0),
             VROUTROSCREDITOS = NVL(V_VROUTROSCREDITOS,0),
             VROUTROSDEBITOS  = NVL(V_VROUTROSDEBITOS,0)
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
         AND CDPAIS       = C_DADOS.CDPAIS
         AND SGESTADO     = C_DADOS.SGESTADO;

   END LOOP;

   /******** Para os estados que o cliente possui inscricao do Substituto Tributario deve ser informada apuracao,
             mesmo que nao haja movimento ********/
   FOR C_INSCR IN (SELECT IE.CDPAIS, IE.SGESTADO, IE.CDINSCESTAST
                     FROM MAPAAPURAC MP, INSCRESTADST IE
                    WHERE MP.NRSEQUMAPAPU = P_NRSEQUMAPAPU
                      AND MP.CDEMPRESA    = IE.CDEMPRESA
                      AND MP.CDINSCESTA   = IE.CDINSCESTA
                      AND NOT EXISTS (SELECT CDPAIS, SGESTADO
                                           FROM MAPAAPURESTADO M
                                          WHERE M.CDPAIS       = IE.CDPAIS
                                            AND M.SGESTADO     = IE.SGESTADO
                                            AND M.NRSEQUMAPAPU = P_NRSEQUMAPAPU)) LOOP
      /******** Insere o item ********/
      INSERT INTO MAPAAPURESTADO
         (NRSEQUMAPAPU, NRSEQMAPAAPUREST, CDPAIS, SGESTADO, CDINSCESTAST, CDRECESUBTRIB, DTVENCSUBTRIB,
          VRCTBLDEB, VRBASECALCDEB, VRDEBITONORMAL, VROUTROSDEBITOS, VRTOTADEBI,
          VRCTBLCRED, VRBASECALCCRED, VRCREDITONORMAL, VRDEVMAPA, VRRESSAMAPA, VROUTROSCREDITOS, VRTOTACRED,
          VRCREDANTERIOR, VRIMPARECOLHER, VRSALDOCREDOR)
      VALUES
         (P_NRSEQUMAPAPU, 1, C_INSCR.CDPAIS, C_INSCR.SGESTADO, C_INSCR.CDINSCESTAST,
          '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
   END LOOP;

   /******** Para o estado da inscricao estadual do cliente deve ser informada apuracao, mesmo que nao haja movimento ********/
   FOR C_IE IN (SELECT IE.CDPAIS, IE.SGESTADO
                  FROM MAPAAPURAC MP, INSCRESTAD IE
                 WHERE MP.NRSEQUMAPAPU = P_NRSEQUMAPAPU
                   AND MP.CDEMPRESA    = IE.CDEMPRESA
                   AND MP.CDINSCESTA   = IE.CDINSCESTA
                   AND NOT EXISTS (SELECT M.CDPAIS, M.SGESTADO
                                     FROM MAPAAPURESTADO M
                                    WHERE M.CDPAIS       = IE.CDPAIS
                                      AND M.SGESTADO     = IE.SGESTADO
                                      AND M.NRSEQUMAPAPU = P_NRSEQUMAPAPU)) LOOP
      /******** Insere o item ********/
      INSERT INTO MAPAAPURESTADO
         (NRSEQUMAPAPU, NRSEQMAPAAPUREST, CDPAIS, SGESTADO, CDINSCESTAST, CDRECESUBTRIB, DTVENCSUBTRIB,
          VRCTBLDEB, VRBASECALCDEB, VRDEBITONORMAL, VROUTROSDEBITOS, VRTOTADEBI,
          VRCTBLCRED, VRBASECALCCRED, VRCREDITONORMAL, VRDEVMAPA, VRRESSAMAPA, VROUTROSCREDITOS, VRTOTACRED,
          VRCREDANTERIOR, VRIMPARECOLHER, VRSALDOCREDOR)
      VALUES
         (P_NRSEQUMAPAPU, 1, C_IE.CDPAIS, C_IE.SGESTADO, '',
          '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
   END LOOP;
    
   /******** Apura a diferenca do complemento/ressarcimento do ICMS ST ********/
   BEGIN
      SELECT IDGERAJUST, CDAJUSTEE220VRREST, DSAJUSTEE220VRREST, CDAJUSTEE220VRCOMP, DSAJUSTEE220VRCOMP
        INTO V_IDGERAJUST, V_CDAJUSTEE220VRREST, V_DSAJUSTEE220VRREST, V_CDAJUSTEE220VRCOMP, V_DSAJUSTEE220VRCOMP
        FROM PARAMESTSPED
       WHERE CDEMPRESA  = V_CDEMPRESA
         AND CDINSCESTA = V_CDINSCESTA;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDGERAJUST         := 'N';
         V_CDAJUSTEE220VRREST := '';
         V_DSAJUSTEE220VRREST := '';
         V_CDAJUSTEE220VRCOMP := '';
         V_DSAJUSTEE220VRCOMP := '';
   END;

   IF V_IDGERAJUST = 'S' THEN
      APURA_DIFERENCA_ICMS_ST( P_NRSEQUMAPAPU );
   END IF;

   BEGIN
      SELECT NVL(SUM(VRSAIDA),0) AS VRSAIDA,
             NVL(SUM(VRSTNFENTR),0) AS VRSTNFENTR
        INTO V_VRSAIDA, V_VRSTNFENTR
        FROM CONF_AJUSTE_ST_RS
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRSAIDA    := 0;
         V_VRSTNFENTR := 0;
   END;

   V_DIFF := NVL(V_VRSAIDA,0) - NVL(V_VRSTNFENTR,0);

   IF V_DIFF > 0 THEN
      UPDATE MAPAAPURESTADO
         SET VRSTNFSAID = V_VRSAIDA,
             VRSTNFENTR = V_VRSTNFENTR,
             VRSTNFCOMP = V_DIFF,
             VRSTNFRESS = 0
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
         AND CDPAIS       = V_CDPAISIE
         AND SGESTADO     = V_SGESTADOIE;

      V_NRSEQAJUSAPURSG := NVL(V_NRSEQAJUSAPURSG,0) + 1;
      INSERT INTO AJUSTMAPAAPURSG
         (NRSEQUMAPAPU, CDPAIS, SGESTADO, NRSEQAJUSAPURSG, DSAJUSTEAPURSG, VRAJUSTEAPURSG, CDAJUSTEAPURSG, IDTPAJUSTEAPSG, IDGERAUTO, IDTPAJUSTE)
      VALUES
         (P_NRSEQUMAPAPU , V_CDPAISIE, V_SGESTADOIE, V_NRSEQAJUSAPURSG, V_DSAJUSTEE220VRCOMP, V_DIFF, V_CDAJUSTEE220VRCOMP, 'D', 'CRST', 'OD');
   ELSIF ABS(V_DIFF) > 0 THEN
      UPDATE MAPAAPURESTADO
         SET VRSTNFSAID = V_VRSAIDA,
             VRSTNFENTR = V_VRSTNFENTR,
             VRSTNFCOMP = 0,
             VRSTNFRESS = ABS(V_DIFF)
       WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU
         AND CDPAIS       = V_CDPAISIE
         AND SGESTADO     = V_SGESTADOIE;

      V_NRSEQAJUSAPURSG := NVL(V_NRSEQAJUSAPURSG,0) + 1;
      INSERT INTO AJUSTMAPAAPURSG
         (NRSEQUMAPAPU, CDPAIS, SGESTADO, NRSEQAJUSAPURSG, DSAJUSTEAPURSG, VRAJUSTEAPURSG, CDAJUSTEAPURSG, IDTPAJUSTEAPSG, IDGERAUTO, IDTPAJUSTE)
      VALUES
         (P_NRSEQUMAPAPU , V_CDPAISIE, V_SGESTADOIE, V_NRSEQAJUSAPURSG, V_DSAJUSTEE220VRREST, V_DIFF, V_CDAJUSTEE220VRREST, 'C', 'CRST', 'OC');
   END IF;

   /******** Apaga o detalhamento por UF dos Estados que deixaram de existir apos uma nova apuracao do Mapa ********/
   DELETE FROM DETAUFMAPAEST
    WHERE NOT NRSEQUMAPAPU||CDPAIS||SGESTADO IN (SELECT NRSEQUMAPAPU||CDPAIS||SGESTADO
                                                   FROM MAPAAPURESTADO
                                                  WHERE NRSEQUMAPAPU = P_NRSEQUMAPAPU)
      AND NRSEQUMAPAPU = P_NRSEQUMAPAPU;
END;
/