-- =============================================
-- Author:  Timur R. Khakimov  2014
-- Create date: 2014-10-13
-- Description: Заполнение таблицы информацией о закрытых случаях
-- =============================================
DROP PROCEDURE IF EXISTS sp_adddoctorvisitnotify;
CREATE PROCEDURE sp_adddoctorvisitnotify(
    "MedicalRecordID" uuid,
    "IsNew" boolean)
AS
$BODY$
declare
	"DoctorVisitNotifyServiceStatus" boolean;
	"PatientID" uuid; 
	"SpecialityName" varchar(255);
	"DoctorFIO" varchar(255);
	"LpuCode" varchar(4);
	"BranchCode" varchar(8);
	"PostID" uuid;
	"IsMovementResult" boolean;
	"IndexType" int;
Begin
	"IsMovementResult" := '0';
	IF "IsNew" = '1'
	then
		"DoctorVisitNotifyServiceStatus" := (SELECT Status from AKUZ.T_VCSN_SERVICES where VCSNServiceName='DoctorVisitNotify');
		IF "DoctorVisitNotifyServiceStatus" = '1'
		then
			SELECT into
				"PatientID", "SpecialityName", "DoctorFIO", "LpuCode", "PostID", "BranchCode", "IndexType"
				AmbulanceCard.Patient, Speciality.Name, Worker.FIO, LpuMain.Code, PResource.ResourceIdGuid, Branch.BranchCode, MedicalRecord.type_			
			FROM AKUZ.T_OUTCOME_OF_INSPECTION OutcomeOfInspection
			inner JOIN 
				AKUZ.T_AMBULANCE_CARD_RECORD AmbulanceCardRecord 
				on AmbulanceCardRecord.MedicalRecordID = OutcomeOfInspection.MedicalRecordID
			inner JOIN 
				AKUZ.T_AMBULANCE_CARD AmbulanceCard 
				on AmbulanceCard.AmbulanceCardID = AmbulanceCardRecord.AmbulanceCard
			inner JOIN 
				AKUZ.T_MEDICAL_RECORD MedicalRecord 
				on MedicalRecord.MedicalRecordID = OutcomeOfInspection.MedicalRecordID
			inner JOIN 
				AKUZ.T_RESOURCE PResource 
				on PResource.ResourceID = MedicalRecord.Post
			inner JOIN 
				AKUZ.T_SPECIALITY Speciality 
				on Speciality.SpecialityID = PResource.Speciality
			inner JOIN 
				AKUZ.T_POST Post 
				on Post.ResourceID = MedicalRecord.Post
			inner JOIN 
				AKUZ.T_WORKER Worker 
				on Worker.WorkerID = Post.Worker
			inner JOIN 
				AKUZ.T_DIVISION Division 
				on Division.DivisionID = PResource.Division
			inner JOIN 
				AKUZ.T_BRANCH Branch 
				on Branch.LpuID = Division.Branch
			inner JOIN 
				AKUZ.T_LPU_MAIN LpuMain 
				on LpuMain.LpuID = Branch.LpuMain
			WHERE OutcomeOfInspection.MedicalRecordID = "MedicalRecordID";

			IF "IndexType" = 1110 
			then 
				"IsMovementResult" := "1";
			end if;
			
			INSERT INTO AKUZ.T_DOCTOR_VISIT_NOTIFY2 (DoctorVisitNotifyID, PatientID, SpecName, DoctorFIO, LpuCode, BranchCode, IsMovementResult, MedicalRecordID, CreationDT, PostID)
			VALUES(uuid_generate_v4(), "PatientID", "SpecialityName", "DoctorFIO", "LpuCode", "BranchCode", "IsMovementResult", "MedicalRecordID", current_timestamp, "PostID");
		END if;
	ELSE 
		DELETE FROM AKUZ.T_DOCTOR_VISIT_NOTIFY2 where MedicalRecordID = "MedicalRecordID" AND CreationDT > current_timestamp + (-1 * interval '1 day');
	end if;
End;
$BODY$
  LANGUAGE plpgsql;
