DROP PROCEDURE IF EXISTS ehr.sp_Process_PN8K8VMPD5;

CREATE PROCEDURE ehr.sp_Process_PN8K8VMPD5
(
    "Code" varchar(64),
    "Name" varchar(255),
    "CurrVersion" varchar(8),
	"OldVersion" varchar(8),
    "OID" varchar(54),
	"CheckMatching" boolean
)
    language plpgsql
as
$$
Begin

	declare 
		"entityID" integer := (select Entityid from VCLib.T_ENTITIES e where EntName = 'EHR_RUS_PN8K8VMPD5'); 
		"refBooks" integer := (select b.EhrRusRefBooksID from EHR.T_EHR_RUS_REF_BOOKS b where b.Entities = "entityID" and b.CurrVersion = "CurrVersion" limit 1);
		"ehrRusIDsCount" integer;
		maxEhrRusID integer;	

	Begin
		update "PN8K8VMPD5" set "SORT" = null where "SORT" = '';

		if "OldVersion" is not null or "refBooks" is not null
		then
			if "refBooks" is null
			then
				"refBooks" := (select b.EhrRusRefBooksID from EHR.T_EHR_RUS_REF_BOOKS b where b.Entities = "entityID" and b.CurrVersion = "OldVersion" limit 1);
			end if;
		
			if "CheckMatching" = '1'
			then
				DROP TABLE IF EXISTS tempTbForEhrs;
				CREATE TEMP TABLE tempTbForEhrs(
				    Id1 integer
				  , Id2 integer
				);
		
				insert into tempTbForEhrs
				select er.IdEHR, tt."ID"
				from ehr.T_EHR_RUS_PN8K8VMPD5 er 
					left join "PN8K8VMPD5" tt on er.IdEHR = tt."ID"
				where er.EhrRusRefBooks = "refBooks";
		
				if exists (select * from tempTbForEhrs where id2 is null)
				then
					RAISE EXCEPTION 'Невозможно обновить справочник, обнаружено несоответствие записей нового справочника с текущем. Скачайте новый справочник и обновите связи!';
				end if;
				DROP TABLE tempTbForEhrs;
			end if;
		
			if "refBooks" is null
			then
				CALL sp_GenerateIdForEntity('EHR.EHR_RUS_REF_BOOKS', 'PrimaryKey', 1,"refBooks");
		
				INSERT INTO EHR.T_EHR_RUS_REF_BOOKS
					(EhrRusRefBooksID,Code,Name,CurrVersion,UpdateDate,Entities,OID, Deleted)
				VALUES
					("refBooks", "Code", "Name", "CurrVersion", now(), "entityID", "OID", '0');
			else
				update EHR.T_EHR_RUS_REF_BOOKS
				set Code = "Code",
					Name= "Name",
					CurrVersion = "CurrVersion",
					UpdateDate = now(),
					Entities = "entityID",
					OID = "OID"
				where EhrRusRefBooksID = "refBooks";
			end if;
		
			UPDATE EHR.T_EHR_RUS_PN8K8VMPD5 r2 
			SET NameEHR = p."S_NAME"
				, CodeEHR = p."ICD-10"
			from "PN8K8VMPD5" p 
			where r2.IdEHR = p."ID" and r2.EhrRusRefBooks = "refBooks";
		
			UPDATE EHR.T_EHR_RUS_PN8K8VMPD5 rb																					  
				SET  SORT = p."SORT"
			 FROM "PN8K8VMPD5" p  
			WHERE rb.IdEHR = p."ID" and rb.EhrRusRefBooks = "refBooks";
		
			update "PN8K8VMPD5" p
			set EhrRusID = -1
			where not exists (select * from EHR.T_EHR_RUS_PN8K8VMPD5 r2 where r2.IdEHR = p."ID" and r2.EhrRusRefBooks = "refBooks");
		
			"ehrRusIDsCount" := (SELECT COUNT(*) FROM "PN8K8VMPD5"  WHERE EhrRusID = -1);

			CALL sp_GenerateIdForEntity('EHR.EHR_RUS_PN8K8VMPD5', 'PrimaryKey', "ehrRusIDsCount",maxEhrRusID);
			maxEhrRusID := maxEhrRusID - 1;
		
			WITH CTE AS (
				SELECT
					IdEHR,
					ROW_NUMBER() OVER (ORDER BY "ID") AS RowNum
				FROM "PN8K8VMPD5"
				WHERE EhrRusID = -1 
			)
			UPDATE "PN8K8VMPD5" d
			SET EhrRusID = c.RowNum + maxEhrRusID
			from CTE c 
			where c.IdEHR = d.IdEHR;
		
			INSERT INTO EHR.T_EHR_RUS_PN8K8VMPD5
			           (EhrRusRefBooks
			           ,EhrRusID
			           ,IdEHR
			           ,CodeEHR
			           ,NameEHR
			           ,SORT)
			select 
				"refBooks"
				,p.EhrRusID
				,p."ID"
				,p."ICD-10"
				,p."S_NAME"
				,p."SORT"
			from "PN8K8VMPD5" p
			where p.EhrRusID is not null;
		else
		    alter table "PN8K8VMPD5" add column idnew int GENERATED ALWAYS AS IDENTITY;

			CALL sp_GenerateIdForEntity('EHR.EHR_RUS_REF_BOOKS', 'PrimaryKey', 1,"refBooks");
		
			INSERT INTO EHR.T_EHR_RUS_REF_BOOKS
				(EhrRusRefBooksID,Code,Name,CurrVersion,UpdateDate,Entities,OID, Deleted)
			VALUES
				("refBooks", "Code", "Name", "CurrVersion", now(), "entityID", "OID", '0');
		
			"ehrRusIDsCount" := (SELECT COUNT(*) FROM "PN8K8VMPD5");
			
			CALL sp_GenerateIdForEntity('EHR.EHR_RUS_PN8K8VMPD5', 'PrimaryKey', "ehrRusIDsCount",maxEhrRusID);
			maxEhrRusID := maxEhrRusID - 1;
		
			UPDATE "PN8K8VMPD5" SET EhrRusID = idnew + maxEhrRusID;
		
			INSERT INTO EHR.T_EHR_RUS_PN8K8VMPD5
				       (EhrRusRefBooks
					   ,EhrRusID
			           ,IdEHR
				       ,CodeEHR
					   ,NameEHR
			           ,SORT)  
			select 
				"refBooks"
				,p.EhrRusID
				,p."ID"
				,p."ICD-10"
				,p."S_NAME"
				,p."SORT"
			from "PN8K8VMPD5" p
			where p.EhrRusID is not null;
		
			update ehr.T_EHR_REFERENCE
			set EhrRusRefBooks = "refBooks"
			where EhrEntity = "entityID" and EhrRusRefBooks is null;
		end if;

		drop table "PN8K8VMPD5";
	end;
End;
$$;