IF EXISTS
(
	SELECT *
	FROM   sys.objects
	WHERE  object_id = OBJECT_ID(N'[dbo].[sp_GetSetAdditionalFactorsRequestCatalog]')
		   AND [type] IN(N'P', N'PC')
)
	BEGIN
		DROP PROCEDURE [dbo].[sp_GetSetAdditionalFactorsRequestCatalog];
	END;
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- ==================================================
-- Author:      Vitacore (с)
-- Create date: 2019-04-23
-- Description: Синхронизация дополнительных факторов заявочного каталога
-- ==================================================


CREATE PROCEDURE [dbo].[sp_GetSetAdditionalFactorsRequestCatalog]
		@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(255)
			,@OwnerID varchar(255)
			,@FTLOAD varchar(6);

		SELECT @dateTime = ISNULL(@dateTime, GETDATE()),
			   @FTLOAD = 'FTLoad';
		IF(@Xml IS NULL)
			BEGIN
				
				-- Инициализация
				SELECT @ContentEncoding = 'utf-8',
					   @Type = 'ADDITIONAL_FACTORS_REQUEST_CATALOG',
					   @OwnerID = @ID;

				-- Получаем тип операции
				SELECT @OperationType = @FTLOAD;

				-- собираем ADDITIONAL_FACTORS_REQUEST_CATALOG в xml
				SELECT       @Result =
				(
					SELECT   @OperationType AS 'header/TYPE',
					(
						SELECT 
								 afda.AdditionalFactorsDrugApplicationItemID	AS 'ID'
								,afda.DrugApplicationListItem					AS 'DrugApplicationListItem'
								,b.BenefitViews									AS 'BenefitViews'
								,b.BenefitCode									AS 'BenefitCode'
						FROM   [RDS].[T_ADDITIONAL_FACTORS_DRUG_APPLICATION_ITEM] afda
							JOIN [RDS].[T_DRUG_APPLICATION_LIST_ITEM] AS [dali] on dali.DrugApplicationListItemID = afda.DrugApplicationListItem
							JOIN [RDS].[T_DRUG_APPLICATION_LIST] AS [dal] ON [dal].[DrugApplicationListID] = [dali].[DrugApplicationList]
							left join rds.T_BENEFITS b on b.BenefitsID = afda.Benefits
						WHERE  DATEPART(YEAR, [dal].[EndDate]) >= DATEPART(YEAR, @dateTime) and dal.IsActive = 1
						FOR XML PATH('ADDITIONAL_FACTORS_REQUEST_CATALOG'), TYPE
					) AS                       'body/ADDITIONAL_FACTORS_REQUEST_CATALOGS'
					FOR XML PATH(''), ROOT('ADDITIONAL_FACTORS_REQUEST_CATALOG')
				);

				-- Отправка
				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 AS s
				WHERE  
					(@QueueName IS NOT NULL
					AND [s].[ServerName] = @QueueName) 
					OR (@QueueName IS NULL 
					AND [s].[ServerType] IN(0, 1)); -- Рассылаем пакет всем подписанным серверам AKUZ-а и APS, если не указана очередь
			END;
	END;
GO