create or replace PROCEDURE COPIA_ITEMFAT_EQUIP_VIGENCIA (
    P_CDFILIAL IN VARCHAR2,
    P_CDCIA IN VARCHAR2,
    P_CDEQUIPORI IN VARCHAR2,
    P_NRSEQPADEQUIPMDATAORI IN NUMBER,
    P_CDEQUIPDES IN VARCHAR2,
    P_DTINIVIGENCIA IN DATE, 
    P_CDOPERADOR IN VARCHAR2,
    P_NRORG IN NUMBER
)
AS
  
  V_NRSEQPADEQUIPMDATA NUMBER;

BEGIN

   V_NRSEQPADEQUIPMDATA := NULL;
    
   FOR CUR_EQUIP IN (SELECT CDEQUIP
                          FROM EQUIPCIA
                          WHERE CDFILIAL = P_CDFILIAL
                          AND CDCIA      = P_CDCIA
                          AND VERIF_VALOR_LISTA(CDEQUIP, P_CDEQUIPDES) IS NOT NULL
   ) LOOP 
        
        
    /* Sequencial de vigencia para a data*/
    SELECT MAX(NRSEQPADEQUIPMDATA)
     INTO V_NRSEQPADEQUIPMDATA 
    FROM PADEQUIPMDATA
       WHERE CDFILIAL = P_CDFILIAL AND CDCIA = P_CDCIA
         AND CDEQUIP = CUR_EQUIP.CDEQUIP
         AND DTINIVIGENCIA = P_DTINIVIGENCIA;

    IF (CUR_EQUIP.CDEQUIP = P_CDEQUIPORI AND
        V_NRSEQPADEQUIPMDATA = P_NRSEQPADEQUIPMDATAORI) THEN
       CONTINUE;
    END IF;

    IF V_NRSEQPADEQUIPMDATA IS NULL
    THEN 
    /* Cria sequencial para a nova vigencia */ 
    NOVO_CODIGO('PADEQUIPMDATA', V_NRSEQPADEQUIPMDATA,1, P_NRORG);
    /* Insere a nova configuracao para o Voo */
    INSERT INTO PADEQUIPMDATA
      (CDFILIAL, CDCIA, CDEQUIP,
        NRSEQPADEQUIPMDATA, DTINIVIGENCIA,
        NRORG, NRORGULTATU, NRORGINCLUSAO,
        DTINCLUSAO, DTULTATU,
        CDOPERINCLUSAO, CDOPERULTATU, IDATIVO)
      VALUES (P_CDFILIAL, P_CDCIA, CUR_EQUIP.CDEQUIP, 
              V_NRSEQPADEQUIPMDATA, P_DTINIVIGENCIA, P_NRORG,
              P_NRORG, P_NRORG, SYSDATE, SYSDATE, P_CDOPERADOR, P_CDOPERADOR, 'S');
    ELSE 
    /*Deleta a configuracao do Voo*/      
    DELETE FROM PADEQUIPM
    WHERE CDFILIAL = P_CDFILIAL
      AND CDCIA = P_CDCIA
      AND CDEQUIP = CUR_EQUIP.CDEQUIP
      AND NRSEQPADEQUIPMDATA = V_NRSEQPADEQUIPMDATA;
    END IF;

    INSERT INTO PADEQUIPM
     (CDFILIAL, CDCIA, NRSERVICOCIAFILI,
      CDCLASSE, CDCICLO, CDEQUIP, 
      QTSERVOO, CDSERVICO, CDARVSERV,
      NRORG, NRORGULTATU, NRORGINCLUSAO,
      DTINCLUSAO, DTULTATU,
      CDOPERINCLUSAO, CDOPERULTATU, IDATIVO, NRSEQPADEQUIPMDATA)
     SELECT P_CDFILIAL, P_CDCIA, NRSERVICOCIAFILI,
            CDCLASSE, CDCICLO, CUR_EQUIP.CDEQUIP, 
            QTSERVOO, CDSERVICO, CDARVSERV,
          NRORG, NRORGULTATU, NRORGINCLUSAO,
          DTINCLUSAO, DTULTATU,
          CDOPERINCLUSAO, CDOPERULTATU, IDATIVO, V_NRSEQPADEQUIPMDATA
       FROM PADEQUIPM
      WHERE CDFILIAL = P_CDFILIAL
        AND CDCIA = P_CDCIA
        AND CDEQUIP = P_CDEQUIPORI
        AND NRSEQPADEQUIPMDATA = P_NRSEQPADEQUIPMDATAORI;

    V_NRSEQPADEQUIPMDATA := NULL;        
        
  END LOOP; 
END;
/