CREATE OR REPLACE PROCEDURE COPIA_PRATO_CARDTRAB
(
   P_NRCARDAPIOTRAB IN NUMBER,
	P_NRCOMPCARDTRAB IN NUMBER,
	P_NRDIACARDTRABDEST IN NUMBER,
	P_NRCONFIGCARDTRABDEST IN NUMBER,
	P_NRORG IN NUMBER,
	P_CDOPERADOR IN VARCHAR2,
   P_SUBTITUIR IN VARCHAR2 DEFAULT 'S',
   P_COPIA_PRATO IN VARCHAR2 DEFAULT 'S',
   P_COMENSAIS IN FLOAT DEFAULT NULL
)
AS
	V_QTDE NUMBER;  
   V_NRDIACARDTRABORI NUMBER;
   V_NRCONFIGCARDTRABORI NUMBER;
   V_NRCOMPCARDTRABDEST NUMBER;
   V_CDFILAUXPRAT VARCHAR2(4);
   V_CDPRATO VARCHAR2(10);
   V_VRPECONSCARDTRAB FLOAT;
BEGIN
	-- Confere se e uma composicao valida e se ela pertence ao cardapio informado
	SELECT MAX(NRDIACARDTRAB), MAX(NRCONFIGCARDTRAB), 
	       MAX(CDFILAUXPRAT), MAX(CDPRATO), MAX(VRPECONSCARDTRAB)
     INTO V_NRDIACARDTRABORI, V_NRCONFIGCARDTRABORI,
          V_CDFILAUXPRAT, V_CDPRATO, V_VRPECONSCARDTRAB
     FROM COMPCARDTRAB
    WHERE NRCOMPCARDTRAB = P_NRCOMPCARDTRAB
      AND NRCARDAPIOTRAB = P_NRCARDAPIOTRAB;

   -- Se percentual informado ao chamar a procedure, utiliza o percentual informado
   V_VRPECONSCARDTRAB := NVL(P_COMENSAIS, V_VRPECONSCARDTRAB);

  	IF V_NRDIACARDTRABORI IS NOT NULL AND 
      V_NRCONFIGCARDTRABORI IS NOT NULL THEN
     	
      -- Busca a composicao para o dia e coluna de destino
   	SELECT MAX(NRCOMPCARDTRAB)
        INTO V_NRCOMPCARDTRABDEST
        FROM COMPCARDTRAB
       WHERE NRCARDAPIOTRAB = P_NRCARDAPIOTRAB
         AND NRDIACARDTRAB = P_NRDIACARDTRABDEST
         AND NRCONFIGCARDTRAB = P_NRCONFIGCARDTRABDEST;

      IF V_NRCOMPCARDTRABDEST IS NOT NULL THEN
         /*Se nao pode substituir sai da funcao*/
         IF P_SUBTITUIR = 'N' THEN
            RETURN;
         ELSE
            /*Atualiza o prato e comensais da composicao. O prato so atualiza se copia prato for S*/
            UPDATE COMPCARDTRAB
               SET CDFILAUXPRAT = CASE WHEN P_COPIA_PRATO = 'S' THEN V_CDFILAUXPRAT ELSE CDFILAUXPRAT END,
                   CDPRATO = CASE WHEN P_COPIA_PRATO = 'S' THEN V_CDPRATO ELSE CDPRATO END,
                   VRPECONSCARDTRAB = V_VRPECONSCARDTRAB,
                   NRORGULTATU = P_NRORG,
                   CDOPERULTATU = P_CDOPERADOR,
                   DTULTATU = SYSDATE
             WHERE NRCOMPCARDTRAB = V_NRCOMPCARDTRABDEST;
         END IF;
      ELSE      
         V_NRCOMPCARDTRABDEST := TO_NUMBER(RETORNA_NOVO_CODIGO('COMPCARDTRAB', 1));
         INSERT INTO COMPCARDTRAB
         (NRCOMPCARDTRAB,NRCARDAPIOTRAB,
			 NRDIACARDTRAB, NRCONFIGCARDTRAB,
			 CDFILAUXPRAT,CDPRATO,VRPECONSCARDTRAB,
			 NRORG, NRORGINCLUSAO, NRORGULTATU,
			 CDOPERINCLUSAO,CDOPERULTATU,
			 DTINCLUSAO, DTULTATU)         
         VALUES
         (V_NRCOMPCARDTRABDEST, P_NRCARDAPIOTRAB, 
          P_NRDIACARDTRABDEST, P_NRCONFIGCARDTRABDEST,
          V_CDFILAUXPRAT, V_CDPRATO, V_VRPECONSCARDTRAB,
          P_NRORG, P_NRORG, P_NRORG,
          P_CDOPERADOR, P_CDOPERADOR,
          SYSDATE, SYSDATE);
      END IF;
   END IF;
END;
/