create or replace FUNCTION BUSCA_BASE_COMISSAO_FECP(
   P_CDFILIAL     IN ITEMPRODUTO.CDFILIAL%TYPE,
   P_NRLANCTONF   IN ITEMPRODUTO.NRLANCTONF%TYPE,
   P_NRSEQITPROD  IN ITEMPRODUTO.NRSEQITPROD%TYPE) RETURN NUMBER IS

   V_VRPRODUTO     NUMBER;
   V_VRICMSST      NUMBER;
   V_CDFILIEMIT    VARCHAR2(04);
   V_IDICMSCOMISS  VARCHAR2(01);
   V_RESULT        NUMBER;
BEGIN
   SELECT SUM(IT.VRTOTAITEM - IT.VRDESCITEM)
     INTO V_VRPRODUTO
     FROM ITEMPRODUTO IT
    WHERE IT.CDFILIAL = P_CDFILIAL
      AND IT.NRLANCTONF = P_NRLANCTONF
      AND IT.NRSEQITPROD = P_NRSEQITPROD;
     
   SELECT NVL(SUM(IP.VRIMPOSTOIT), 0)+NVL(SUM(IP.VRADICFECP), 0)
     INTO V_VRICMSST
     FROM ITEMPROIMPOS IP, IMPOSTO I, IMPOSTONFE INFE
    WHERE IP.CDFILIAL = P_CDFILIAL
      AND IP.NRLANCTONF = P_NRLANCTONF
      AND IP.NRSEQITPROD = P_NRSEQITPROD
      AND IP.CDFISCALIT = '1'
      AND IP.CDIMPOSTO = I.CDIMPOSTO
      AND I.CDIMPOSTONFE = INFE.CDIMPOSTONFE
      AND INFE.CDIMPOSTONFE = '80';
   
   SELECT MAX(N.CDFILIEMIT)
     INTO V_CDFILIEMIT
     FROM NOTAFISCAL N
    WHERE N.CDFILIAL = P_CDFILIAL
      AND N.NRLANCTONF = P_NRLANCTONF;
      
   SELECT NVL(MAX(IDICMSCOMISS), 'N')
     INTO V_IDICMSCOMISS
     FROM PAREXPEDICAO
    WHERE CDFILIAL = V_CDFILIEMIT;
    
   IF V_IDICMSCOMISS = 'S' THEN
      V_RESULT := V_VRPRODUTO + V_VRICMSST;
   ELSE 
      V_RESULT := V_VRPRODUTO;
   END IF;   
   RETURN(V_RESULT);     
   
END;
/