DROP PROCEDURE IF EXISTS ehr.SP_EHR_REPLACEMENT_FILL;

CREATE PROCEDURE ehr.SP_EHR_REPLACEMENT_FILL
(
	"oldVersion" varchar(8)
,	"newVersion" varchar(8)
,	"code" varchar(64)
,	"parent" uuid
,	"entity" varchar(100)
,	"attr" varchar(100)
,	"onlyUpdate" boolean
)
    language plpgsql
as
$$
Begin

	DECLARE 
		"OldEhrRusRefBooks" integer := (SELECT rb.EhrRusRefBooksID FROM EHR.T_EHR_RUS_REF_BOOKS rb WHERE rb.Code = "code" AND rb.CurrVersion = "oldVersion" limit 1);
		"NewEhrRusRefBooks" integer := (SELECT rb1.EhrRusRefBooksID FROM EHR.T_EHR_RUS_REF_BOOKS rb1 WHERE rb1.Code = "code" AND rb1.CurrVersion = "newVersion" limit 1);
		"EntityID" integer := (SELECT erfb.Entities FROM EHR.T_EHR_RUS_REF_BOOKS erfb WHERE erfb.EhrRusRefBooksID = "OldEhrRusRefBooks");
		"NameEHR" VARCHAR(132) := (SELECT e.Schema + '.T_' + e.EntName FROM VCLib.T_ENTITIES e WHERE e.EntityID = "EntityID");
		"conditionCode" VARCHAR(100);
		_tsql text;
BEGIN
	IF EXISTS (SELECT MappingName FROM VCLib.T_ENTITIES_ATTRIBUTES ea WHERE EntityID = "EntityID" And MappingName = 'IdEHR' limit 1) then
		"conditionCode" := 'e1.IdEHR = e2.IdEHR';
	ELSIF EXISTS (SELECT MappingName FROM VCLib.T_ENTITIES_ATTRIBUTES ea WHERE EntityID = "EntityID" And MappingName = 'CodeEHR' limit 1) then
		"conditionCode" := 'e1.CodeEHR = e2.CodeEHR';
	end if;
	
	
	if("onlyUpdate" = 1)
	then
		_tsql := '
		select distinct(dd.' || "attr" || ')
		into TEMPORARY OldData
		from ' || "entity" || ' dd 
		join ' || "NameEHR" || ' er on er.EhrRusID = dd.' || "attr" || '
		where er.EhrRusRefBooks = ''' || "OldEhrRusRefBooks"::varchar(50) || ''';
		
		INSERT INTO  EHR.T_ELEMENT_EHR_REPLACEMENT (ElementEhrReplacementID, EhrReplacement, OldEhr, NewEhr, ExistsData, AutomaticallyFilled)
		SELECT uuid_generate_v4(),  ''' || "parent" ::varchar(36) || ''', e1.EhrRusID, e2.EhrRusID , case when old.' || "attr" || ' is not null then ''' || 1 || ''' else ''' || 0 || ''' end, case when e2.EhrRusID is not null then ''' || 1 || ''' else ''' || 0 || ''' end
		FROM ' || "NameEHR" || ' e1
		LEFT JOIN ' || "NameEHR" || ' e2 ON ' || "conditionCode" || ' AND e2.EhrRusRefBooks = ''' || "NewEhrRusRefBooks"::varchar(50) || '''
		left join OldData old on old.' || "attr" || ' = e1.EhrRusID
		WHERE e1.EhrRusRefBooks = ''' || "OldEhrRusRefBooks"::varchar(50) || ''' ;
		
		drop table OldData;';
	ELSE  
		_tsql := '
			select distinct(dd.' || "attr" || ')
			into OldData
			from ' || "entity" || ' dd 
			join ' || "NameEHR" || ' er on er.EhrRusID = dd.' || "attr" || '
			where er.EhrRusRefBooks = ''' || "OldEhrRusRefBooks"::varchar(50) || ''';
			
			update EHR.T_ELEMENT_EHR_REPLACEMENT er
				set ExistsData = ''' || 1 || '''
			from OldData old  
			where old.' || "attr" || ' = er.OldEhr and er.ExistsData = ''' || 0 || ''' and er.EhrReplacement = ''' || "parent" ::varchar(36) || ''';
	
			drop table OldData ;';
	End if;

	--RAISE NOTICE '%', _tsql;
	EXECUTE _tsql;	
End;
End;
$$;
