CREATE OR REPLACE PROCEDURE RDS.sp_CreateDispDirectList(
    OUT cnt INTEGER)
    LANGUAGE plpgsql
AS
$$
BEGIN

    DELETE
    FROM RDS.T_DISP_DIRECT_INFO info
    WHERE
        EXISTS (SELECT
                    1
                FROM RDS.T_DISP_DIRECT dd
                WHERE
                      dd.DispDirectID = info.DispDirect
                  AND dd.Year = DATE_PART(year, CURRENT_TIMESTAMP));

    DELETE
    FROM RDS.T_DISP_DIRECT_INTERVIEW inter
    WHERE
        EXISTS (SELECT
                    1
                FROM RDS.T_DISP_DIRECT dd
                WHERE
                      dd.DispDirectID = inter.DispDirect
                  AND dd.Year = DATE_PART(year, CURRENT_TIMESTAMP));

    DELETE
    FROM RDS.T_DISP_DIRECT_STATUS stat
    WHERE
        EXISTS (SELECT
                    1
                FROM RDS.T_DISP_DIRECT dd
                WHERE
                      dd.DispDirectID = stat.DispDirect
                  AND dd.Year = DATE_PART(year, CURRENT_TIMESTAMP));


    SELECT COUNT(*) INTO cnt FROM RDS.T_DISP_DIRECT;

    INSERT INTO
        RDS.T_DISP_DIRECT (DispDirectID,
                           ID_PAC,
                           FAM,
                           IM,
                           OT,
                           W,
                           DR,
                           VPOLIS,
                           SPOLIS,
                           NPOLIS,
                           DOCTYPE,
                           DOCSER,
                           DOCNUM,
                           COMENTP,
                           MR,
                           YEAR,
                           CODE_SMO,
                           CODE_MO,
                           SNILS_P,
                           SNILS_D)
    SELECT
        gen_random_uuid(),
        p.PatientID,
        p.LastName,
        p.FirstName,
        p.FatherName,
        p.Sex,
        p.Birthday,
        p.PolicyForm,
        p.PolisSerial,
        p.PolisNumber,
        p.DocType,
        p.DocSeries,
        p.DocNumber,
        NULL,
        NULL,
        DATE_PART('year', CURRENT_TIMESTAMP),
        p.F002Smo,
        p.LpuMain,
        p.SNILS,
        p.SNILS_D
    FROM RDS.T_PATIENT p
    WHERE
          (DATE_PART('year', CURRENT_DATE) - DATE_PART('year', p.Birthday))::INTEGER % 3 = 0
      AND (DATE_PART('year', CURRENT_DATE) - DATE_PART('year', p.Birthday)) >= 21
      AND (DATE_PART('year', CURRENT_DATE) - DATE_PART('year', p.Birthday)) <= 99;

    SELECT
        COUNT(*) - cnt
    INTO cnt
    FROM RDS.T_DISP_DIRECT;
END;
$$