-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2015-11-03
-- Description: Загрузка льготников по 12 ВЗН
-- =============================================
DROP PROCEDURE IF EXISTS sp_GetSetRDSNosology;

CREATE PROCEDURE sp_GetSetRDSNosology
(
    "Xml" xml = null    
,	"ID" uuid DEFAULT NULL::uuid
,   "QueueName" varchar(100) = 'RDSSync'
,   "DateTime" TimeStamp = null
,	"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('/NOSOLOGY/header[1]/TYPE[1]/text()',"Xml"))[1]::varchar(36);

            -- Generate table TMP_NOSOLOGYS
			Drop Table If Exists TMP_NOSOLOGYS;
            Create Temp Table TMP_NOSOLOGYS
            as
			select (xpath('./ID[1]/text()', x))[1]::text::UUID								as ID
			,(xpath('./ADRESS[1]/text()', x))[1]::varchar(256)									as Adress
			,to_timestamp((xpath('./AUTO_DATE_CHANGE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as AutoDateOfChange
			,(xpath('./CARD_STATUS[1]/text()', x))[1]::varchar(256)								as CardStatus
			,(xpath('./COMMENT[1]/text()', x))[1]::varchar(1024)									as Comment
			,to_timestamp((xpath('./CHANGE_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')		as DateOfChange
			,to_timestamp((xpath('./DECLUSION_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as DateOfDeclusion
			,to_timestamp((xpath('./INCLUSION_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as DateOfInclusion
			,(xpath('./EXECUTIVE_AUTHORITY[1]/text()', x))[1]::varchar(256)						as ExecutiveAuthority
			,(xpath('./HEAD[1]/text()', x))[1]::varchar(256)										as Head
			,(xpath('./OMS_NUMBER[1]/text()', x))[1]::varchar(30)								as OmsNumber
			,(xpath('./OMS_SERIAL[1]/text()', x))[1]::varchar(30)								as OmsSerial
			,(xpath('./OPERATION_CODE[1]/text()', x))[1]::varchar(128)							as OperationCode
			,(xpath('./UNIQUE_NUMBER[1]/text()', x))[1]::varchar(128)							as UniqueNumber
			,(xpath('./MKB[1]/text()', x))[1]::varchar(10)										as Mkb
			,(xpath('./DIAGNOSIS[1]/text()', x))[1]::varchar(4096)								as Diagnosis
			,(xpath('./DOC_SERIES[1]/text()', x))[1]::varchar(30)								as DocSeries
			,(xpath('./DOC_NUMBER[1]/text()', x))[1]::varchar(30)								as DocNumber
			,to_timestamp((xpath('./BIRTHDAY[1]/text()', x))[1]::text, 'DD.MM.YYYY')			as Birthday
			,(xpath('./FIRST_NAME[1]/text()', x))[1]::varchar(60)								as FirstName
			,(xpath('./LAST_NAME[1]/text()', x))[1]::varchar(60)									as LastName
			,(xpath('./FATHER_NAME[1]/text()', x))[1]::varchar(60)								as FatherName
			,to_timestamp((xpath('./DOC_ISSUE_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as DocIssueDate
			,(xpath('./DOC_ISSUE_ORG[1]/text()', x))[1]::varchar(256)							as DocIssueOrg
			,(xpath('./DECLUSION_LPU[1]/text()', x))[1]::varchar(6)								as DeclusionLPU
			,(xpath('./DOC_TYPE[1]/text()', x))[1]::text::int											as DocumentType
			,(xpath('./EX178[1]/text()', x))[1]::text::int												as ExemptionBy178
			,(xpath('./EX890[1]/text()', x))[1]::text::int												as ExemptionBy890
			,(xpath('./INCLUSION_LPU[1]/text()', x))[1]::varchar(6)								as InclusionLPU
			,(xpath('./REGION[1]/text()', x))[1]::varchar(13)									as Region
			,(xpath('./SEX[1]/text()', x))[1]::text::int												as Sex
			,(xpath('./RF_ACCOUNT[1]/text()', x))[1]::text::int										as SubjectOfRFAccounted
			,(xpath('./SNILS[1]/text()', x))[1]::varchar(14)										as SNILS
			,(xpath('./BENIFITS[1]/text()', x))[1]::varchar(500)									as Benefits
			,(xpath('./BIRTHDAY_LAST_NAME[1]/text()', x))[1]::varchar(60)						as BirthdayLastName
			,(xpath('./DIASBILITY[1]/text()', x))[1]::text::int										as Disability
			,(xpath('./THERAPY_RESISTANCE[1]/text()', x))[1]::text::int								as TherapyResistance
			,to_timestamp((xpath('./DEATH_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')		as DeathDate
			,(xpath('./OKATO[1]/text()', x))[1]::varchar(20)									as OKATO
			,(xpath('./SMO[1]/text()', x))[1]::varchar(5)										as F002Smo
			from
				(
					select	unnest(xpath('/NOSOLOGY/body/NOSOLOGY_ITEMS/NOSOLOGY_ITEM', "Xml"::xml)) as x
				) t
			where _OperationType = 'FTLoad';

			-- Generate table TMP_NOSOLOGY
			Drop Table If Exists TMP_NOSOLOGY;
            Create Temp Table TMP_NOSOLOGY
            as
			select (xpath('./header[1]/ID[1]/text()', x))[1]::text::UUID							as ID
			,(xpath('./body[1]/ADRESS[1]/text()', x))[1]::varchar(256)									as Adress
			,to_timestamp((xpath('./body[1]/AUTO_DATE_CHANGE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as AutoDateOfChange
			,(xpath('./body[1]/CARD_STATUS[1]/text()', x))[1]::varchar(256)								as CardStatus
			,(xpath('./body[1]/COMMENT[1]/text()', x))[1]::varchar(1024)									as Comment
			,to_timestamp((xpath('./body[1]/CHANGE_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')		as DateOfChange
			,to_timestamp((xpath('./body[1]/DECLUSION_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as DateOfDeclusion
			,to_timestamp((xpath('./body[1]/INCLUSION_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as DateOfInclusion
			,(xpath('./body[1]/EXECUTIVE_AUTHORITY[1]/text()', x))[1]::varchar(256)						as ExecutiveAuthority
			,(xpath('./body[1]/HEAD[1]/text()', x))[1]::varchar(256)										as Head
			,(xpath('./body[1]/OMS_NUMBER[1]/text()', x))[1]::varchar(30)								as OmsNumber
			,(xpath('./body[1]/OMS_SERIAL[1]/text()', x))[1]::varchar(30)								as OmsSerial
			,(xpath('./body[1]/OPERATION_CODE[1]/text()', x))[1]::varchar(128)							as OperationCode
			,(xpath('./body[1]/UNIQUE_NUMBER[1]/text()', x))[1]::varchar(128)							as UniqueNumber
			,(xpath('./body[1]/MKB[1]/text()', x))[1]::varchar(10)										as Mkb
			,(xpath('./body[1]/DIAGNOSIS[1]/text()', x))[1]::varchar(4096)								as Diagnosis
			,(xpath('./body[1]/DOC_SERIES[1]/text()', x))[1]::varchar(30)								as DocSeries
			,(xpath('./body[1]/DOC_NUMBER[1]/text()', x))[1]::varchar(30)								as DocNumber
			,to_timestamp((xpath('./body[1]/BIRTHDAY[1]/text()', x))[1]::text, 'DD.MM.YYYY')			as Birthday
			,(xpath('./body[1]/FIRST_NAME[1]/text()', x))[1]::varchar(60)								as FirstName
			,(xpath('./body[1]/LAST_NAME[1]/text()', x))[1]::varchar(60)									as LastName
			,(xpath('./body[1]/FATHER_NAME[1]/text()', x))[1]::varchar(60)								as FatherName
			,to_timestamp((xpath('./body[1]/DOC_ISSUE_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as DocIssueDate
			,(xpath('./body[1]/DOC_ISSUE_ORG[1]/text()', x))[1]::varchar(256)							as DocIssueOrg
			,(xpath('./body[1]/DECLUSION_LPU[1]/text()', x))[1]::varchar(6)								as DeclusionLPU
			,(xpath('./body[1]/DOC_TYPE[1]/text()', x))[1]::text::int											as DocumentType
			,(xpath('./body[1]/EX178[1]/text()', x))[1]::text::int												as ExemptionBy178
			,(xpath('./body[1]/EX890[1]/text()', x))[1]::text::int												as ExemptionBy890
			,(xpath('./body[1]/INCLUSION_LPU[1]/text()', x))[1]::varchar(6)								as InclusionLPU
			,(xpath('./body[1]/REGION[1]/text()', x))[1]::varchar(13)									as Region
			,(xpath('./body[1]/SEX[1]/text()', x))[1]::text::int												as Sex
			,(xpath('./body[1]/RF_ACCOUNT[1]/text()', x))[1]::text::int										as SubjectOfRFAccounted
			,(xpath('./body[1]/SNILS[1]/text()', x))[1]::varchar(14)										as SNILS
			,(xpath('./body[1]/BENIFITS[1]/text()', x))[1]::varchar(500)									as Benefits
			,(xpath('./body[1]/BIRTHDAY_LAST_NAME[1]/text()', x))[1]::varchar(60)						as BirthdayLastName
			,(xpath('./body[1]/DIASBILITY[1]/text()', x))[1]::text::int										as Disability
			,(xpath('./body[1]/THERAPY_RESISTANCE[1]/text()', x))[1]::text::int								as TherapyResistance
			,to_timestamp((xpath('./body[1]/DEATH_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')			as DeathDate
			,(xpath('./body[1]/OKATO[1]/text()', x))[1]::varchar(20)									as OKATO
			,(xpath('./body[1]/SMO[1]/text()', x))[1]::varchar(5)										as F002Smo
			from
				(
					select	unnest(xpath('/NOSOLOGY', "Xml"::xml)) as x
				) t
			where _OperationType <> 'FTLoad';

			ALTER TABLE TMP_NOSOLOGY ADD Patient uuid;
			ALTER TABLE TMP_NOSOLOGYS ADD Patient uuid;

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

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

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

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

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

			 -- Поиск по ФИО + ДР
			 update TMP_NOSOLOGYS nos
			 set Patient = p.PatientID
			 from AKUZ.T_PATIENT p
			 where p.LastName = nos.LastName and p.FirstName = nos.FirstName and (p.FatherName = nos.FatherName or p.FatherName is null and nos.FatherName is null) and p.Birthday = nos.Birthday and nos.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 = 19006 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
			           uuid_generate_v4()
			           ,nos.Patient
			           ,(select b.BenefitsID from AKUZ.T_BENEFITS b 
					   where b.BenefitCode = nos.Benefits and b.BenefitViews = 19006 limit 1)
			           ,null
			           ,null
			           ,nos.DateOfInclusion
			           ,nos.DateOfDeclusion
			           ,(select m.MkbID from AKUZ.T_MKB m where nos.Mkb = m.MCBCode limit 1)
			           ,'1'
			           ,'0'
			           ,2
			           ,nos.UniqueNumber
			           ,nos.InclusionLPU
			           ,null
			           ,null
			           ,null
			           ,null
			           ,null
			           ,nos.DateOfInclusion
					   FROM TMP_NOSOLOGYS nos
					   where nos.Patient is not null;

			elsif(_OperationType = 'Delete')
			then

			delete from AKUZ.T_PATIENT_BENEFITS pd 
				using AKUZ.T_BENEFITS b
				join TMP_NOSOLOGY nos on nos.Patient = pd.Patient
			where b.BenefitsID = pd.Benefits and b.BenefitViews = 19006 and pd.CreateType = 2 and b.BenefitCode = nos.Benefits;
			
			ELSE
				delete from AKUZ.T_PATIENT_BENEFITS pd 
					using AKUZ.T_BENEFITS b
					join TMP_NOSOLOGY nos on nos.Patient = pd.Patient
				where b.BenefitsID = pd.Benefits and b.BenefitViews = 19006 and pd.CreateType = 2 and b.BenefitCode = nos.Benefits;

				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
			           uuid_generate_v4()
			           ,nos.Patient
			           ,(select b.BenefitsID from AKUZ.T_BENEFITS b 
					   where b.BenefitCode = nos.Benefits and b.BenefitViews = 19006 limit 1)
			           ,null
			           ,null
			           ,nos.DateOfInclusion
			           ,nos.DateOfDeclusion
			           ,(select m.MkbID from AKUZ.T_MKB m where nos.Mkb = m.MCBCode limit 1)
			           ,'1'
			           ,'0'
			           ,2
			           ,nos.UniqueNumber
			           ,nos.InclusionLPU
			           ,null
			           ,null
			           ,null
			           ,null
			           ,null
			           ,nos.DateOfInclusion
					   FROM TMP_NOSOLOGY nos
					   where nos.Patient is not null;
			END if;

		DROP TABLE TMP_NOSOLOGY;
		DROP TABLE TMP_NOSOLOGYS;
        end if;
    End;
End;
$$;