-- =============================================
-- Author:		Vitacore (с)
-- Create date: 2020-01-31
-- Description:	Выгрузка информации о госпитализации в ISZL
-- =============================================
drop procedure if exists public.sp_iszl_motioninhospitalxml;
CREATE procedure public.sp_iszl_motioninhospitalxml
(
	"LpuCode" text DEFAULT NULL::text
,	"Xml" text DEFAULT NULL
,	"IsNew" integer DEFAULT 1::integer
,	"ID" uuid DEFAULT NULL::uuid
,	"QueueName" varchar(255) DEFAULT NULL::varchar(255)
,	"ObjectType" integer DEFAULT 0::integer	-- 0 - Движение 1- выписка
)
AS
$BODY$
Declare	_Result text;
	_ContentEncoding varchar(255):= 'utf-8';
	_Type varchar(255) := 'MOTION_IN_HOSPITAL';
	_OperationType varchar(255);
	_OwnerID UUID := "ID";
Begin
	IF "Xml" is null
	then
		IF "ObjectType" = 0
		then
			--выясняем тип операции
			IF "IsNew" = 1
			then
				_OperationType := 'Insert';
			ELSIF "IsNew" = 0 and exists(select* from akuz.T_MOVEMENTS_DIVISION_CARD mdc where mdc.MedicalEpisodeID = "ID")
			then
				_OperationType := 'Update';
			ELSIF "IsNew" = 0 and not exists(select* from akuz.T_MOVEMENTS_DIVISION_CARD mdc where mdc.MedicalEpisodeID = "ID")
			then
				_OperationType := 'Delete';
				_Result := XMLELEMENT(name "MOTION_IN_HOSPITAL", XMLFOREST(XMLFOREST("LpuCode" as "MO", _OperationType as "TYPE") as header));			
			END if;

			IF _OperationType <> 'Delete'
			then
				select
				XMLELEMENT
				(
					name "MOTION_IN_HOSPITAL"
				,	XMLFOREST
					(
						XMLFOREST
						(
							"LpuCode" as "MO"
						,	_OperationType as "TYPE"
						) as header
					)
				,	XMLFOREST
					(
						XMLFOREST
						(
							to_char(mov.MovementDate, 'YYYY-MM-DD') as "HOSPITALISATION_DATE"
						,	mov.MedCardNumber as "MED_CARD_NUMBER"
						,	br.BranchCode as "BRANCH"
						,	d.Code as "DIVISION"
						,	sb.Code as "V020_STRUCTURE_BED"	
						,	to_char(me.DateIn, 'YYYY-MM-DD') as "DATE_IN"
						,	to_char(me.DateOut, 'YYYY-MM-DD') as "DATE_OUT"
						,	1									as "TYPE_MOT"
						,	''									as "USL_OK"
						,	''									as "OUTCOME"
						) as body
					)
				)
				from akuz.T_MOVEMENTS_DIVISION_CARD mdc
				join AKUZ.T_MEDICAL_EPISODE me on mdc.MedicalEpisodeID = me.MedicalEpisodeID
				inner join  akuz.T_STRUCTURE_BED sb  on sb.StructureBedID = mdc.StructureBed
				inner join  akuz.T_V002_PROFILE v0  on v0.Id = sb.V002Profile
				--LPU
				inner join akuz.T_DIVISION d on d.DivisionID = mdc.Division
				inner join  akuz.T_BRANCH br  on br.LpuID = d.Branch
				inner join  akuz.T_LPU_MAIN lp  on lp.LpuID = br.LpuMain
				--patient
				inner join akuz.T_MOVEMENT mov on mov.MovementID = mdc.Movement
				into _Result
				where mdc.MedicalEpisodeID = "ID";
            end if;
		ELSE
			--выясняем тип операции
			IF "IsNew" = 1
			then
				_OperationType := 'Insert';
			ELSIF "IsNew" = 0 and exists(select* from akuz.T_MOVEMENT_RESULT mr where mr.MedicalRecordId = "ID")
			then
				_OperationType := 'Update';
			ELSIF "IsNew" = 0 and not exists(select* from akuz.T_MOVEMENT_RESULT mr where mr.MedicalRecordId = "ID")
			then
				_OperationType := 'Delete';
				_Result := XMLELEMENT(name "MOTION_IN_HOSPITAL", XMLFOREST(XMLFOREST("LpuCode" as "MO", _OperationType as "TYPE") as header));			
			END if;

			IF _OperationType <> 'Delete'
			then
				select
				XMLELEMENT
				(
					name "MOTION_IN_HOSPITAL"
				,	XMLFOREST
					(
						XMLFOREST
						(
							"LpuCode" as "MO"
						,	_OperationType as "TYPE"
						) as header
					)
				,	XMLFOREST
					(
						XMLFOREST
						(
							to_char(mov.MovementDate, 'YYYY-MM-DD') as "HOSPITALISATION_DATE"
						,	mov.MedCardNumber as "MED_CARD_NUMBER"
						,	br.BranchCode as "BRANCH"							
						,	d.Code as "DIVISION"
						,	sb.Code as "V020_STRUCTURE_BED"
						,	to_char(mr.DatIn, 'YYYY-MM-DD') as "DATE_IN"
						,	to_char(mr.DatOut, 'YYYY-MM-DD') as "DATE_OUT"
						,	2 as "TYPE_MOT"
						,	coalesce(v012.DL_USLOV::varchar(10), '')		as "USL_OK"
						,	case when mr.TreatmentOutcome = 102 then 1
								when mr.TreatmentOutcome = 103 then 2
								when mr.TreatmentOutcome = 104 then 3 
							end as "OUTCOME"
						) as body
					)
				)
				from akuz.T_MOVEMENT_RESULT mr
				inner join  akuz.T_STRUCTURE_BED sb on sb.StructureBedID = mr.StructureBed
				inner join  akuz.T_V002_PROFILE v0  on v0.Id = sb.V002Profile
				--LPU
				inner join  akuz.T_DIVISION d  on d.DivisionID = mr.Division
				inner join  akuz.T_BRANCH br  on br.LpuID = d.Branch
				inner join  akuz.T_LPU_MAIN lp  on lp.LpuID = br.LpuMain
				--patient
				inner join  akuz.T_MOVEMENT mov  on mov.MovementID = mr.MedicalcardRegistration
				inner join  AKUZ.T_V012_OUTCOME v012 on mr.TreatmentOutcome = v012.IDIZ
				into _Result
				where mr.MedicalRecordId = "ID"; --and d.IsRequestonDivision = 0 and d.IsRequestInHospital = 1;
			END if;	
		END if;
		
		INSERT INTO akuz.T_RABBIT_SEND_OBJECT(RabbitSendObjectID, QueueName, Content, MessageID, Headers, ContentEncoding, "type", UserID, State, CreateDateTime, OwnerID)
		select gen_random_uuid(), "QueueName", ConvertTextToBinaryZip(_Result, ''), null, null, _ContentEncoding, _Type, null, 0, Current_TimeStamp::TIMESTAMP, _OwnerID;
	END if;
End;
$BODY$ Language plpgsql;
