-- =============================================
-- Author:		Vitacore (с)
-- Create date: 2020-01-31
-- Description:	Выгрузка информации о госпитализации в ISZL
-- =============================================
drop procedure if exists sp_ISZL_MotionInHospitalXml;
CREATE procedure sp_ISZL_MotionInHospitalXml
(
	"LpuCode" text DEFAULT NULL::text
,	"Xml" xml DEFAULT NULL::xml
,	"IsNew" boolean DEFAULT '1'::boolean
,	"ID" uuid DEFAULT NULL::uuid
,	"QueueName" varchar(255) DEFAULT NULL::varchar(255)
,	"ObjectType" boolean DEFAULT '0'::boolean	-- 0 - Движение 1- выписка
)
AS
$BODY$
Declare	_Result text;
	_ContentEncoding varchar(255);
	_Type varchar(255);
	_OperationType varchar(255);
	_OwnerID UUID;
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;

			_ContentEncoding := 'utf-8';
			_Type := 'MOTION_IN_HOSPITAL';
			_OwnerID := "ID";

			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";
			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;

				_ContentEncoding := 'utf-8';
				_Type := 'MOTION_IN_HOSPITAL';
				_OwnerID := "ID";

				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, '')		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;
		END if;
		
		INSERT INTO akuz.T_RABBIT_SEND_OBJECT(RabbitSendObjectID, QueueName, Content, MessageID, Headers, ContentEncoding, Type, UserID, State, CreateDateTime, OwnerID)
		select uuid_generate_v4(), "QueueName", ConvertTextToBinaryZip(_Result, ''), null, null, _ContentEncoding, _Type, null, 0, Current_TimeStamp::TIMESTAMP, _OwnerID;
	END if;
End;
$BODY$ Language plpgsql;
