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_GetSetBillOfGoodsLinkPT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_GetSetBillOfGoodsLinkPT]
GO
-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2020-07-21
-- Description: Выгрузка/загрузка справочника  в(из) RDS
-- =============================================
CREATE PROCEDURE [dbo].[sp_GetSetBillOfGoodsLinkPT]
    @Xml xml = null,
    @IsNew bit = 1,
    @ID uniqueidentifier = null,
    @QueueName varchar(100) = null,
    @dateTime datetime = null,
    @User uniqueidentifier = null
AS
BEGIN

    SET NOCOUNT ON;

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

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

    IF (@Xml is null)
    BEGIN
        -- Инициализация
        select @OwnerID = @ID

        --выясняем тип операции
        IF (@ID is null)
        BEGIN
            select @OperationType = @FTLOAD
        END
        ELSE IF(@IsNew = 1)
        BEGIN
            select @OperationType = @INSERT
        END
        ELSE IF (@IsNew = 0 and exists (select * from [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE s where s.BillOfGoodsLinkPaymentTypeID = @ID))
        BEGIN
            select @OperationType = @UPDATE
        END
        ELSE IF (@IsNew = 0 and not exists (select * from [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE s where s.BillOfGoodsLinkPaymentTypeID = @ID))
        BEGIN
            select @OperationType = @DELETE
            select @Result =
            (
                select @OperationType as 'header/TYPE'
                      ,@ID            as 'header/ID'
                FOR XML PATH(''),
                ROOT('BILL_OF_GOODS_LINK_PAYMENT_TYPE')
            )
        END

        -- Обработка операции
        IF (@OperationType = @FTLOAD)
        BEGIN
            -- Первичная загрузка
            select @Result =
            (
                select @FTLOAD						as 'header/TYPE'
                      ,(
                            select s.BillOfGoodsLinkPaymentTypeID		as 'BILL_OF_GOODS_LINK_PAYMENT_TYPE/ID'
							,s.BillOfGoods								as 'BILL_OF_GOODS_LINK_PAYMENT_TYPE/BillOfGoods'
							,convert(varchar(10), s.DateBegin, 104)		as 'BILL_OF_GOODS_LINK_PAYMENT_TYPE/DateBegin'
							,convert(varchar(10), s.DateEnd, 104)		as 'BILL_OF_GOODS_LINK_PAYMENT_TYPE/DateEnd'
							,s.PaymentType								as 'BILL_OF_GOODS_LINK_PAYMENT_TYPE/PaymentType'
                            from [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE s
                            for xml path(''),
                            type
                      ) as 'body/BILL_OF_GOODS_LINK_PAYMENT_TYPES'
                for xml path(''),
                root('BILL_OF_GOODS_LINK_PAYMENT_TYPE')
            )
        END
        ELSE IF(@OperationType <> @DELETE)
        BEGIN

            -- собираем BILL_OF_GOODS_LINK_PAYMENT_TYPE
            SELECT @Result =
            (
                select @OperationType as 'header/TYPE'
                      ,@ID            as 'header/ID'

                      ,s.BillOfGoods							as 'body/BillOfGoods'
					  ,convert(varchar(10), s.DateBegin, 104)	as 'body/DateBegin'
					  ,convert(varchar(10), s.DateEnd, 104)		as 'body/DateEnd'
					  ,s.PaymentType							as 'body/PaymentType'
                from [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE s
                where s.BillOfGoodsLinkPaymentTypeID = @ID
                for xml path(''),
                root('BILL_OF_GOODS_LINK_PAYMENT_TYPE')
            )
        END

        -- Отправка
        INSERT INTO [RDS].[T_RABBIT_SEND_OBJECT]
            ([RabbitSendObjectID] ,[QueueName] ,[Content] ,[MessageID] ,[Headers] ,[ContentEncoding] ,[Type] ,[UserID] ,[State] ,[CreateDateTime] ,[OwnerID])
        select NewID()--(<RabbitSendObjectID, uniqueidentifier,>
              ,s.ServerName--,<QueueName, varchar(255),>
              ,dbo.ConvertTextToBinaryZip(@Result, '')--,<Content, text,>
              ,null--,<MessageID, varchar(255),>
              ,null--,<Headers, varchar(255),>
              ,@ContentEncoding--,<ContentEncoding, varchar(255),>
              ,@Type--,<Type, varchar(255),>
              ,@User--,<UserID, varchar(255),>
              ,0--,<State, int,>)
              ,@dateTime--,<CreateDateTime, datetime,>)
              ,@OwnerID--,<OwnerID, varchar(255),>
        from [RDS].T_SYNC_SERVERS s
        where (@QueueName is not null and s.ServerName = @QueueName)
                or
             (@QueueName is null and s.ServerType in (0, 1)) -- Рассылаем пакет всем подписанным серверам AKUZ-а и APS, если не указана очередь
    END
    ELSE
    IF (@Xml is not null)
    BEGIN

        -- Получаем тип операции
        select @OperationType = t.c.value('./header[1]/TYPE[1]', 'varchar(6)')
              ,@OwnerID = t.c.value('./header[1]/ID[1]', 'uniqueidentifier')
              ,@Result = cast(@Xml as varchar(max))
        from @Xml.nodes('BILL_OF_GOODS_LINK_PAYMENT_TYPE') T(c)


        -- Обработка операции
        if (@OperationType = @FTLOAD)
        BEGIN
            -- Generate table #BILL_OF_GOODS_LINK_PAYMENT_TYPES
            select t.c.value('./ID[1]', 'uniqueidentifier')                           as [ID]
                 , t.c.value('./BillOfGoods[1]', 'uniqueidentifier')                  as [BillOfGoods]
                 , convert(datetime, t.c.value('./DateBegin[1]', 'varchar(10)'), 104) as [DateBegin]
                 , convert(datetime, t.c.value('./DateEnd[1]', 'varchar(10)'), 104)   as [DateEnd]
                 , t.c.value('./PaymentType[1]', 'int')                               as [PaymentType]
            INTO #BILL_OF_GOODS_LINK_PAYMENT_TYPES
            from @Xml.nodes('BILL_OF_GOODS_LINK_PAYMENT_TYPE/body/BILL_OF_GOODS_LINK_PAYMENT_TYPES/BILL_OF_GOODS_LINK_PAYMENT_TYPE') T(c)

            delete from [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE

            -- Загружаем новые
            INSERT INTO [PHARM].[T_BILL_OF_GOODS_LINK_PAYMENT_TYPE]
                       (BillOfGoodsLinkPaymentTypeID,BillOfGoods,PaymentType,DateBegin,DateEnd)
            SELECT
                       nmf.ID,
                       nmf.BillOfGoods,
					   nmf.PaymentType,
					   nmf.DateBegin,
					   nmf.DateEnd
            from #BILL_OF_GOODS_LINK_PAYMENT_TYPES nmf
        END
        ELSE
            BEGIN
                -- Generate table #BILL_OF_GOODS_LINK_PAYMENT_TYPE
                select T.c.value('./header[1]/ID[1]', 'uniqueidentifier')                         as [ID]
                     , t.c.value('./body[1]/BillOfGoods[1]', 'uniqueidentifier')                  as [BillOfGoods]
                     , convert(datetime, t.c.value('./body[1]/DateBegin[1]', 'varchar(10)'), 104) as [DateBegin]
                     , convert(datetime, t.c.value('./body[1]/DateEnd[1]', 'varchar(10)'), 104)   as [DateEnd]
                     , t.c.value('./body[1]/CertificateNumber[1]', 'int')                         as [PaymentType]
                INTO #BILL_OF_GOODS_LINK_PAYMENT_TYPE
                from @Xml.nodes('BILL_OF_GOODS_LINK_PAYMENT_TYPE') T(c)

                if (@OperationType = @DELETE)
                    BEGIN
                        -- Удаление
                        delete s
                        from [PHARM].[T_BILL_OF_GOODS_LINK_PAYMENT_TYPE] s
                                 join #BILL_OF_GOODS_LINK_PAYMENT_TYPE nmf on nmf.[ID] = s.BillOfGoodsLinkPaymentTypeID
                    END
                else
                    BEGIN
                        -- update [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE
                        update s
                        set s.BillOfGoods = nmf.BillOfGoods
                          , s.PaymentType = nmf.PaymentType
                          , s.DateBegin   = nmf.DateBegin
                          , s.DateEnd     = nmf.DateEnd
                        from [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE s
                                 join #BILL_OF_GOODS_LINK_PAYMENT_TYPE nmf on nmf.ID = s.BillOfGoodsLinkPaymentTypeID
                        where @OperationType = @UPDATE

                        -- insert [PHARM].T_BILL_OF_GOODS_LINK_PAYMENT_TYPE
                        INSERT INTO [PHARM].[T_BILL_OF_GOODS_LINK_PAYMENT_TYPE]
                        (BillOfGoodsLinkPaymentTypeID, BillOfGoods, PaymentType, DateBegin, DateEnd)
                        SELECT nmf.ID,
                               nmf.BillOfGoods,
                               nmf.PaymentType,
                               nmf.DateBegin,
                               nmf.DateEnd
                        from #BILL_OF_GOODS_LINK_PAYMENT_TYPE nmf
                        where @OperationType = @INSERT
                    END
            END


        -- Отправка всем остальным подписанным серверам AKUZ-а и APS
        INSERT INTO [RDS].[T_RABBIT_SEND_OBJECT]
            ([RabbitSendObjectID] ,[QueueName] ,[Content] ,[MessageID] ,[Headers] ,[ContentEncoding] ,[Type] ,[UserID] ,[State] ,[CreateDateTime] ,[OwnerID])
        select NewID()--(<RabbitSendObjectID, uniqueidentifier,>
              ,s.ServerName--,<QueueName, varchar(255),>
              ,dbo.ConvertTextToBinaryZip(@Result, '')--,<Content, text,>
              ,null--,<MessageID, varchar(255),>
              ,null--,<Headers, varchar(255),>
              ,@ContentEncoding--,<ContentEncoding, varchar(255),>
              ,@Type--,<Type, varchar(255),>
              ,@User--,<UserID, varchar(255),>
              ,0--,<State, int,>)
              ,@dateTime--,<CreateDateTime, datetime,>)
              ,@OwnerID--,<OwnerID, varchar(255),>
        from [RDS].T_SYNC_SERVERS s
        where s.ServerName <> @QueueName
                and
            @OperationType <> @FTLOAD

    END
END
GO