CREATE OR REPLACE PROCEDURE IMPOSTO_ENTRADA_PRODUTO(
   P_EMPRESA      IN ALIQUOTA.CDEMPRESA%TYPE,                    --EMPRESA
   P_INSCESTA     IN ALIQUOTA.CDINSCESTA%TYPE,                   --INSCRICAO ESTADUAL
   P_TIPOOPER     IN INCIDENCIA.CDTIPOOPER%TYPE,                 --TIPO DE OPERACAO
   P_CDFORNECED   IN FORNECEDOR.CDFORNECED%TYPE,                 --CODIGO FORNECEDOR
   P_FILIAL       IN NOTAFISCAL.CDFILIAL%TYPE,                   --FILIAL
   P_LANCTONF     IN NOTAFISCAL.NRLANCTONF%TYPE,                 --N LANCAMENTO
   P_INIVALID     IN ALIQUOTA.DTINIVALID%TYPE,                   --DATA DE INICIO DE VALIDADDE
   P_ENTRSAID     IN NOTAFISCAL.IDENTRSAIDOP%TYPE DEFAULT 'E',   --PARAMETRO P/ IMPORTACAO DE NOTAS DE SAIDA
   P_CDOPERADOR   IN LANCTOESTOQ.CDOPERADOR%TYPE  DEFAULT NULL,
   P_CDGRUPOFISC  IN VARCHAR2,
   P_IDINTEREST   IN VARCHAR2,
   P_CDARVPROD    IN VARCHAR2,
   P_CDGRPFISCSV  IN VARCHAR2,
   P_IDORIGDESTNF IN VARCHAR2,
   P_CDFILIRECE   IN VARCHAR2,
   P_CDFILIEMIT   IN VARCHAR2,
   P_CDCLIENTE    IN VARCHAR2,
   P_VRPRODUTO    IN NUMBER,
   P_IDORIGEMPROD IN VARCHAR2 DEFAULT 'N',
   P_SGESTADO     IN VARCHAR2 DEFAULT NULL,
   P_CDMUNICIPIO  IN VARCHAR2 DEFAULT NULL)

IS
   V_IDOPERDEVONF CHAR(1);
   V_IDORIGDESTNF CHAR(1);
   V_DEVOLORIG    VARCHAR2(10);
   V_EXISTE       NUMBER;
   V_PAISORIG     VARCHAR2(04);
   V_ESTAORIG     VARCHAR2(02);
   V_MUNIORIG     VARCHAR2(04);
   V_PAISDEST     VARCHAR2(04);
   V_ESTADEST     VARCHAR2(02);
   V_MUNIDEST     VARCHAR2(04);
   V_ALIQTEMP     VARCHAR2(25);
   V_INCITEMP     VARCHAR2(25);
   V_CDORIGDESTNF VARCHAR2(25);
   V_VRALIQUTMP    FLOAT;
   V_VRADICALIQFECP FLOAT;
   V_IDNFPRESTSERV VARCHAR2(01);
   V_IDEMISFILNFSERV VARCHAR2(01);
   V_IDUTLOCPRESTSERV VARCHAR2(01);

   V_IDENDEMIS      VARCHAR2(01);
   V_CDEMPRESA      VARCHAR2(02);
   V_CDINSCESTA     VARCHAR2(16);

   V_IDENTEMIS      VARCHAR2(01);
