SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_RR_Patients]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RR_Patients]
GO
-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2015-11-13
-- Description: Загрузка регистра региональных льготников.
-- =============================================
CREATE PROCEDURE [dbo].[sp_RR_Patients]
    @Xml xml = null
    ,@ID uniqueidentifier = null
    ,@QueueName varchar(100) = 'RDSSync'
    ,@dateTime datetime = null
    ,@User uniqueidentifier = null
AS
BEGIN
    SET NOCOUNT ON;

    declare @Result varchar(max)
           ,@ContentEncoding varchar(255)
           ,@Type varchar(255)
           ,@OperationType varchar(255)
           ,@OwnerID uniqueidentifier
            -- Operation types
           ,@INSERT varchar(6)
           ,@UPDATE varchar(6)
           ,@DELETE varchar(6)
           ,@FTLOAD varchar(6)

    select @dateTime = ISNULL(@dateTime, GETDATE())
            -- Operation types
          ,@INSERT = 'Insert'
          ,@UPDATE = 'Update'
          ,@DELETE = 'Delete'
          ,@FTLOAD = 'FTLoad'

    IF (@Xml is not null)
    BEGIN
        
        -- Получаем тип операции
        select @OperationType = t.c.value('./header[1]/TYPE[1]', 'varchar(6)')
        from @Xml.nodes('RR_PATIENT') T(c)

        -- Generate table #RR_PATIENTS
        select t.c.value('./RrPatientID[1]', 'int')											as [RrPatientID]
              ,t.c.value('./Snils[1]', 'varchar(14)')										as [Snils]
              ,t.c.value('./DocSeries[1]', 'varchar(16)')									as [DocSeries]
              ,t.c.value('./DocNumber[1]', 'varchar(16)')									as [DocNumber]
              ,t.c.value('./LastName[1]', 'varchar(40)')									as [LastName]
              ,t.c.value('./FirstName[1]', 'varchar(40)')									as [FirstName]
              ,t.c.value('./FatherName[1]', 'varchar(40)')									as [FatherName]
              ,convert(datetime, t.c.value('./Birthday[1]', 'varchar(10)'), 104)			as [Birthday]
              ,convert(datetime, t.c.value('./DateBegin[1]', 'varchar(10)'), 104)			as [DateBegin]
              ,convert(datetime, t.c.value('./DateEnd[1]', 'varchar(10)'), 104)				as [DateEnd]
              ,convert(datetime, t.c.value('./LastEditDate[1]', 'varchar(10)'), 104)		as [LastEditDate]
              ,t.c.value('./Sex[1]', 'int')													as [Sex]
              ,t.c.value('./Lpu[1]', 'varchar(6)')											as [Lpu]
              ,t.c.value('./ExcludeReason[1]', 'int')										as [ExcludeReason]
              ,t.c.value('./DocType[1]', 'int')												as [TIPD]
              ,t.c.value('./Kod[1]', 'varchar(32)')											as [Kod]
              ,t.c.value('./KodAdr[1]', 'varchar(11)')										as [KodAdr]
              ,convert(datetime, t.c.value('./DAT_PROV[1]', 'varchar(10)'), 104)			as [DAT_PROV]
              ,t.c.value('./BirthSurname[1]', 'varchar(40)')								as [BirthSurname]
              ,t.c.value('./LpuFirst[1]', 'varchar(6)')										as [LpuFirst]
              ,t.c.value('./SOST_R[1]', 'int')												as [SOST_R]
              ,convert(datetime, T.c.value('./DocIssueDate[1]', 'varchar(10)'), 104)		as [DocIssueDate]
              ,T.c.value('./Enp[1]', 'varchar(16)')											as [Enp]
              ,T.c.value('./DocIssueOrg[1]', 'varchar(256)')								as [DocIssueOrg]
              ,T.c.value('./RealFiasAddress[1]', 'varchar(36)')								as [RealFiasAddress]
              ,T.c.value('./RealFiasHome[1]', 'varchar(36)')								as [RealFiasHome]
              ,T.c.value('./RealCity[1]', 'varchar(100)')									as [RealCity]
              ,T.c.value('./RealCityPrefix[1]', 'varchar(10)')								as [RealCityPrefix]
              ,T.c.value('./RealStreet[1]', 'varchar(100)')									as [RealStreet]
              ,T.c.value('./RealStreetPrefix[1]', 'varchar(10)')							as [RealStreetPrefix]
              ,T.c.value('./RealHouse[1]', 'varchar(100)')									as [RealHouse]
              ,T.c.value('./RealBuild[1]', 'varchar(100)')									as [RealBuild]
              ,T.c.value('./RealStruc[1]', 'varchar(100)')									as [RealStruc]
              ,T.c.value('./RealRoom[1]', 'varchar(100)')									as [RealRoom]
              ,convert(datetime, T.c.value('./RealLiveStartDate[1]', 'varchar(10)'), 104)	as [RealLiveStartDate]
              ,convert(datetime, T.c.value('./RealLiveEndDate[1]', 'varchar(10)'), 104)		as [RealLiveEndDate]
              ,T.c.value('./LegalFiasAddress[1]', 'varchar(36)')							as [LegalFiasAddress]
              ,T.c.value('./LegalFiasHome[1]', 'varchar(36)')								as [LegalFiasHome]
              ,T.c.value('./LegalCity[1]', 'varchar(100)')									as [LegalCity]
              ,T.c.value('./LegalCityPrefix[1]', 'varchar(10)')								as [LegalCityPrefix]
              ,T.c.value('./LegalStreet[1]', 'varchar(100)')								as [LegalStreet]
              ,T.c.value('./LegalStreetPrefix[1]', 'varchar(10)')							as [LegalStreetPrefix]
              ,T.c.value('./LegalHouse[1]', 'varchar(100)')									as [LegalHouse]
              ,T.c.value('./LegalBuild[1]', 'varchar(100)')									as [LegalBuild]
              ,T.c.value('./LegalStruc[1]', 'varchar(100)')									as [LegalStruc]
              ,T.c.value('./LegalRoom[1]', 'varchar(100)')									as [LegalRoom]
              ,convert(datetime, T.c.value('./LegalLiveStartDate[1]', 'varchar(10)'), 104)  as [LegalLiveStartDate]
              ,convert(datetime, T.c.value('./LegalLiveEndDate[1]', 'varchar(10)'), 104)	as [LegalLiveEndDate]
              ,T.c.value('./CitizenShip[1]', 'int')											as [CitizenShip]
              ,T.c.value('./EhrRus5o5e88vhc6[1]', 'varchar(52)')							as [EhrRus5o5e88vhc6]
              ,T.c.value('./EhrRus5o5e88vhc6Ver[1]', 'varchar(52)')							as [EhrRus5o5e88vhc6Ver]
            INTO #RR_PATIENTS
        from @Xml.nodes('RR_PATIENT/body/RR_PATIENTS/RR_PATIENT') T(c)
        where @OperationType = @FTLOAD

        -- Обработка операции
        if (@OperationType = @FTLOAD)
        BEGIN
            -- Первичная загрузка            
            delete from [APS].[T_RR_PATIENT_BENEFIT]
			delete from [APS].[T_RR_PATIENT]

            -- Загружаем новые
            INSERT INTO [APS].[T_RR_PATIENT]
                       (
						 [RrPatientID]
						,[SNILS]
						,[DocSeries]
						,[DocNumber]
						,[FatherName] 
						,[FirstName] 
						,[LastName] 
						,[Birthday] 
						,[Sex] 
						,[DateBegin] 
						,[DateEnd] 
						,[LastEditDate] 
						,[LastEditLpu] 
						,[ExcludeReason]
						,Kod
						,KodAdr
						,DAT_PROV
						,BirthSurname
						,LpuMainFirst
						,SOST_R
						,DocType
						,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
                       nrp.RrPatientID--<RrPatientID, int,>
                      ,nrp.Snils--<SNILS, varchar(14),>
                      ,nrp.DocSeries--<DocSeries, varchar(8),>
                      ,nrp.DocNumber--<DocNumber, varchar(8),>
                      ,nrp.FatherName--<FatherName, varchar(40),>
                      ,nrp.FirstName--<FirstName, varchar(40),>
                      ,nrp.LastName--<LastName, varchar(40),>
                      ,nrp.Birthday--<Birthday, datetime,>
                      ,eSex.EnumID--<Sex, int,>
                      ,nrp.DateBegin--<DateBegin, datetime,>
                      ,nrp.DateEnd--<DateEnd, datetime,>
                      ,nrp.LastEditDate--<LastEditDate, datetime,>
                      ,nrp.Lpu--<LastEditLpu, varchar(6),>)
                      ,nrp.ExcludeReason--<ExcludeReason, int,>)
                      ,nrp.Kod
                      ,nrp.KodAdr
                      ,nrp.DAT_PROV
                      ,nrp.BirthSurname
                      ,nrp.LpuFirst
                      ,nrp.SOST_R
                      ,e.EnumID
			          ,nrp.DocIssueDate
			          ,nrp.DocIssueOrg
			          ,nrp.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 #RR_PATIENTS nrp
                left join [VCLib].T_ENUMS eSex on eSex.Code = nrp.Sex and eSex.EnumTypeID = 103
				left join vclib.T_ENUMS e on e.EnumTypeID = 105 and e.Code = nrp.TIPD
		        left join EHR.T_EHR_RUS_O00015 cs on cs.CODE = nrp.CitizenShip
		        outer apply (
		        	select top 1 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 = nrp.EhrRus5o5e88vhc6 and RRB.CURRVERSION = nrp.EhrRus5o5e88vhc6Ver
		        ) doc

        END

        -- Drop tables
        DROP TABLE #RR_PATIENTS

    END
END
