-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2020-09-01
-- Description: Загрузка льготников по орфанным заболеваниям
-- =============================================
DROP PROCEDURE IF EXISTS sp_GetSetRDSOrphRegister;

CREATE PROCEDURE sp_GetSetRDSOrphRegister
(
	"Xml" text DEFAULT NULL
,	"ID" uuid DEFAULT NULL::uuid
,	"QueueName" character varying DEFAULT 'rds.registry'::character varying
,	"dateTime" timestamp without time zone DEFAULT NULL::timestamp without time zone
,	"User" uuid DEFAULT NULL::uuid
)
    language plpgsql
as
$$
 Begin
    declare 
    _OperationType varchar(36);
    Begin
        IF ("Xml" is not null)
        then
	    	"dateTime" := coalesce("dateTime", Current_TimeStamp::TIMESTAMP);
            
            -- Получаем тип операции		
			select into
				_OperationType
				(xpath('/ORPHAN_REGISTER/header[1]/TYPE[1]/text()',"Xml"::xml))[1]::varchar(36);

			-- Generate table TMP_ORPHAN_REGISTERS
			Drop Table If Exists TMP_ORPHAN_REGISTERS;
            Create Temp Table TMP_ORPHAN_REGISTERS
            as
			select (xpath('ORPHAN_REGISTER_ITEM/ID[1]/text()', x))[1]::text::UUID								as ID
			,to_timestamp((xpath('ORPHAN_REGISTER_ITEM/DATE_BEGIN[1]/text()', x))[1]::text, 'YYYY.MM.DD')		as DateBegin
			,to_timestamp((xpath('ORPHAN_REGISTER_ITEM/DATE_END[1]/text()', x))[1]::text, 'YYYY.MM.DD')		as DateEnd
			,(xpath('ORPHAN_REGISTER_ITEM/FIRST_NAME[1]/text()', x))[1]::varchar(60)							as FirstName
			,(xpath('ORPHAN_REGISTER_ITEM/LAST_MANE[1]/text()', x))[1]::varchar(60)							as LastName
			,(xpath('ORPHAN_REGISTER_ITEM/BIRTH_LAST_MANE[1]/text()', x))[1]::varchar(60)						as BirthLastName
			,(xpath('ORPHAN_REGISTER_ITEM/FATHER_NAME[1]/text()', x))[1]::varchar(60)							as FatherName
			,to_timestamp((xpath('ORPHAN_REGISTER_ITEM/BIRTHDAY[1]/text()', x))[1]::text, 'YYYY.MM.DD')		as Birthday
			,(xpath('ORPHAN_REGISTER_ITEM/SEX[1]/text()', x))[1]::text::int									as Sex
			,(xpath('ORPHAN_REGISTER_ITEM/SNILS[1]/text()', x))[1]::varchar(14)								as SNILS
			,(xpath('ORPHAN_REGISTER_ITEM/DIASBILITY[1]/text()', x))[1]::text::int								as Disability
			,(xpath('ORPHAN_REGISTER_ITEM/ADRESS[1]/text()', x))[1]::varchar(1000)								as Adress
			,(xpath('ORPHAN_REGISTER_ITEM/OKATO[1]/text()', x))[1]::varchar(256)								as OKATO
			,(xpath('ORPHAN_REGISTER_ITEM/FEDERAL[1]/text()', x))[1]::text::boolean							as Federal
			,to_timestamp((xpath('ORPHAN_REGISTER_ITEM/DOC_ISSUE_DATE[1]/text()', x))[1]::text, 'YYYY.MM.DD')	as DocIssueDate
			,(xpath('ORPHAN_REGISTER_ITEM/DOC_ISSUE_ORG[1]/text()', x))[1]::varchar(256)						as DocIssueOrg
			,(xpath('ORPHAN_REGISTER_ITEM/DOC_TYPE[1]/text()', x))[1]::text::int								as DocType
			,(xpath('ORPHAN_REGISTER_ITEM/DOC_SERIES[1]/text()', x))[1]::varchar(30)							as DocSeries
			,(xpath('ORPHAN_REGISTER_ITEM/DOC_NUMBER[1]/text()', x))[1]::varchar(30)							as DocNumber
			,(xpath('ORPHAN_REGISTER_ITEM/SMO[1]/text()', x))[1]::varchar(5)									as F002Smo
			,(xpath('ORPHAN_REGISTER_ITEM/OMS_SERIAL[1]/text()', x))[1]::varchar(12)							as OmsSerial
			,(xpath('ORPHAN_REGISTER_ITEM/OMS_NUMBER[1]/text()', x))[1]::varchar(32)							as OmsNumber
			,(xpath('ORPHAN_REGISTER_ITEM/MKB[1]/text()', x))[1]::varchar(10)									as Mkb
			,(xpath('ORPHAN_REGISTER_ITEM/DIAGNOSIS[1]/text()', x))[1]::varchar(4096)							as Diagnosis
			,(xpath('ORPHAN_REGISTER_ITEM/MKB_DOP[1]/text()', x))[1]::varchar(10)								as MkbDop
			,(xpath('ORPHAN_REGISTER_ITEM/DIAGNOSIS_DOP[1]/text()', x))[1]::varchar(4096)						as DiagnosisDop
			,(xpath('ORPHAN_REGISTER_ITEM/LPU_MAIN_FIRST[1]/text()', x))[1]::varchar(6)						as LpuMainFirst
			,(xpath('ORPHAN_REGISTER_ITEM/LPU_MAIN[1]/text()', x))[1]::varchar(6)								as LpuMain
			,(xpath('ORPHAN_REGISTER_ITEM/POST_FIO[1]/text()', x))[1]::varchar(255)							as PostFio
			,(xpath('ORPHAN_REGISTER_ITEM/REGISTER_ID[1]/text()', x))[1]::text::int							as RegisterId
			from
				(
					select	unnest(xpath('/ORPHAN_REGISTER/body/ORPHAN_REGISTERS/ORPHAN_REGISTER_ITEM', "Xml"::xml)) as x
				) ORPHAN_REGISTER_ITEM
			where _OperationType = 'FTLoad';

			-- Generate table TMP_ORPHAN_REGISTER
			Drop Table If Exists TMP_ORPHAN_REGISTER;
            Create Temp Table TMP_ORPHAN_REGISTER
            as
			select (xpath('ORPHAN_REGISTER/body[1]/ID[1]/text()', x))[1]::text::UUID								as ID
			,to_timestamp((xpath('ORPHAN_REGISTER/body[1]/DATE_BEGIN[1]/text()', x))[1]::text, 'YYYY.MM.DD')		as DateBegin
			,to_timestamp((xpath('ORPHAN_REGISTER/body[1]/DATE_END[1]/text()', x))[1]::text, 'YYYY.MM.DD')		as DateEnd
			,(xpath('ORPHAN_REGISTER/body[1]/FIRST_NAME[1]/text()', x))[1]::varchar(60)							as FirstName
			,(xpath('ORPHAN_REGISTER/body[1]/LAST_MANE[1]/text()', x))[1]::varchar(60)							as LastName
			,(xpath('ORPHAN_REGISTER/body[1]/BIRTH_LAST_MANE[1]/text()', x))[1]::varchar(60)						as BirthLastName
			,(xpath('ORPHAN_REGISTER/body[1]/FATHER_NAME[1]/text()', x))[1]::varchar(60)							as FatherName
			,to_timestamp( (xpath('ORPHAN_REGISTER/body[1]/BIRTHDAY[1]/text()', x))[1]::text, 'YYYY.MM.DD')		as Birthday
			,(xpath('ORPHAN_REGISTER/body[1]/SEX[1]/text()', x))[1]::text::int									as Sex
			,(xpath('ORPHAN_REGISTER/body[1]/SNILS[1]/text()', x))[1]::varchar(14)								as SNILS
			,(xpath('ORPHAN_REGISTER/body[1]/DIASBILITY[1]/text()', x))[1]::text::int								as Disability
			,(xpath('ORPHAN_REGISTER/body[1]/ADRESS[1]/text()', x))[1]::varchar(1000)								as Adress
			,(xpath('ORPHAN_REGISTER/body[1]/OKATO[1]/text()', x))[1]::varchar(256)								as OKATO
			,(xpath('ORPHAN_REGISTER/body[1]/FEDERAL[1]/text()', x))[1]::text::boolean							as Federal
			,to_timestamp((xpath('ORPHAN_REGISTER/body[1]/DOC_ISSUE_DATE[1]/text()', x))[1]::text, 'YYYY.MM.DD')	as DocIssueDate
			,(xpath('ORPHAN_REGISTER/body[1]/DOC_ISSUE_ORG[1]/text()', x))[1]::varchar(256)						as DocIssueOrg
			,(xpath('ORPHAN_REGISTER/body[1]/DOC_TYPE[1]/text()', x))[1]::text::int								as DocType
			,(xpath('ORPHAN_REGISTER/body[1]/DOC_SERIES[1]/text()', x))[1]::varchar(30)							as DocSeries
			,(xpath('ORPHAN_REGISTER/body[1]/DOC_NUMBER[1]/text()', x))[1]::varchar(30)							as DocNumber
			,(xpath('ORPHAN_REGISTER/body[1]/SMO[1]/text()', x))[1]::varchar(5)									as F002Smo
			,(xpath('ORPHAN_REGISTER/body[1]/OMS_SERIAL[1]/text()', x))[1]::varchar(12)							as OmsSerial
			,(xpath('ORPHAN_REGISTER/body[1]/OMS_NUMBER[1]/text()', x))[1]::varchar(32)							as OmsNumber
			,(xpath('ORPHAN_REGISTER/body[1]/MKB[1]/text()', x))[1]::varchar(10)									as Mkb
			,(xpath('ORPHAN_REGISTER/body[1]/DIAGNOSIS[1]/text()', x))[1]::varchar(4096)							as Diagnosis
			,(xpath('ORPHAN_REGISTER/body[1]/MKB_DOP[1]/text()', x))[1]::varchar(10)								as MkbDop
			,(xpath('ORPHAN_REGISTER/body[1]/DIAGNOSIS_DOP[1]/text()', x))[1]::varchar(4096)						as DiagnosisDop
			,(xpath('ORPHAN_REGISTER/body[1]/LPU_MAIN_FIRST[1]/text()', x))[1]::varchar(6)						as LpuMainFirst
			,(xpath('ORPHAN_REGISTER/body[1]/LPU_MAIN[1]/text()', x))[1]::varchar(6)								as LpuMain
			,(xpath('ORPHAN_REGISTER/body[1]/POST_FIO[1]/text()', x))[1]::varchar(255)							as PostFio
			,(xpath('ORPHAN_REGISTER/body[1]/REGISTER_ID[1]/text()', x))[1]::text::int							as RegisterId
			from
				(
					select	unnest(xpath('/ORPHAN_REGISTER', "Xml"::xml)) as x
				) ORPHAN_REGISTER
			where _OperationType <> 'FTLoad';

			ALTER TABLE TMP_ORPHAN_REGISTER ADD Patient uuid;
			ALTER TABLE TMP_ORPHAN_REGISTERS ADD Patient uuid;

			-- Связываем регистр с пациентами
			-- Поиск по СНИЛС + ДР
			update TMP_ORPHAN_REGISTER orph
			set Patient = p.PatientID
			from AKUZ.T_PATIENT p
			where p.SNILS = orph.SNILS and p.Birthday = orph.Birthday and
				orph.Patient is null
				and orph.SNILS is not null
				and orph.Birthday is not null;

			-- Поиск по серии и номеру документа
			update TMP_ORPHAN_REGISTER orph
			set Patient = p.PatientID
			from AKUZ.T_PATIENT p 
			where LEFT(p.DocSeries, 8) = orph.DocSeries and LEFT(p.DocNumber, 8) = orph.DocNumber and p.Birthday = orph.Birthday and
				orph.Patient is null
				and orph.DocSeries is not null
			    and orph.DocNumber is not null
			    and orph.Birthday is not null;

			-- Поиск по ФИО + ДР
			update TMP_ORPHAN_REGISTER orph
			set Patient = p.PatientID
			from AKUZ.T_PATIENT p
			where p.LastName = orph.LastName and p.FirstName = orph.FirstName and (p.FatherName = orph.FatherName or p.FatherName is null and orph.FatherName is null) and p.Birthday = orph.Birthday and orph.Patient is null;

			-- Поиск по СНИЛС + ДР
			update TMP_ORPHAN_REGISTERS orph
			set Patient = p.PatientID
			from AKUZ.T_PATIENT p 
			where p.SNILS = orph.SNILS and p.Birthday = orph.Birthday and
				orph.Patient is null
				and orph.SNILS is not null
			    and orph.Birthday is not null;

			-- Поиск по серии и номеру документа
			update TMP_ORPHAN_REGISTERS orph
			set Patient = p.PatientID
			from AKUZ.T_PATIENT p
			where LEFT(p.DocSeries, 8) = orph.DocSeries and LEFT(p.DocNumber, 8) = orph.DocNumber and p.Birthday = orph.Birthday and
				orph.Patient is null
				and orph.DocSeries is not null
			    and orph.DocNumber is not null
			    and orph.Birthday is not null;

			-- Поиск по ФИО + ДР
			update TMP_ORPHAN_REGISTERS orph
			set Patient = p.PatientID
			from AKUZ.T_PATIENT p 
			where p.LastName = orph.LastName and p.FirstName = orph.FirstName and (p.FatherName = orph.FatherName or p.FatherName is null and orph.FatherName is null) and p.Birthday = orph.Birthday and orph.Patient is null;

			if (_OperationType = 'FTLoad')
			then

				delete from AKUZ.T_PATIENT_BENEFITS pd 
					using AKUZ.T_BENEFITS b
				where b.BenefitsID = pd.Benefits and b.BenefitViews = 19011 and CreateType = 2;

				INSERT INTO AKUZ.T_PATIENT_BENEFITS
			           (PatientBenefitsID
			           ,Patient
			           ,Benefits
			           ,BenefitDocument
			           ,BenefitDocumentNumber
			           ,BeginDate
			           ,EndDate
			           ,Mkb
			           ,Active
			           ,Deleted
			           ,CreateType
			           ,PAC_ID
			           ,LPU_INF
			           ,SOST_R
			           ,ReasonRegistration
			           ,ReasonDeregistration
			           ,BenefitDocumentSeries
			           ,BenefitDocType
			           ,RegDate)
			     SELECT
			           gen_random_uuid()
			           ,orph.Patient
			           ,(select b.BenefitsID from AKUZ.T_BENEFITS b where b.BenefitViews = 19011 limit 1)
			           ,null
			           ,null
			           ,orph.DateBegin
			           ,orph.DateEnd
			           ,(select m.MkbID from AKUZ.T_MKB m where orph.Mkb = m.MCBCode limit 1)
			           ,'1'
			           ,'0'
			           ,2
			           ,orph.RegisterId
			           ,orph.LpuMain
			           ,null
			           ,null
			           ,null
			           ,null
			           ,null
			           ,orph.DateBegin
					   FROM TMP_ORPHAN_REGISTERS orph
					   where orph.Patient is not null;

			elsif(_OperationType = 'Delete')
			then

				delete from AKUZ.T_PATIENT_BENEFITS pd 
					using AKUZ.T_BENEFITS b 
					join TMP_ORPHAN_REGISTER orph on orph.RegisterId = pd.PAC_ID
				where b.BenefitsID = pd.Benefits and b.BenefitViews = 19011 and pd.CreateType = 2;

			ELSE
				delete from AKUZ.T_PATIENT_BENEFITS pd 
					using AKUZ.T_BENEFITS b
					join TMP_ORPHAN_REGISTER orph on orph.RegisterId = pd.PAC_ID
				where b.BenefitsID = pd.Benefits and b.BenefitViews = 19011 and pd.CreateType = 2;

				INSERT INTO AKUZ.T_PATIENT_BENEFITS
			           (PatientBenefitsID
			           ,Patient
			           ,Benefits
			           ,BenefitDocument
			           ,BenefitDocumentNumber
			           ,BeginDate
			           ,EndDate
			           ,Mkb
			           ,Active
			           ,Deleted
			           ,CreateType
			           ,PAC_ID
			           ,LPU_INF
			           ,SOST_R
			           ,ReasonRegistration
			           ,ReasonDeregistration
			           ,BenefitDocumentSeries
			           ,BenefitDocType
			           ,RegDate)
			     SELECT
			           gen_random_uuid()
			           ,orph.Patient
			           ,(select b.BenefitsID from AKUZ.T_BENEFITS b where b.BenefitViews = 19011 limit 1)
			           ,null
			           ,null
			           ,orph.DateBegin
			           ,orph.DateEnd
			           ,(select m.MkbID from AKUZ.T_MKB m where orph.Mkb = m.MCBCode limit 1)
			           ,'1'
			           ,'0'
			           ,2
			           ,orph.RegisterId
			           ,orph.LpuMain
			           ,null
			           ,null
			           ,null
			           ,null
			           ,null
			           ,orph.DateBegin
					   FROM TMP_ORPHAN_REGISTER orph
					   where orph.Patient is not null;

			END if;

		DROP TABLE TMP_ORPHAN_REGISTER;
		DROP TABLE TMP_ORPHAN_REGISTERS;
        end if;
    End;
End;
$$;