DROP PROCEDURE IF EXISTS sp_CreateBSK_Direction;

CREATE PROCEDURE sp_CreateBSK_Direction
(
	"ID" uuid
,	"QueueName" varchar(100)
,	"User" uuid default null::uuid
)
    language plpgsql
as
$$
Begin

	Declare	
		_newDirId uuid := uuid_generate_v4();
		_newBenId uuid := uuid_generate_v4();
		_PAC_ID int;
		_Patient uuid;
		_DateBeg timestamp;
		_DateEnd timestamp;
		_Diagnosis varchar(255);
		_Old boolean := '0';
		_DRegistrationDate timestamp;
		_CloseDate timestamp;
	Begin
		
		select br.Patient 
		from AKUZ.T_BSK_REGISTER_RECORDS br
		into _Patient
		where br.BskRegisterRecordsID = "ID";
		
		select d.PAC_ID 
		from AKUZ.T_BSK_REGISTER_RECORDS br
			join AKUZ.T_PATIENT_BENEFITS_DIRECTION d on d.Patient = br.Patient
			join AKUZ.T_BSK_BENEFITS_DIRECTION bb on bb.PatientBenefitsDirectionID = d.PatientBenefitsDirectionID
		into _PAC_ID
		where d.PAC_ID is not null  and br.BskRegisterRecordsID = "ID" limit 1;
	
		if exists(select* from AKUZ.T_BSK_REGISTER_RECORDS br where br.Patient = _Patient and br.BskRegisterRecordsID <> "ID")
		then
			_Old := '1';
		else
			_Old := '0';
		end if;
		
		if(_PAC_ID is not null and _Old = '0' and _CloseDate is null and _DRegistrationDate is null)
        then
		   RAISE EXCEPTION 'Ошибка создания направления из терапии! Обратитесь к администратору!';
        end if;
	
		INSERT INTO AKUZ.T_PATIENT_BENEFITS_DIRECTION
				(Date, 
				ChangeType, 
				PatientBenefitsDirectionID, 
				EnterDate, 
				LastName, 
				FirstName, 
				FatherName, 
				Birthday, 
				Kod, 
				DocSeries, 
				DocNumber, 
				Users, 
				Sex, 
				SNILS, 
				DocType, 
				LpuMain, 
				PAC_ID, 
				Patient, 
				type_)
		select	now()::timestamp, 
				case when br.DRegistrationDate is not null or br.CloseDate is not null or _Old = '1' then 2 else 1 end
		,		_newDirId, now()::timestamp
		,		p.LastName
		,		p.FirstName
		,		p.FatherName
		,		p.Birthday
		,		(select ac.Number from AKUZ.T_AMBULANCE_CARD ac where ac.Patient = p.PatientID and ac.CardLpu = br.LpuMain limit 1)
		,		p.DocSeries
		,		p.DocNumber
		,		"User"
		,		p.Sex
		,		p.SNILS
		,		p.DocType
		,		br.LpuMain
		,		_PAC_ID
		,		p.PatientID
		,		(select e.EntityID from VCLib.T_ENTITIES e where e.EntName = 'BSK_BENEFITS_DIRECTION' limit 1)
		from AKUZ.T_BSK_REGISTER_RECORDS br
			join AKUZ.T_PATIENT p on br.Patient = p.PatientID
		where br.BskRegisterRecordsID = "ID";
	
		INSERT INTO AKUZ.T_BSK_BENEFITS_DIRECTION(PatientBenefitsDirectionID, ExcludeReason, BskRegisterRecords)
		select _newDirId, null, "ID";
	
		INSERT INTO AKUZ.T_PATIENT_BENEFITS_DIRECTION_DATA
			(PatientBenefitsDirectionDataID, 
			DiagDate, 
			Document, 
			DocumentDate, 
			PatientBenefitsDirection, 
			Benefits, 
			Doctor, 
			Mkb, 
			BenefitViews, 
			ChangeType, 
			type_)
		select _newBenId, 
			br.DateBegin, 
			null, 
			null, 
			_newDirId, 
			br.Benefits, 
			br.Post, 
			br.Mkb, 
			4
		,	case when br.CloseDate is not null and  br.ExclusionReason is not null and br.ExclusionReason <> 0 then 3
				when br.DRegistrationDate is not null and br.Place = 0 then 2
				else 1 
				end
		,	(select e.EntityID from VCLib.T_ENTITIES e where e.EntName = 'BSK_BENEFITS_DIRECTION_DATA' limit 1)
		from AKUZ.T_BSK_REGISTER_RECORDS br
			join AKUZ.T_PATIENT p on br.Patient = p.PatientID
		where br.BskRegisterRecordsID = "ID";
	
		INSERT INTO AKUZ.T_BSK_BENEFITS_DIRECTION_DATA
			(PatientBenefitsDirectionDataID, 
			MedicalService, 
			DateBegin, 
			DateEnd, 
			ExclusionReason, 
			EstimatedDDate, 
			DRegistrationDate, 
			Place, 
			LpuMainTo, 
			CloseDate)
		select _newBenId, 
			br.MedicalService, 
			br.DateBegin, 
			br.DateEnd, 
			br.ExclusionReason, 
			br.EstimatedDDate, 
			br.DRegistrationDate, 
			br.Place, 
			br.LpuMainTo, 
			br.CloseDate
		from AKUZ.T_BSK_REGISTER_RECORDS br
			join AKUZ.T_PATIENT p on br.Patient = p.PatientID
		where br.BskRegisterRecordsID = "ID";
	
		INSERT INTO AKUZ.T_BSK_BENEFITS_DIRECTION_MEDICAMENTS
			(BskBenefitsDirectionMedicamentsID, 
			BskBenefitsDirectionData, 
			CMnn, 
			DateStart, 
			EndDate, 
			MedicationForms, 
			Regiment, 
			Dose, 
			MeasureUnit, 
			Prepid, 
			DayliCoeff, 
			DoseView, 
			SingleDose, 
			Multiplicity)
		select uuid_generate_v4(), 
			_newBenId, 
			mnn.CMnn, 
			mnn.DateStart, 
			mnn.EndDate, 
			mnn.MedicationForms, 
			mnn.Regiment, 
			mnn.Dose, 
			mnn.MeasureUnit, 
			mnn.Prepid, 
			mnn.DayliCoeff, 
			mnn.DoseView, 
			mnn.SingleDose, 
			mnn.Multiplicity
		from AKUZ.T_BSK_REGISTER_LINK_MNN mnn 
			join AKUZ.T_BSK_REGISTER_RECORDS br on br.BskRegisterRecordsID = mnn.BskRegisterRecords
		where mnn.BskRegisterRecords = "ID";
	
		call sp_BSK_Register_Direction(null, _newDirId, "QueueName");
	
		select into 
			_DateBeg, _DateEnd, _Diagnosis 
			br.DateBegin, coalesce(br.CloseDate, br.DateEnd), left(br.Diagnosis, 255)
		from AKUZ.T_BSK_REGISTER_RECORDS br
			join AKUZ.T_PATIENT p on br.Patient = p.PatientID
		where br.BskRegisterRecordsID = "ID";
	
		call sp_CreatePulmo_Notification(_Patient, _DateBeg, _DateEnd, _Diagnosis);
    End;
End;
$$;