CREATE OR REPLACE PROCEDURE REINF_R4099(
    P_CDEMPRESA      IN EMPRESA.CDEMPRESA%TYPE,
    P_NRENVIO        IN NUMBER,
    P_NREVENTO       IN NUMBER,
    P_IDAMBIENTE     IN VARCHAR2,
    P_DTMESCOMPETENC IN ENVIOEVENTOREINF.DTMESCOMPETENC%TYPE,
    P_IDFECHRET      IN  VARCHAR2)
AS
   V_NRSEQREINF      NUMBER;
   V_DTCOMPSEMMOVTO  VARCHAR2(7);
   V_COUNT           NUMBER;
BEGIN
   
   FOR C_4099 IN (SELECT TO_CHAR(TO_DATE(P_DTMESCOMPETENC),'YYYY-MM')                               AS PERAPUR,
                         P_IDAMBIENTE                                                               AS TMPAMB,
                         '1'                                                                        AS PROCEMI,
                         '2.1.2'                                                                    AS VERPROC,
                         DECODE(E.IDTPIJUREMPR,'J','1','F','2',' ')                                 AS TPINSC,
                         DECODE(E.IDTPIJUREMPR,'J',SUBSTR(E.NRINSJUREMPR,1,8), 'F', E.NRINSJUREMPR) AS NRINSC,
                         R.NMREPRES                                                                 AS NMRESP,
                         R.NRCPFREPRES                                                              AS CPFRESP,
                         REPLACE(REPLACE(REPLACE(REPLACE(R.NRDDDTELEREPRES1||R.NRTELEREPRES1,'-'),')'),'('),' ') AS TELEFONE,
                         R.DSEMAILREPRES                                                            AS EMAIL,
                         P_IDFECHRET                                                                AS FECHRET
                    FROM PARAMEMPREINF P,
                         EMPRESA E,
                         REPRESLEGAL R
                   WHERE E.CDEMPRESA = P.CDEMPRESA
                     AND P.CDEMPRESA = P_CDEMPRESA
                     AND P.CDREPRES  = R.CDREPRES ) LOOP

       NOVO_CODIGO_NT('NRSEQREINF', V_NRSEQREINF);

       INSERT INTO ARQEFD_REINF
          (CDEMPRESA, NREVENTO, NRENVIO, CDCAMPO1, CDCAMPO2,
           CDCAMPO3, CDCAMPO4, CDCAMPO5, CDCAMPO6, CDCAMPO7,
           CDCAMPO8, CDCAMPO9, CDCAMPO10, CDCAMPO11, NRSEQREINF)
       VALUES
          (P_CDEMPRESA, P_NREVENTO, P_NRENVIO, C_4099.PERAPUR, C_4099.TMPAMB,
           C_4099.PROCEMI , C_4099.VERPROC, C_4099.TPINSC, C_4099.NRINSC, C_4099.NMRESP,
           C_4099.CPFRESP, C_4099.TELEFONE, C_4099.EMAIL, C_4099.FECHRET, V_NRSEQREINF);
   END LOOP;
END;
/