IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_LoadAnswerFromFrlloProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_LoadAnswerFromFrlloProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_LoadAnswerFromFrlloProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_LoadAnswerFromFrlloProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2021 01 14
-- Description: Выгрузка данных в ФРЛЛО
-- =============================================
CREATE PROCEDURE [rds].[sp_LoadAnswerFromFrlloProcess]
    @ExportId uniqueidentifier,
    @Xml xml
AS
BEGIN
	
	DECLARE 
		 @EntityId INT	= (SELECT TOP 1 e.Entities FROM RDS.T_EXPORT_FRLLO e WHERE e.ExportFrlloID = @ExportId)
		,@PalId INT		= (SELECT TOP 1 e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'PALLIATIVE_REGISTER')
		,@RRId INT		= (SELECT TOP 1 e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'RR_PATIENT')
		,@SpecId INT	= (SELECT TOP 1 e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'SPECIAL_BENEFITS_REGISTR')
		,@BskId INT		= (SELECT TOP 1 e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'BSK_REGISTER')
	
	select
		 t.c.value('./document_id[1]', 'uniqueidentifier')	AS [document_id]
		,t.c.value('./status[1]', 'int')					AS [status]
		,t.c.value('./reg_num[1]', 'varchar(100)')			AS [reg_num]
		,err.c.value('./code[1]', 'varchar(max)')			AS [code]
		,err.c.value('./description[1]', 'varchar(max)')	AS [description]
	INTO #Answer
	FROM @Xml.nodes('root/result/element') T(c)
		OUTER APPLY t.c.nodes('./errors/element') err(c)
	
	if ((select count(*) from #Answer) = 0)
	BEGIN
		RAISERROR('Структура загружаемого файла не соответствует документации, либо Вы загружаете пустой файл!', 16, 10) 		
	END

	update fed
	set fed.FrlloId = a.reg_num,
		fed.FrlloStatus = a.status,
		fed.FrlloError = a.error
	from RDS.T_EXPORT_FRLLO_DATA fed
		CROSS APPLY(
			select 
				 an.reg_num
				,an.status
				,(select a2.code + '-' + a2.description + '/' from #Answer a2 where a2.document_id = an.document_id for xml path('')) as error
			from #Answer an 
				where fed.ExportFrllo = @ExportId and an.document_id = fed.ExportFrlloDataID
			group by an.document_id, an.reg_num, an.status
		) a

	drop table #Answer

	if(@EntityId = @PalId)
	Begin
		update pal
		set pal.FrlloId = fed.FrlloId
		from RDS.T_PALLIATIVE_REGISTER pal
		join RDS.T_EXPORT_FRLLO_DATA fed on fed.ObjId = pal.PalliativeRegisterID
		where fed.ExportFrllo = @ExportId and fed.FrlloId is not null and pal.FrlloId is null
	End
	
	if(@EntityId = @RRId)
	Begin
		update rr
		set rr.FrlloId = fed.FrlloId
		from RDS.[T_RR_PATIENT] rr
		join RDS.T_EXPORT_FRLLO_DATA fed on fed.ObjId = rr.Id
		where fed.ExportFrllo = @ExportId and fed.FrlloId is not null and rr.FrlloId is null
	End
	
	if(@EntityId = @SpecId)
	Begin
		update spec
		set spec.FrlloId = fed.FrlloId
		from RDS.T_SPECIAL_BENEFITS_REGISTR spec
		join RDS.T_EXPORT_FRLLO_DATA fed on fed.ObjId = spec.SpecialBenefitsRegistrID
		where fed.ExportFrllo = @ExportId and fed.FrlloId is not null and spec.FrlloId is null
	End
	
	if(@EntityId = @BskId)
	Begin
		update bsk
		set bsk.FrlloId = fed.FrlloId
		from RDS.T_BSK_REGISTER bsk
		join RDS.T_EXPORT_FRLLO_DATA fed on fed.ObjId = bsk.BskRegisterID
		where fed.ExportFrllo = @ExportId and fed.FrlloId is not null and bsk.FrlloId is null
	End
END				
				