CREATE OR REPLACE PROCEDURE public.sp_rr_patients(
	"Xml" text DEFAULT NULL::text,
	"ID" uuid DEFAULT NULL::uuid,
	"QueueName" character varying DEFAULT 'RDSSync'::character varying,
	datetime timestamp without time zone DEFAULT NULL::timestamp without time zone,
	"User" uuid DEFAULT NULL::uuid
)
LANGUAGE plpgsql
AS
$$
DECLARE
    p_xml             xml          := "Xml" :: xml;
    p_queuename       varchar(100) := "QueueName";
    p_datetime        timestamp    := COALESCE(datetime, CURRENT_TIMESTAMP);
    p_user            uuid         := "User";
    p_id              uuid         := "ID";
    v_result          text;
    v_operationtype   varchar(255);
    v_contentencoding varchar(255);
    v_type            varchar(255) := 'RR_PATIENT_BENEFIT';
    v_ownerid         uuid;
    c_ftload          varchar(6)   := 'FTLoad';
BEGIN

    IF (p_xml IS NULL) THEN
        v_operationtype := c_ftload;
    END IF;

    IF (v_operationtype = c_ftload) THEN

			SELECT 
			    '<RR_PATIENT><header><TYPE>FTLoad</TYPE></header><body><RR_PATIENTS>' ||
			    string_agg(
			        XMLSERIALIZE(CONTENT patient_xml AS TEXT),
			        ''
			    ) ||
			    '</RR_PATIENTS></body></RR_PATIENT>'
			INTO v_result
			FROM (
			    SELECT
			        XMLELEMENT(
			            NAME "RR_PATIENT",
			            XMLFOREST(
			                rp.rrpatientid AS "RrPatientID",
			                rp.snils AS "Snils",
			                rp.docseries AS "DocSeries",
			                rp.docnumber AS "DocNumber",
			                rp.lastname AS "LastName",
			                rp.firstname AS "FirstName",
			                rp.fathername AS "FatherName",
			                TO_CHAR(rp.birthday, 'YYYY.MM.DD') AS "Birthday",
			                TO_CHAR(rp.datebegin, 'YYYY.MM.DD') AS "DateBegin",
			                TO_CHAR(rp.dateend, 'YYYY.MM.DD') AS "DateEnd",
			                TO_CHAR(rp.lasteditdate, 'YYYY.MM.DD') AS "LastEditDate",
			                esex.code AS "Sex",
			                rp.lasteditlpu AS "Lpu",
			                rp.excludereason AS "ExcludeReason",
			                rp.tipd AS "DocType",
			                rp.kod AS "Kod",
			                rp.kodadr AS "KodAdr",
			                TO_CHAR(rp.dat_prov, 'YYYY.MM.DD') AS "DAT_PROV",
			                rp.birthsurname AS "BirthSurname",
			                rp.lpumainfirst AS "LpuFirst",
			                rp.sost_r AS "SOST_R"
			            )
			        ) AS patient_xml
			    FROM rds.t_rr_patient rp
			    JOIN vclib.t_enums esex ON esex.enumid = rp.sex
			) AS patients;


        INSERT INTO rds.t_rabbit_send_object
        (
            rabbitsendobjectid,
            queuename,
            content,
            messageid,
            headers,
            contentencoding,
            type,
            userid,
            state,
            createdatetime,
            ownerid
        )
        SELECT gen_random_uuid(),
               s.servername,
               public.converttexttobinaryzip(v_result, ''),
               NULL,
               NULL,
               v_contentencoding,
               v_type,
               p_user,
               0,
               p_datetime,
               v_ownerid
        FROM rds.t_sync_servers s
        WHERE (p_queuename IS NOT NULL AND s.servername = p_queuename)
           OR (p_queuename IS NULL AND s.servertype IN (0, 1));

    END IF;

END;
$$;