BEGIN
   /*VARIAVEIS COM A CHAVE PARA AS TABELAS TEMPORARIAS*/
   V_ALIQTEMP     := P_FILIAL||P_LANCTONF;
   V_INCITEMP     := P_FILIAL||P_LANCTONF;
   V_IDORIGDESTNF := P_IDORIGDESTNF;

   /*CASO TENHA REGISTRO NA TABELA TEMPORARIA, OS REGISTROS SAO EXCLUIDOS*/
   SELECT COUNT(*)
     INTO V_EXISTE
     FROM INCITEMP
    WHERE NRINCITEMP = P_FILIAL||P_LANCTONF;

   IF V_EXISTE > 0 THEN
      DELETE FROM INCITEMP
       WHERE NRINCITEMP = P_FILIAL||P_LANCTONF;
   END IF;

   /*VARIAVEIS PARA CONSULTA DE ALIQUOTA, INCIDENCIA */
   BEGIN
      SELECT CDPAIS,     SGESTADO,   CDMUNICIPIO
      INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
      FROM INSCRESTAD
      WHERE (CDEMPRESA  = P_EMPRESA) AND
            (CDINSCESTA = P_INSCESTA);
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_PAISDEST := NULL; V_ESTADEST := NULL; V_MUNIDEST := NULL;
   END;

   Begin
      SELECT NVL(MAX(IDNFPRESTSERV), 'N'), NVL(MAX(IDUTLOCPRESTSERV), 'N')
        INTO   V_IDNFPRESTSERV, V_IDUTLOCPRESTSERV
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = 'E'
         AND CDTIPOOPER   = P_TIPOOPER;
   Exception
      When No_Data_Found Then
         V_IDNFPRESTSERV := 'N'; V_IDUTLOCPRESTSERV := 'N';
   End;

   IF V_IDNFPRESTSERV = 'S' THEN
      BEGIN
         SELECT NVL(MAX(IDEMISFILNFSERV),'P')
           INTO V_IDEMISFILNFSERV
           FROM FILIAL
          WHERE (CDFILIAL = P_CDFILIRECE);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDEMISFILNFSERV := 'P';
      END;

      IF (V_IDEMISFILNFSERV <> 'I') THEN
         BEGIN
            SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
              INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
              FROM ENDEFILI
             WHERE (CDFILIAL     = P_CDFILIRECE) AND
                   (IDTPENDEFILI = V_IDEMISFILNFSERV);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISDEST := NULL; V_ESTADEST := NULL; V_MUNIDEST := NULL;
         END;
      END IF;
   END IF;

   IF (V_IDNFPRESTSERV = 'S') AND (V_IDUTLOCPRESTSERV = 'S') THEN
      V_ESTADEST := NVL(P_SGESTADO, V_ESTADEST);
      V_MUNIDEST := NVL(P_CDMUNICIPIO, V_MUNIDEST);
   END IF;

   V_CDORIGDESTNF := P_CDFORNECED;

   /*SE O IDENTIFICADOR DE ORIGEM DO LANCAMENTO FOR IGUAL A FILIAL*/
   IF V_IDORIGDESTNF = 'L' THEN
      V_CDORIGDESTNF := P_CDFILIEMIT;

      Begin
         SELECT NVL(MAX(IDENDEMISFIL),'I'), MAX(CDEMPRESA)  , MAX(CDINSCESTA)
         INTO   V_IDENDEMIS          , V_CDEMPRESA, V_CDINSCESTA
         FROM FILIAL
         WHERE (CDFILIAL = P_CDFILIEMIT);
      Exception
         When No_Data_Found Then
            V_IDENDEMIS := 'I'; V_CDEMPRESA := Null; V_CDINSCESTA := Null;
      End;

      IF V_IDENDEMIS = 'I' THEN
         Begin
            SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM INSCRESTAD
            WHERE CDEMPRESA  = V_CDEMPRESA AND
                  CDINSCESTA = V_CDINSCESTA;
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      ELSE
         Begin
            SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFILI
            WHERE CDFILIAL     = P_CDFILIEMIT AND
                  IDTPENDEFILI = V_IDENDEMIS;
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      END IF;

   /*SE O IDENTIFICADOR DE ORIGEM DO LANCAMENTO FOR IGUAL A CLIENTE*/
   ELSIF V_IDORIGDESTNF = 'C' THEN
      BEGIN
        SELECT CDPAIS, SGESTADO, CDMUNICIPIO
          INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
          FROM ENDECLIE
         WHERE (CDCLIENTE    = P_CDCLIENTE) AND
               (IDTPENDECLIE = 'P');
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
      END;
   /*SE O IDENTIFICADOR DE ORIGEM DO LANCAMENTO FOR IGUAL A FORNECEDOR*/
   ELSIF V_IDORIGDESTNF = 'F' THEN
      BEGIN
         SELECT CDPAIS, SGESTADO, CDMUNICIPIO
           INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
           FROM ENDEFORN
          WHERE (CDFORNECED   = P_CDFORNECED) AND
                (IDTPENDEFORN = 'P');
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
       END;
   ELSE
      /*SE O IDENTIFICADOR DE ORIGEM DO LANCAMENTO FOR IGUAL A LICENCA DE USO OU OUTRO VALOR DIFERENTE DE L,C,F */
      BEGIN
         SELECT CDPAIS, SGESTADO, CDMUNICIPIO
         INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
         FROM ENDEFORN
         WHERE (CDFORNECED   = P_CDFORNECED) AND
               (IDTPENDEFORN = 'P');
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
      END;
   END IF;

   IF(NOT P_TIPOOPER IN ('07','09','10'))  THEN

      CONSULTA_INCIDENCIA(P_ENTRSAID, P_EMPRESA, P_CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, P_CDGRUPOFISC, P_CDGRPFISCSV, P_IDINTEREST, '', P_CDFILIRECE, P_CDFORNECED, P_CDCLIENTE, P_INIVALID, P_CDFILIEMIT, P_VRPRODUTO, 'S', P_IDORIGEMPROD, P_SGESTADO, P_CDMUNICIPIO);

      FOR C_INCIDENCIA IN (SELECT IT.CDIMPOTEMP, MAX(IT.CDFISCTEMP) AS CDFISCTEMP,
                                  MAX(IT.IDTRATIMPTMP) AS IDTRATIMPTMP, MAX(IP.IDCONSISTENT) AS IDCONSISTENT,
                                  MAX(NVL(IP.IDUTMUNIORIG, 'N')) AS IDUTMUNIORIG, MAX(IP.IDIMPORECUP) AS IDIMPORECUP,
                                  MAX(NVL(IP.IDPREIMPENTR, 'N')) AS IDPREIMPENTR,MAX(IP.IDORGARRECAD) AS IDORGARRECAD,
                                  MAX(IDUTVLRQTDEIMPO) AS IDUTVLRQTDEIMPO
                             FROM INCITEMP IT, IMPOSTO IP
                             WHERE (IT.NRINCITEMP = V_INCITEMP)    AND
                                   (IP.CDIMPOSTO  = IT.CDIMPOTEMP) AND
                                   (IP.IDPRODNOTA = 'P')
                             GROUP BY IT.CDIMPOTEMP
                             ORDER BY IT.CDIMPOTEMP) LOOP

         /* CONSIDERA O MUNICIPIO DE DESTINO */


         IF C_INCIDENCIA.IDUTMUNIORIG = 'D' THEN
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, P_CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, P_VRPRODUTO, P_INIVALID, P_FILIAL,
                                       P_LANCTONF, P_CDGRUPOFISC, P_TIPOOPER, '', 'S', P_VRPRODUTO,
                                       P_CDFILIRECE, P_CDFORNECED, P_CDCLIENTE, P_IDORIGEMPROD);

         ELSE
            CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, P_CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, P_VRPRODUTO, P_INIVALID, P_FILIAL,
                                       P_LANCTONF, P_CDGRUPOFISC, P_TIPOOPER, '', 'S', P_VRPRODUTO,
                                       P_CDFILIRECE, P_CDFORNECED, P_CDCLIENTE, P_IDORIGEMPROD);

         END IF;

         V_VRALIQUTMP := 0;

         /*CASO TENHA REGISTRO NA TABELA TEMPORARIA, OS REGISTROS SAO EXCLUIDOS*/
         DELETE
           FROM ALIQTEMPPROD
          WHERE NRALIQTEMP = V_ALIQTEMP
            AND CDIMPOTEMP = C_INCIDENCIA.CDIMPOTEMP;

         SELECT NVL(MAX(VRALIQUTMP), 0), NVL(MAX(VRADICALIQFECP), 0)
           INTO V_VRALIQUTMP, V_VRADICALIQFECP
           FROM ALIQTEMP
          WHERE NRALIQTEMP = V_ALIQTEMP;
          
         INSERT
           INTO ALIQTEMPPROD
                (NRALIQTEMP, CDIMPOTEMP, VRALIQUTMP, VRADICALIQFECP)
         VALUES (V_ALIQTEMP, C_INCIDENCIA.CDIMPOTEMP, V_VRALIQUTMP, V_VRADICALIQFECP);

         /*CASO TENHA REGISTRO NA TABELA TEMPORARIA, OS REGISTROS SAO EXCLUIDOS*/
         SELECT COUNT(*)
           INTO V_EXISTE
           FROM ALIQTEMP
          WHERE NRALIQTEMP = P_FILIAL||P_LANCTONF;

         IF V_EXISTE > 0 THEN
            DELETE
              FROM ALIQTEMP
             WHERE NRALIQTEMP = P_FILIAL||P_LANCTONF;
         END IF; 
      END LOOP;
   END IF;
END;
/