DROP PROCEDURE IF EXISTS sp_n012markdiagload;
DROP FUNCTION IF EXISTS sp_n012markdiagload;

CREATE PROCEDURE public.sp_n012markdiagload("Xml" bytea, "FileName" character varying)
LANGUAGE 'plpgsql'
AS $BODY$
	
declare T xml;
declare tempStrXml text;
BEGIN
	select convert_from("Xml", 'WIN1251') into tempStrXml;
	
	select replace(tempStrXml, 'encoding="windows-1251"','')::xml into T; 
	
	DROP TABLE IF EXISTS temp_n012;

	CREATE TEMP TABLE temp_n012 as
	SELECT 
		ID_I_D::int, 
		DS_Igh,
		ID_Igh::int, 
		CASE WHEN  DATEBEG  = '' THEN NULL ELSE DATEBEG::TIMESTAMP END , 
		CASE WHEN  DATEEND  = '' THEN NULL ELSE DATEEND::TIMESTAMP END 
	FROM
	XMLTABLE ('/packet/zap' PASSING T 
	COLUMNS 
		ID_I_D text path './ID_I_D' null, 
		DS_Igh text path './DS_Igh' null,
		ID_Igh text path './ID_Igh' null,
		DATEBEG text path './DATEBEG' null, 
		DATEEND text path './DATEEND' null );
	
		update IES.T_N012_MARK_DIAG t2
	set  DS_Igh=t1.DS_Igh
		,DATEEND=t1.DATEEND
	from temp_n012 t1
	where (t1.ID_I_D=t2.ID_I_D and t1.DATEBEG = t2.DATEBEG);

	insert into IES.T_N012_MARK_DIAG(N012MarkDiagID, ID_I_D, DS_Igh, N010Mark, DATEBEG, DATEEND)
	select gen_random_uuid(),t1.ID_I_D,t1.DS_Igh,t3.N010MarkID,t1.DATEBEG,t1.DATEEND
	from temp_n012 t1
	left join IES.T_N012_MARK_DIAG t2 on (t1.ID_I_D=t2.ID_I_D and t1.DATEBEG = t2.DATEBEG)
	join IES.T_N010_MARK t3 on (t1.ID_Igh = t3.ID_Igh)
	where t2.N012MarkDiagID is null;

	drop table if exists temp_n012;
	
	return;
END
$BODY$;
