IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_RegulatorRRO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RegulatorRRO]
GO
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO


---- =============================================
---- Author:      Vitacore (с)
---- Create date: 2016-12-02
---- Description: Управление обработкой данных, приходящих  через RABBIT_RECEIVE_OBJECT
---- =============================================
--CREATE PROCEDURE [dbo].[sp_RegulatorRRO]
--	@ID uniqueidentifier = null
--	,@Type varchar(255) = ''   -- Имя операции сервиса 
--	,@Reply varchar(max) = ''
--AS
--BEGIN
--	Declare
--	     @xDoc xml = ''
--		,@kod varchar(16) = ''
--		,@Message varchar(1024) = ''
--		,@IDOwner varchar(64) = ''      -- ID объекта, который изменялся
--		,@IDOwner_ uniqueidentifier = null
--		,@IDOwnerForm varchar(64) = ''   -- ID объекта, форму которого надо открывать при повторной передаче 
--		,@IDOwnerForm_ uniqueidentifier = null
--		,@IDPatient varchar(64) = ''  
--		,@IDPatient_ uniqueidentifier = null

--	SET NOCOUNT ON;
		
--	IF     @Type = N'ServiceDiabBurPatientAdd' 
--	   OR  @Type = N'ServiceDiabBurPatientUpdate' 
--	   OR  @Type = N'ServiceDiabBurPatientDel' 
		
--	   OR  @Type = N'ServiceTbBurPatientAdd' 
--	   OR  @Type = N'ServiceTbBurPatientUpdate' 	
		
--		--- Бурятия. Итог действия с  пациентом
--		BEGIN
--			Set   @xDoc= @Reply

--			select 
--				@kod = r.value('@Kod', 'nvarchar(8)') 
--				,@Message = r.value('@Message', 'nvarchar(255)')
--				,@IDOwner = r.value('@IDOwner', 'nvarchar(64)')
--				,@IDOwnerForm = r.value('@IDOwnerForm', 'nvarchar(64)')
--				,@IDPatient  = r.value('@IDPatient', 'nvarchar(64)')
--			from @xDoc.nodes('/dataRecieve/item') col(r)

--			IF (@kod = '0')  
--				BEGIN
--						IF    SUBSTRING(@Type,1,9) = 'ServiceTb' 
--						BEGIN
--							--  Запомнить ID пациента,  который добавлен в базу профилактики туберкулеза РИАС
--							SELECT @IDPatient_= CAST(@IDPatient AS uniqueidentifier)
--							if not exists (select * from  [dbo].[T_IDPATIENT_SEND_RIAS] where PatientID = @IDPatient_)
--							BEGIN
--								  insert into [dbo].[T_IDPATIENT_SEND_RIAS](PatientID,  TimeSend) values(@IDPatient_, GETDATE())
--							END
--						END
--				END
			
			
--			IF (@kod = '0')  AND (SUBSTRING(@Type,1,11) = 'ServiceDiab' ) 
--				BEGIN
-- 					-- Запрос к web-сервису выполнен успешно, в Регистре льгота создана
--					SELECT  @IDOwner_= CAST(@IDOwner AS uniqueidentifier)
					
--					update pbd
--					set pbd.Loaded = 1
--					from [AKUZ].T_PATIENT_BENEFITS_DIRECTION pbd
--					join [AKUZ].T_PATIENT_BENEFITS_DIRECTION_DATA pbdd  on pbdd.PatientBenefitsDirection = pbd.PatientBenefitsDirectionID
--					where pbdd.PatientBenefitsDirectionDataID = @IDOwner_
				
--					--  Добавление льготы
--					IF     @Type  = N'ServiceDiabBurPatientAdd' 
--						   BEGIN
--								INSERT INTO [AKUZ].[T_PATIENT_BENEFITS]
--										   ([PatientBenefitsID] ,[Patient] ,[Benefits] ,[BenefitDocumentNumber] ,[BeginDate] ,[Mkb] ,[Active] ,[Deleted]
--										   ,[CreateType] ,[LPU_INF] ,[SOST_R] ,[RegDate])
--										   --, [PAC_ID])
--								SELECT
--										   NEWID()--<PatientBenefitsID, uniqueidentifier,>
--										   ,pbd.Patient--<Patient, uniqueidentifier,>
--										   ,pbdd.Benefits--<Benefits, uniqueidentifier,>
--										   ,pbdd.Document--<BenefitDocumentNumber, varchar(255),>
--										   ,pbd.[Date]--<BeginDate, datetime,>
--										   ,mkb.MkbID--<Mkb, uniqueidentifier,>
--										   ,1--<Active, bit,>
--										   ,0--<Deleted, bit,>
--										   ,2--<CreateType, int,>
--										   ,lm.LpuCode--<LPU_INF, varchar(4),>
--										   ,pbd.SOST_R--<SOST_R, int,>
--										   ,GETDATE()--<RegDate, datetime,>
--										   --,@RrPatient--<PAC_ID, bigint,>)   --@IDParentRecive
--								from [AKUZ].T_PATIENT_BENEFITS_DIRECTION_DATA pbdd
--									join [AKUZ].T_PATIENT_BENEFITS_DIRECTION pbd on pbd.PatientBenefitsDirectionID = pbdd.PatientBenefitsDirection
--									left join [AKUZ].T_MKB mkb on mkb.MCBCode = pbdd.Mkb
--									join [AKUZ].T_LPU_MAIN lm on lm.LpuID = pbd.LpuMain
--								where pbdd.PatientBenefitsDirectionDataID = @IDOwner_
--										and
--									not exists
--									(
--										select *
--										from [AKUZ].T_PATIENT_BENEFITS pb
--										where pb.Patient = pbd.Patient
--												and
--											pb.Benefits = pbdd.Benefits
--									)
--						   END

