IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_GetMilkRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_GetMilkRegister]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2022-03-16
-- Description: Загрузка молочного регистра.
-- =============================================
CREATE PROCEDURE [dbo].[sp_GetMilkRegister]
    @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('MILK_REGISTER') T(c)

        -- Generate table #MILK_REGISTER
        select t.c.value('./RegisterID[1]', 'int')                                   as [RegisterID]
              ,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]
              ,t.c.value('./DocSeries[1]', 'varchar(16)')                            as [DocSeries]
              ,t.c.value('./DocNumber[1]', 'varchar(16)')                            as [DocNumber]
              ,t.c.value('./Sex[1]', 'int')                                          as [Sex]
              ,t.c.value('./Snils[1]', 'varchar(14)')                                as [Snils]
              ,t.c.value('./DocType[1]', 'int')                                      as [DocType]
			  ,t.c.value('./Polis[1]', 'varchar(255)') 								 as [Polis]
			  ,t.c.value('./OKATO[1]', 'varchar(255)')								 as [OKATO]
			  ,t.c.value('./City[1]', 'varchar(255)')							     as [City]
			  ,t.c.value('./LHouse[1]', 'varchar(255)')								 as [LHouse]
			  ,t.c.value('./Block[1]', 'varchar(255)')							     as [Block]
			  ,t.c.value('./Flat[1]', 'varchar(255)')								 as [Flat]
			  ,t.c.value('./LFlat[1]', 'varchar(255)')								 as [LFlat]
			  ,t.c.value('./Room[1]', 'varchar(255)')							     as [Room]
			  ,t.c.value('./House[1]', 'varchar(255)')								 as [House]
			  ,t.c.value('./Street[1]', 'varchar(255)')								 as [Street]
			  ,t.c.value('./ExcludeReason[1]', 'int')                                as [ExcludeReason]
              ,t.c.value('./PatientId[1]', 'uniqueidentifier')                       as [PatientId]
              
            INTO #MILK_REGISTER
        from @Xml.nodes('MILK_REGISTER/body/PATIENT') T(c)
        where @OperationType = @FTLOAD

		
        -- Generate table #MILK_BENEFITS
        select t.c.value('./RegisterID[1]', 'int')                                as [RegisterID]
              ,convert(datetime, t.c.value('./DiagDate[1]', 'varchar(10)'), 104)  as [DiagDate]
              ,t.c.value('./Mkb[1]', 'varchar(8)')                                as [Mkb]
              ,t.c.value('./BenefitCode[1]', 'varchar(255)')                      as [BenefitCode]
              ,t.c.value('./BenefitViews[1]', 'int')                              as [BenefitViews]
              ,convert(datetime, t.c.value('./BeginDate[1]', 'varchar(10)'), 104) as [BeginDate]
              ,convert(datetime, t.c.value('./EndDate[1]', 'varchar(10)'), 104)   as [EndDate]

            INTO #MILK_BENEFITS
        from @Xml.nodes('MILK_REGISTER/body/PATIENT/BENEFITS/BENEFIT') T(c)
        where @OperationType = @FTLOAD

        -- Обработка операции
        if (@OperationType = @FTLOAD)
        BEGIN
            -- Связываем регистр с пациентами
            -- Поиск по СНИЛС + ДР
            update pr
            set pr.PatientId = p.PatientID
            from #MILK_REGISTER pr
                join [AKUZ].T_PATIENT p on p.SNILS = pr.Snils and p.Birthday = pr.Birthday
            where 
				pr.Snils is not null
				and pr.Birthday is not null

            -- Поиск по серии и номеру документа
            update pr
            set pr.PatientId = p.PatientID
            from #MILK_REGISTER pr
                join [AKUZ].T_PATIENT p on LEFT(p.DocSeries, 8) = pr.DocSeries and LEFT(p.DocNumber, 8) = pr.DocNumber and p.Birthday = pr.Birthday
            where 
				pr.PatientId is null
				and pr.DocSeries is not null
                and pr.DocNumber is not null

            -- Поиск по ФИО + ДР
            update pr
            set pr.PatientId = p.PatientID
            from #MILK_REGISTER pr
                join [AKUZ].T_PATIENT p on p.LastName = pr.LastName and p.FirstName = pr.FirstName and (p.FatherName = pr.FatherName or p.FatherName is null and pr.FatherName is null) and p.Birthday = pr.Birthday
            where pr.PatientId is null

			delete pb
            from akuz.T_PATIENT_BENEFITS pb 
			join [AKUZ].T_BENEFITS b on b.BenefitsID = pb.Benefits
			where b.BenefitViews in (19099)

            -- Загружаем новые
            INSERT INTO [AKUZ].[T_PATIENT_BENEFITS]
                       ([PatientBenefitsID] ,[Patient] ,[Benefits] ,[BeginDate] ,[EndDate] ,[Mkb] ,[Active]
                       ,[Deleted] ,[CreateType] ,[RegDate], [PAC_ID])
            SELECT
                       NEWID()--<PatientBenefitsID, uniqueidentifier,>
                       ,p.PatientID--<Patient, uniqueidentifier,>
                       ,b.BenefitsID--<Benefits, uniqueidentifier,>
                       ,pb.BeginDate--<BeginDate, datetime,>
                       ,pb.EndDate--<EndDate, datetime,>
                       ,(select top 1 m.MkbID from AKUZ.T_MKB m where m.MCBCode = pb.Mkb)--<Mkb, uniqueidentifier,>
                       ,1--<Active, bit,>
                       ,0--<Deleted, bit,>
                       ,2--<CreateType, int,>
                       ,@dateTime--<RegDate, datetime,>)
					   ,pb.RegisterID
            from #MILK_BENEFITS pb
                join #MILK_REGISTER pr on pr.RegisterID = pb.RegisterID
                join [AKUZ].T_PATIENT p on p.PatientID = pr.PatientId
                join [VCLib].T_ENUMS eBv on eBv.Code = pb.BenefitViews and eBv.EnumTypeID = 190
                join [AKUZ].T_BENEFITS b on b.BenefitCode = pb.BenefitCode and b.BenefitViews = eBv.EnumID
        END

        -- Drop tables
        DROP TABLE #MILK_REGISTER
        DROP TABLE #MILK_BENEFITS

    END
END