-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2024-06-21
-- Description: Загрузка регистра БСК.
-- =============================================
DROP PROCEDURE IF EXISTS DBO.sp_getbskregister;

CREATE OR REPLACE PROCEDURE APS.sp_getbskregister
(
	"Xml" text DEFAULT null
,	"IsNew" integer = 1
,	"ID" uuid DEFAULT NULL::uuid
,	"QueueName" character varying DEFAULT 'RDSSync'::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
		"dateTime" := Coalesce("dateTime", Current_TimeStamp::TIMESTAMP);
        IF ("Xml" is not null)
        then
            
            -- Получаем тип операции		
			_OperationType := (xpath('/BSK_REGISTER/header[1]/TYPE[1]/text()', "Xml"::xml))[1]::varchar(36);

            -- Generate table Tmp_BSK_REGISTER
			Drop Table If Exists Tmp_BSK_REGISTER;
            Create Temp Table Tmp_BSK_REGISTER
            as
            select (xpath('/PATIENT/RegisterID[1]/text()', t.x))[1]::text::int                                    as RegisterID
                  ,(xpath('/PATIENT/LastName[1]/text()', t.x))[1]::varchar(40)                                    as LastName
                  ,(xpath('/PATIENT/FirstName[1]/text()', t.x))[1]::varchar(40)                                   as FirstName
                  ,(xpath('/PATIENT/FatherName[1]/text()', t.x))[1]::varchar(40)                                  as FatherName
                  ,to_timestamp((xpath('/PATIENT/Birthday[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')               as Birthday
                  ,(xpath('/PATIENT/Kod[1]/text()', t.x))[1]::varchar(32)		                                  as Kod
                  ,(xpath('/PATIENT/DocSeries[1]/text()', t.x))[1]::varchar(8)                                    as DocSeries
                  ,(xpath('/PATIENT/DocNumber[1]/text()', t.x))[1]::varchar(8)                                    as DocNumber
                  ,(xpath('/PATIENT/Sex[1]/text()', t.x))[1]::text::int                                           as Sex
                  ,(xpath('/PATIENT/Snils[1]/text()', t.x))[1]::varchar(14)                                       as Snils
                  ,to_timestamp((xpath('/PATIENT/DateBegin[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')              as DateBegin
                  ,to_timestamp((xpath('/PATIENT/DateEnd[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')                as DateEnd
                  ,to_timestamp((xpath('/PATIENT/LastEditDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')           as LastEditDate
                  ,(xpath('/PATIENT/Lpu[1]/text()', t.x))[1]::varchar(6)                                          as Lpu
                  ,(xpath('/PATIENT/ExcludeReason[1]/text()', t.x))[1]::text::int                                 as ExcludeReason
                  ,(xpath('/PATIENT/DocType[1]/text()', t.x))[1]::text::int                                       as DocType
                  ,(xpath('/PATIENT/PatientId[1]/text()', t.x))[1]::text::UUID                                    as PatientId
                  ,(xpath('/PATIENT/BirthSurname[1]/text()', t.x))[1]::varchar(40)                                as BirthSurname
                  ,to_timestamp((xpath('/PATIENT/DocIssueDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')           as DocIssueDate
                  ,(xpath('/PATIENT/Enp[1]/text()', t.x))[1]::varchar(16)                                         as Enp
                  ,(xpath('/PATIENT/DocIssueOrg[1]/text()', t.x))[1]::varchar(256)                                as DocIssueOrg
                  ,(xpath('/PATIENT/RealFiasAddress[1]/text()', t.x))[1]::varchar(36)                             as RealFiasAddress
                  ,(xpath('/PATIENT/RealFiasHome[1]/text()', t.x))[1]::varchar(36)                                as RealFiasHome
                  ,(xpath('/PATIENT/RealCity[1]/text()', t.x))[1]::varchar(100)                                   as RealCity
                  ,(xpath('/PATIENT/RealCityPrefix[1]/text()', t.x))[1]::varchar(10)                              as RealCityPrefix
                  ,(xpath('/PATIENT/RealStreet[1]/text()', t.x))[1]::varchar(100)                                 as RealStreet
                  ,(xpath('/PATIENT/RealStreetPrefix[1]/text()', t.x))[1]::varchar(10)                            as RealStreetPrefix
                  ,(xpath('/PATIENT/RealHouse[1]/text()', t.x))[1]::varchar(100)                                  as RealHouse
                  ,(xpath('/PATIENT/RealBuild[1]/text()', t.x))[1]::varchar(100)                                  as RealBuild
                  ,(xpath('/PATIENT/RealStruc[1]/text()', t.x))[1]::varchar(100)                                  as RealStruc
                  ,(xpath('/PATIENT/RealRoom[1]/text()', t.x))[1]::varchar(100)                                   as RealRoom
                  ,to_timestamp((xpath('/PATIENT/RealLiveStartDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')      as RealLiveStartDate
                  ,to_timestamp((xpath('/PATIENT/RealLiveEndDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')        as RealLiveEndDate
                  ,(xpath('/PATIENT/LegalFiasAddress[1]/text()', t.x))[1]::varchar(100)                           as LegalFiasAddress
                  ,(xpath('/PATIENT/LegalFiasHome[1]/text()', t.x))[1]::varchar(100)                              as LegalFiasHome
                  ,(xpath('/PATIENT/LegalCity[1]/text()', t.x))[1]::varchar(100)                                  as LegalCity
                  ,(xpath('/PATIENT/LegalCityPrefix[1]/text()', t.x))[1]::varchar(100)                            as LegalCityPrefix
                  ,(xpath('/PATIENT/LegalStreet[1]/text()', t.x))[1]::varchar(100)                                as LegalStreet
                  ,(xpath('/PATIENT/LegalStreetPrefix[1]/text()', t.x))[1]::varchar(100)                          as LegalStreetPrefix
                  ,(xpath('/PATIENT/LegalHouse[1]/text()', t.x))[1]::varchar(100)                                 as LegalHouse
                  ,(xpath('/PATIENT/LegalBuild[1]/text()', t.x))[1]::varchar(100)                                 as LegalBuild
                  ,(xpath('/PATIENT/LegalStruc[1]/text()', t.x))[1]::varchar(100)                                 as LegalStruc
                  ,(xpath('/PATIENT/LegalRoom[1]/text()', t.x))[1]::varchar(100)                                  as LegalRoom
                  ,to_timestamp((xpath('/PATIENT/LegalLiveStartDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')     as LegalLiveStartDate
                  ,to_timestamp((xpath('/PATIENT/LegalLiveEndDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')       as LegalLiveEndDate
                  ,(xpath('/PATIENT/CitizenShip[1]/text()', t.x))[1]::text::int                                   as CitizenShip
                  ,eh1.EhrRusID                                                                                   as EhrRus5o5e88vhc6
            from
    		(
    		    select	unnest(xpath('BSK_REGISTER/body[1]/PATIENT', "Xml"::xml)) as x
    		) t
            left join lateral (
		    	select n1.EhrRusID
		    	from EHR.T_EHR_RUS_5O5E88VHC6 n1
					LEFT JOIN EHR.T_EHR_RUS_REF_BOOKS RRB ON RRB.EhrRusRefBooksID = n1.EhrRusRefBooks
				where n1.CodeEHR = (xpath('PATIENT/EhrRus5o5e88vhc6[1]/text()', x))[1]::varchar(255) and RRB.CURRVERSION = (xpath('PATIENT/EhrRus5o5e88vhc6Ver[1]/text()', x))[1]::varchar(255) 
                limit 1
		    ) eh1 on true;

	    	
            -- Generate table Tmp_BSK_BENEFITS
			Drop Table If Exists Tmp_BSK_BENEFITS;
            Create Temp Table Tmp_BSK_BENEFITS
            as
            select (xpath('/BENEFITS/RegisterID[1]/text()', t.x))[1]::text::int									as RegisterID
                  ,(xpath('/BENEFITS/BenID[1]/text()', t.x))[1]::text::UUID									    as BenID
                  ,to_timestamp((xpath('/BENEFITS/DiagDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')			as DiagDate
                  ,(xpath('/BENEFITS/Document[1]/text()', t.x))[1]::varchar(16)									as Document
                  ,to_timestamp((xpath('/BENEFITS/DocumentDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')        as DocumentDate
                  ,(xpath('/BENEFITS/Mkb[1]/text()', t.x))[1]::varchar(8)										as Mkb
                  ,(xpath('/BENEFITS/BenefitCode[1]/text()', t.x))[1]::varchar(255)								as BenefitCode
                  ,(xpath('/BENEFITS/BenefitViews[1]/text()', t.x))[1]::text::int								as BenefitViews
                  ,to_timestamp((xpath('/BENEFITS/BeginDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')		    as BeginDate
                  ,to_timestamp((xpath('/BENEFITS/EndDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')		        as EndDate
                  ,(xpath('/BENEFITS/Lpu[1]/text()', t.x))[1]::varchar(6)										as Lpu
                  ,(xpath('/BENEFITS/ServiceCode[1]/text()', t.x))[1]::varchar(20)								as ServiceCode
                  ,(xpath('/BENEFITS/ServiceName[1]/text()', t.x))[1]::varchar(255)								as ServiceName
                  ,(xpath('/BENEFITS/ExclusionReason[1]/text()', t.x))[1]::text::int							as ExclusionReason
                  ,to_timestamp((xpath('/BENEFITS/EstimatedDDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')      as EstimatedDDate
                  ,to_timestamp((xpath('/BENEFITS/DRegistrationDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')   as DRegistrationDate
                  ,(xpath('/BENEFITS/Place[1]/text()', t.x))[1]::text::int										as Place
                  ,(xpath('/BENEFITS/LpuTo[1]/text()', t.x))[1]::varchar(6)										as LpuTo
                  ,to_timestamp((xpath('/BENEFITS/CloseDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')			as CloseDate
            from
    		(
    		    select	unnest(xpath('BSK_REGISTER/body[1]/PATIENT/BENEFITS', "Xml"::xml)) as x
    		) t;	

	    	-- Generate table Tmp_BSK_MEDICAMENTS
			Drop Table If Exists Tmp_BSK_MEDICAMENTS;
            Create Temp Table Tmp_BSK_MEDICAMENTS
            as
            select (xpath('(MEDICAMENTS/BenID[1]/text()', t.x))[1]::text::UUID							        BenID
                  ,(xpath('(MEDICAMENTS/Mnn[1]/text()', t.x))[1]::text::int									    Mnn
                  ,to_timestamp((xpath('(MEDICAMENTS/DateStart[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')          DateStart
                  ,to_timestamp((xpath('(MEDICAMENTS/EndDate[1]/text()', t.x))[1]::text, 'DD.MM.YYYY')            EndDate
                  ,(xpath('(MEDICAMENTS/MedicationForms[1]/text()', t.x))[1]::text::UUID				            MedicationForms
                  ,(xpath('(MEDICAMENTS/Regiment[1]/text()', t.x))[1]::varchar(255)                               Regiment
                  ,(xpath('(MEDICAMENTS/Dose[1]/text()', t.x))[1]::decimal(31,10)                                 Dose
                  ,(xpath('(MEDICAMENTS/Prepid[1]/text()', t.x))[1]::text::int								    Prepid
                  ,(xpath('(MEDICAMENTS/DayliCoeff[1]/text()', t.x))[1]::decimal(31,10)                           DayliCoeff
                  ,(xpath('(MEDICAMENTS/MeasureUnit[1]/text()', t.x))[1]::varchar(255)						    MeasureUnit
                  ,(xpath('(MEDICAMENTS/MeasureUnitType[1]/text()', t.x))[1]::text::int						    MeasureUnitType
                  ,(xpath('(MEDICAMENTS/SingleDose[1]/text()', t.x))[1]::decimal(31,10)                           SingleDose
                  ,(xpath('(MEDICAMENTS/Multiplicity[1]/text()', t.x))[1]::text::int							    Multiplicity
                  ,(xpath('(MEDICAMENTS/DoseView[1]/text()', t.x))[1]::varchar(255)							    DoseView
                  ,(xpath('(MEDICAMENTS/DoseView[1]/text()', t.x))[1]::text::int								    DoseViewType
            from
    			(
    				select	unnest(xpath('BSK_REGISTER/body[0]/PATIENT/BENEFITS/MEDICAMENTS', "Xml"::xml)) as x
    			) t;	
                
            -- Обработка операции
            if _OperationType = 'FTLoad' or (select count(*) from Tmp_BSK_REGISTER) > 1
            then
                delete from APS.T_BSK_REGISTER_MEDICAMENTS;
			    delete from APS.T_BSK_REGISTER_DATA;
			    delete from APS.T_BSK_REGISTER;
            else
			    delete from APS.T_BSK_REGISTER_MEDICAMENTS meds
			    	using APS.T_BSK_REGISTER_DATA ben, APS.T_BSK_REGISTER rr, Tmp_BSK_REGISTER r
                    where
                        ben.BskRegisterDataID = meds.BskRegisterData
                        and rr.BskRegisterID = ben.BskRegister
                        and r.RegisterID = rr.PAC_ID;

			    delete from APS.T_BSK_REGISTER_DATA ben
                    using APS.T_BSK_REGISTER rr, Tmp_BSK_REGISTER r 
                    where 
                        rr.BskRegisterID = ben.BskRegister and
                        r.RegisterID = rr.PAC_ID;

			    delete from APS.T_BSK_REGISTER rr
                    using Tmp_BSK_REGISTER r 
                    where 
                        r.RegisterID = rr.PAC_ID;
            end if;
            
            INSERT INTO APS.T_BSK_REGISTER
			(
                BskRegisterID
			    ,ExcludeReason
			    ,LastEditDate
			    ,LastName
			    ,FirstName
			    ,FatherName
			    ,Birthday
			    ,Kod
			    ,DocSeries
			    ,DocNumber
			    ,PAC_ID
			    ,Sex
			    ,SNILS
			    ,DocType
			    ,LpuMain
			    ,DateBegin
			    ,DateEnd
			    ,DocIssueDate
			    ,DocIssueOrg
			    ,Enp
			    ,RealFiasAddress
			    ,RealFiasHome
			    ,RealCity
			    ,RealCityPrefix
			    ,RealStreet
			    ,RealStreetPrefix
			    ,RealHouse
			    ,RealBuild
			    ,RealStruc
			    ,RealRoom
			    ,RealLiveStartDate
			    ,RealLiveEndDate
			    ,LegalFiasAddress
			    ,LegalFiasHome
			    ,LegalCity
			    ,LegalCityPrefix
			    ,LegalStreet
			    ,LegalStreetPrefix
			    ,LegalHouse
			    ,LegalBuild
			    ,LegalStruc
			    ,LegalRoom
			    ,LegalLiveStartDate
			    ,LegalLiveEndDate
			    ,CitizenShip
			    ,EhrRus5o5e88vhc6
			)
			select	
                gen_random_uuid()
				,ExcludeReason
				,LastEditDate
				,LastName
				,FirstName
				,FatherName
				,Birthday
				,Kod
				,DocSeries
				,DocNumber
				,RegisterID
				,eSex.EnumID
				,SNILS
				,e.EnumID
				,Lpu
				,DateBegin
				,DateEnd
				,DocIssueDate
				,DocIssueOrg
				,Enp
				,RealFiasAddress
				,RealFiasHome
				,RealCity
				,RealCityPrefix
				,RealStreet
				,RealStreetPrefix
				,RealHouse
				,RealBuild
				,RealStruc
				,RealRoom
				,RealLiveStartDate
				,RealLiveEndDate
				,LegalFiasAddress
				,LegalFiasHome
				,LegalCity
				,LegalCityPrefix
				,LegalStreet
				,LegalStreetPrefix
				,LegalHouse
				,LegalBuild
				,LegalStruc
				,LegalRoom
				,LegalLiveStartDate
				,LegalLiveEndDate
				,cs.EhrRusID
				,doc.EhrRusID
			from Tmp_BSK_REGISTER r
				left join vclib.T_ENUMS e on e.EnumTypeID = 105 and e.Code = r.DocType
				left join VCLib.T_ENUMS eSex on eSex.EnumTypeID = 103 and eSex.Code = r.Sex
				left join EHR.T_EHR_RUS_O00015 cs on cs.CODE = r.CitizenShip
				left join lateral (
					select doc.EhrRusID 
					from EHR.T_EHR_RUS_5O5E88VHC6 doc
						LEFT JOIN EHR.T_EHR_RUS_REF_BOOKS RRB ON RRB.EhrRusRefBooksID = doc.EhrRusRefBooks
					where doc.CodeEHR = r.EhrRus5o5e88vhc6 and RRB.CURRVERSION = r.EhrRus5o5e88vhc6Ver limit 1
				) doc on true;

			INSERT INTO APS.T_BSK_REGISTER_DATA
			(
				BskRegisterDataID
				,BskRegister
				,ServiceCode
				,ServiceName
				,DiagDate
				,Document
				,DocumentDate
				,Mkb
				,Benefits
				,BeginDate
				,EndDate
				,ExclusionReason
				,EstimatedDDate
				,DRegistrationDate
				,Place
				,LpuMainTo
				,CloseDate
				,LpuMain
				,LastEditDate
			)
			select		
				b.BenID
				,r.BskRegisterID
				,ServiceCode
				,ServiceName
				,DiagDate
				,Document
				,DocumentDate
				,Mkb
				,bb.BenefitsID
				,BeginDate
				,EndDate
			    ,b.ExclusionReason
			    ,b.EstimatedDDate
			    ,b.DRegistrationDate
			    ,b.Place
			    ,b.LpuTo
				,b.CloseDate
				,b.Lpu
				,current_date
			from Tmp_BSK_BENEFITS b
				join APS.T_BSK_REGISTER r on r.PAC_ID = b.RegisterID
				left join VCLib.T_ENUMS e on e.EnumTypeID = 190 and e.Code = b.BenefitViews
				left join APS.T_BENEFITS bb on bb.BenefitCode = b.BenefitCode and bb.BenefitViews = e.EnumID;

			
			INSERT INTO APS.T_BSK_REGISTER_MEDICAMENTS
		    (
				BskRegisterMedicamentsID
				,BskRegisterData
				,CMnn
				,DateStart
				,EndDate
				,MedicationForms
				,Regiment
				,Dose
				,MeasureUnit
				,Prepid
				,DayliCoeff
				,SingleDose
				,Multiplicity
				,DoseView
			)
		    select 
				gen_random_uuid()
				,meds.BenID
				,(select CMnnID 
					from PHARm.T_C_MNN 
					where OtherID = meds.Mnn limit 1)
				,meds.DateStart
				,meds.EndDate
				,meds.MedicationForms
				,meds.Regiment
				,meds.Dose
				,(select dw.Code 
					from PHARM.T_DOSE_VIEW dw 
					where dw.Name = meds.MeasureUnit and dw.ViewType = meds.MeasureUnitType limit 1)
				,meds.Prepid
				,meds.DayliCoeff
				,meds.SingleDose
				,meds.Multiplicity
				,(select dw.Code 
					from PHARM.T_DOSE_VIEW dw 
					where dw.Name = meds.DoseView and dw.ViewType = meds.DoseViewType limit 1)
		     from Tmp_BSK_MEDICAMENTS meds;

            -- Drop tables
            DROP TABLE Tmp_BSK_REGISTER;
            DROP TABLE Tmp_BSK_BENEFITS;
	    	DROP TABLE Tmp_BSK_MEDICAMENTS;
        end if;
    End;
End;
$$;