DROP PROCEDURE IF EXISTS ehr.sp_Process_V2LJ680EAR;

CREATE PROCEDURE ehr.sp_Process_V2LJ680EAR
(
    "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_V2LJ680EAR'); 
		"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
		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_V2LJ680EAR er 
					left join "V2LJ680EAR" 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_V2LJ680EAR r2
			SET NameEHR = p."S_NAME"
				, CodeEHR = p."ICD-10"
			from "V2LJ680EAR" p 
			where r2.IdEHR = p."ID" and r2.EhrRusRefBooks = "refBooks";
		
			UPDATE EHR.T_EHR_RUS_V2LJ680EAR rb																					  
				SET 																						    
			       SORT = p."SORT"
			 FROM "V2LJ680EAR" p
			WHERE rb.IdEHR = p."ID" and rb.EhrRusRefBooks = "refBooks";
		
			update p
			set EhrRusID = -1
			from "V2LJ680EAR" p
			where not exists (select * from EHR.T_EHR_RUS_V2LJ680EAR r2 where r2.IdEHR = p."ID" and r2.EhrRusRefBooks = "refBooks");
		
			"ehrRusIDsCount" := (SELECT COUNT(*) FROM "V2LJ680EAR"  WHERE EhrRusID = -1);

			CALL sp_GenerateIdForEntity('EHR.EHR_RUS_V2LJ680EAR', 'PrimaryKey', "ehrRusIDsCount",maxEhrRusID);
			maxEhrRusID := maxEhrRusID - 1;
		
			WITH CTE AS (
				SELECT
					EhrRusID,
					ROW_NUMBER() OVER (ORDER BY "ID") AS RowNum
				FROM "V2LJ680EAR"
				WHERE EhrRusID = -1
			)
			UPDATE "V2LJ680EAR" d			
			SET EhrRusID = c.RowNum + maxEhrRusID
			from CTE c
			where c.EhrRusID = d.EhrRusID;
		
			INSERT INTO EHR.T_EHR_RUS_V2LJ680EAR
			           (EhrRusRefBooks
			           ,EhrRusID
			           ,IdEHR
			           ,CodeEHR
			           ,NameEHR
			           ,SORT)
			select 
				"refBooks"
				,p.EhrRusID
				,p."ID"::integer
				,p."ICD-10"
				,p."S_NAME"
				,p."SORT"::integer
			from "V2LJ680EAR" p
			where p.EhrRusID is not null;
		else
		
			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 "V2LJ680EAR");
			
			CALL sp_GenerateIdForEntity('EHR.EHR_RUS_V2LJ680EAR', 'PrimaryKey', "ehrRusIDsCount",maxEhrRusID);
			maxEhrRusID := maxEhrRusID - 1;
		
			WITH CTE AS (
				SELECT
					EhrRusID,
					ROW_NUMBER() OVER (ORDER BY "ID") AS RowNum
				FROM "V2LJ680EAR"
			)
			UPDATE "V2LJ680EAR" d
			SET EhrRusID = c.RowNum + maxEhrRusID
			from CTE c
			where c.EhrRusID = d.EhrRusID;

			INSERT INTO EHR.T_EHR_RUS_V2LJ680EAR
				       (EhrRusRefBooks
					   ,EhrRusID
			           ,IdEHR
				       ,CodeEHR
					   ,NameEHR
			           ,SORT)  
			select 
				"refBooks"
				,p.EhrRusID
				,p."ID"::integer
				,p."ICD-10"
				,p."S_NAME"
				,p."SORT"::integer
			from "V2LJ680EAR" 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 "V2LJ680EAR";
	end;
End;
$$;