--					IF     @Type = N'ServiceDiabBurPatientDel'
--						BEGIN
--							-- Закрытие льготы
--							update pb
--							set pb.BenefitDocumentNumber = pbdd.Document
--								,pb.EndDate = pbd.[Date]
--								,pb.Mkb = mkb.MkbID
--								,pb.SOST_R = pbd.SOST_R
--								--,pb.PAC_ID = @RrPatient
--								,pb.Active = 0
--								,pb.Deleted = 1
--							from [AKUZ].T_PATIENT_BENEFITS_DIRECTION_DATA pbdd
--								left join [AKUZ].T_MKB mkb on mkb.MCBCode = pbdd.Mkb
--								join [AKUZ].T_PATIENT_BENEFITS_DIRECTION pbd on pbd.PatientBenefitsDirectionID = pbdd.PatientBenefitsDirection
--								join [AKUZ].T_LPU_MAIN lm on lm.LpuID = pbd.LpuMain
--								join [AKUZ].T_PATIENT_BENEFITS pb on pb.Patient = pbd.Patient
--										and
--									pb.Benefits = pbdd.Benefits
--							where pbdd.PatientBenefitsDirectionDataID =@IDOwner_
								
--						END

--					IF     @Type = N'ServiceDiabBurPatientUpdate' 
--						BEGIN
--						-- Обновление льготы
--						update pb
--						set pb.BenefitDocumentNumber = pbdd.Document
--							,pb.BeginDate = pbd.[Date]
--							,pb.EndDate = null
--							,pb.Mkb = mkb.MkbID
--							,pb.SOST_R = pbd.SOST_R
--							,pb.LPU_INF = lm.LpuCode
--							--,pb.PAC_ID = @RrPatient
--							,pb.CreateType = 2
--							,pb.Active = 1
--							,pb.Deleted = 0
--						from [AKUZ].T_PATIENT_BENEFITS_DIRECTION_DATA pbdd
--							left join [AKUZ].T_MKB mkb on mkb.MCBCode = pbdd.Mkb
--							join [AKUZ].T_PATIENT_BENEFITS_DIRECTION pbd on pbd.PatientBenefitsDirectionID = pbdd.PatientBenefitsDirection
--							join [AKUZ].T_LPU_MAIN lm on lm.LpuID = pbd.LpuMain
--							join [AKUZ].T_PATIENT_BENEFITS pb on pb.Patient = pbd.Patient
--									and
--								pb.Benefits = pbdd.Benefits
--						where pbdd.PatientBenefitsDirectionDataID = @IDOwner_
								
--						END
--				END

--			GOTO FINISH
--		END
	
	
--	IF       @Type = N'ServiceDiabBurRecipeReleaseDetrash' 
--		OR   @Type = N'ServiceDiabBurRecipeTrash'     
--		--- Бурятия. Результат действия с  рецептом
--		begin     
--			Set @xDoc = @Reply 
--			select 
--			@kod = r.value('@Kod', 'nvarchar(8)') 
--			,@Message = r.value('@Message', 'nvarchar(255)')
--			,@IDOwner = r.value('@IDOwner', 'nvarchar(64)')
--			,@IDOwnerForm = r.value('@IDOwnerForm', 'nvarchar(64)')
--			from   @xDoc.nodes('/dataRecieve/item') col(r)

--			SELECT  @IDOwner_= CAST(@IDOwner AS uniqueidentifier)

--			IF (@kod = '0') AND (@IDOwner <> '')
--				begin
-- 					-- Запрос к web-сервису выполнен успешно
--					update r
--					set r.Deleted =	case							 
--						when  @Type = N'ServiceDiabBurRecipeReleaseDetrash' then 0
--						when  @Type = N'ServiceDiabBurRecipeTrash'   then 1
--						else 0
--					end			
--					from [AKUZ].T_RECIPE r
--					where r.RecipeID =  @IDOwner_
--				end

--				GOTO FINISH
--		end

	
--	-- Бурятия. Турбодиагностика.  Действия не предусмотрены.
--	IF       @Type = N'ServiceTbBurPatientAddMatou' 
--		OR   @Type = N'ServiceTbBurPatientAddFluoro'     
--		OR   @Type = N'ServiceTbBurPatientAddBCG'      
--		begin
--			Set @xDoc = @Reply 
--			select 
--			@kod = r.value('@Kod', 'nvarchar(8)') 
--			,@Message = r.value('@Message', 'nvarchar(255)')
--			,@IDOwner = r.value('@IDOwner', 'nvarchar(64)')
--			,@IDOwnerForm = r.value('@IDOwnerForm', 'nvarchar(64)')
--			,@IDPatient  = r.value('@IDPatient', 'nvarchar(64)')
--			from   @xDoc.nodes('/dataRecieve/item') col(r)

--			GOTO FINISH
--		end

	
--	FINISH:

--	-- Фиксируем не принятые запросы к сервисам РИАС для их исправления и повторной отправки (@IDOwner = '' при массовом запросе)
--	if @IDOwner <> ''
--	BEGIN
--		SELECT  @IDOwnerForm_= CAST(@IDOwnerForm AS uniqueidentifier)
--		DELETE FROM [AKUZ].T_REJECTED_REQUESTS_WSERVICE where IDOwnerForm = @IDOwnerForm_
	
--		IF (@kod <> '0') 
--		begin
--				insert into [AKUZ].T_REJECTED_REQUESTS_WSERVICE	values(NEWID(),GETDATE(), @kod, @Message, @IDOwnerForm_ ,@Type)
--		end
--	END

--END
