create or replace FUNCTION PRATO_NOMEFANT(
   P_CDFILIAL IN VARCHAR2,
   P_CDSERVFILI IN VARCHAR2,
   P_CDPRATO IN VARCHAR2,
   P_CDFILAUXPRAT IN VARCHAR2,
   P_CDFILCENTPME IN FILIAL.CDFILIAL%TYPE DEFAULT NULL,
   P_CDTIPOCARD   IN TIPOCARD.CDTIPOCARD%TYPE DEFAULT NULL) RETURN VARCHAR2 IS
   V_NOME VARCHAR2(80);
   V_RECEITA VARCHAR2(1);
BEGIN
   V_NOME := NULL;
   V_RECEITA := RECEITA_UTILIZADA(P_CDPRATO, P_CDFILAUXPRAT, P_CDFILIAL, P_CDSERVFILI, P_CDFILCENTPME, P_CDTIPOCARD);
   IF V_RECEITA = 'S' THEN 
      SELECT NMFANTASIASE INTO V_NOME
      FROM PRATSERV 
      WHERE CDFILIAL = P_CDFILIAL 
        AND CDSERVFILI = P_CDSERVFILI 
        AND CDPRATO = P_CDPRATO 
        AND CDFILAUXPRAT = P_CDFILAUXPRAT;
        
   END IF;

   IF V_RECEITA = 'F' THEN 
      SELECT NMFANTASIAPF INTO V_NOME
      FROM PRATFILI 
      WHERE CDFILIAL = P_CDFILIAL 
        AND CDFILAUXPRAT = P_CDFILAUXPRAT
        AND CDPRATO = P_CDPRATO;
   END IF;

   IF V_RECEITA = 'T' THEN 
      SELECT NMFANTASIAPRTP INTO V_NOME
      FROM PRATTPCARD
      WHERE CDFILCENTPME = P_CDFILCENTPME 
        AND CDTIPOCARD = P_CDTIPOCARD 
        AND CDFILAUXPRAT = P_CDFILAUXPRAT
        AND CDPRATO = P_CDPRATO;   
   END IF;

   IF V_RECEITA = 'P' THEN 
      SELECT NMFANTASIAPR INTO V_NOME
      FROM PRATPADR
      WHERE CDFILAUXPRAT = P_CDFILAUXPRAT
        AND CDPRATO = P_CDPRATO;   
   END IF;
   
   IF V_NOME IS NULL THEN
      SELECT NMPRATO INTO V_NOME
      FROM PRATO
      WHERE CDFILAUXPRAT = P_CDFILAUXPRAT
        AND CDPRATO = P_CDPRATO;
   END IF; 
   
   RETURN(V_NOME);
END;
/
