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

        -- Обработка операции
        if (@OperationType = @FTLOAD)
        BEGIN
            -- Generate table #RR_PATIENT_BENEFITS
            SELECT t.c.value('./RrPatient[1]', 'int')                                    AS RrPatient,
                   CONVERT(DATETIME, t.c.value('./DiagDate[1]', 'varchar(10)'), 104)     AS DiagDate,
                   t.c.value('./Document[1]', 'varchar(16)')                             AS Document,
                   CONVERT(DATETIME, t.c.value('./DocumentDate[1]', 'varchar(10)'), 104) AS DocumentDate,
                   t.c.value('./Dop[1]', 'varchar(1)')                                   AS Dop,
                   t.c.value('./Mkb[1]', 'varchar(8)')                                   AS Mkb,
                   CONVERT(DATETIME, t.c.value('./BeginDate[1]', 'varchar(10)'), 104)    AS BeginDate,
                   CONVERT(DATETIME, t.c.value('./EndDate[1]', 'varchar(10)'), 104)      AS EndDate,
                   t.c.value('./BenefitCode[1]', 'varchar(255)')                         AS BenefitCode,
                   t.c.value('./BenefitViews[1]', 'int')                                 AS BenefitViews,
                   t.c.value('./Lpu[1]', 'varchar(6)')                                   AS Lpu,
                   CONVERT(DATETIME, t.c.value('./LastEditDate[1]', 'varchar(10)'), 104) AS LastEditDate,
                   t.c.value('./Post[1]', 'varchar(10)')                                 AS Post,
                   t.c.value('./DivisionManager[1]', 'varchar(10)')                      AS DivisionManager
            INTO #RR_PATIENT_BENEFITS
            FROM @Xml.nodes('RR_PATIENT_BENEFIT/body/RR_PATIENT_BENEFITS/RR_PATIENT_BENEFIT') T(c)

            -- Первичная загрузка
            delete pb
            from akuz.T_PATIENT_BENEFITS pb
				join [AKUZ].T_BENEFITS b on b.BenefitsID = pb.Benefits
			where b.BenefitViews in (19002,19003,19005)

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