create or replace function rpt1.han_evnps_survey_pg(p_evnps_id bigint) returns table (
  "Xml_DateAuthor" character varying,
  "Xml_Text" character varying,
  rgx_complaint text,
  rgx_anamnesvitae text,
  rgx_treatmentplan text,
  "XmlType_id" integer,
  "EvnSection_IsPriem" integer)
language plpgsql as $plpgsql$BEGIN
return query
	--73002388087521
with Document as(
	select
		concat(
			'Дата и время осмотра: ',
			coalesce(
				to_char(EvnXml.EvnXml_insDT, 'DD.MM.YYYY HH24:mm'), 
				'не указана') ,
			'   Лечащий врач: ',
			coalesce(
				trim(pmUserCache.pmUser_Name), 
				'не указан')
			) as DateAuthor, --дата и автор документа

		cast(xtd.XmlTemplateData_Data as varchar) as XmlTemplateData_Data, --строка из которой берутся названия разделов документа

		cardinality(
			regexp_split_to_array(
				cast(xtd.XmlTemplateData_Data as varchar),
				'<fieldLabel>')) - 1 as T_count, --количество разделов документа
		
		rpt.striphtml2_pg(cast(EvnXml_Data as varchar)) as EvnXml_Data, --текст документа сохраняя теги
		EvnXml.XmlType_id,
		coalesce(EvnSection.EvnSection_IsPriem,1) as EvnSection_IsPriem,
		evn.person_id
			
	from v_evnxml as EvnXml
		inner join v_evn as Evn on Evn.Evn_id = EvnXml.Evn_id
		inner join evnsection on Evn.Evn_id = EvnSection.Evn_id
		left join pmUserCache on pmUserCache.pmUser_id = EvnXml.pmUser_insID
		left join v_xmltemplate as template 
			on template.XmlTemplate_id = evnxml.XmlTemplate_id
		left join XmlTemplateData as xtd 
			on xtd.XmlTemplateData_id = template.XmlTemplateData_id
	where
		Evn.Evn_rid = p_evnps_id
		and EvnXml.XmlType_id in ( 2, 8, 9, 10 )
),

cte_tegs as
(
select 
	  DateAuthor::varchar as Xml_DateAuthor,	  
	  rpt.han_evnps_survey_parse_pg( --в строку с текстом документа вставляются заголовки
		T_count,
		XmlTemplateData_Data,
		EvnXml_Data
		)::varchar as Xml_Text,	
	Document.XmlType_id::int4, 
	EvnSection_IsPriem::int4
from Document	
)

select 
	Xml_DateAuthor::varchar,
	Xml_Text::varchar,	
  regexp_replace(btrim(btrim(regexp_match(Xml_Text, '(?<=<complaint>)(.*?)(?=</complaint>)')::varchar, '{}'), '""'),'<[^b\s]>|</[^b\s]>|<b>Жалобы:</b>', '', 'g')::text as rgx_complaint, -- жалобы в приемном и движении без тегов	
	regexp_replace(btrim(btrim(regexp_match(Xml_Text, '(?<=<anamnesvitae>)(.*?)(?=</anamnesvitae>)')::varchar, '{}'), '""'),'<[^b\s]>|</[^b\s]>|<b>Анамнез|жизни:</b>', '', 'g')::text as rgx_anamnesvitae, --анамнез
	regexp_replace(btrim(btrim(regexp_match(Xml_Text, '(?<=<TreatmentPlan>)(.*?)(?=</TreatmentPlan>)')::varchar, '{}'), '""'),'<[^b\s]>|</[^b\s]>|<b>План|лечения:</b>', '', 'g')::text as rgx_TreatmentPlan, --план лечения
	XmlType_id,EvnSection_IsPriem
from cte_tegs

	;
END$plpgsql$;

