IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateFrlloRecipeProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_UpdateFrlloRecipeProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_UpdateFrlloRecipeProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_UpdateFrlloRecipeProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2023 12 11
-- Description: Обновление данных по рецептам связанных с выгрузкой в ФРЛЛО
-- =============================================
CREATE PROCEDURE [rds].[sp_UpdateFrlloRecipeProcess]
    @ExportId uniqueidentifier,
    @Type int
AS
BEGIN

declare @Unloaded bit
SELECT @Unloaded = Unloaded FROM RDS.T_EXPORT_FRLLO_RECIPE WHERE ExportFrlloRecipeID = @ExportId

if(@Unloaded = 0)
begin
	update RDS.T_EXPORT_FRLLO_RECIPE set Unloaded = 1 WHERE ExportFrlloRecipeID = @ExportId

	DECLARE @NUM INT = 50000

	CREATE TABLE #TMP_OBJ(
	 ID UNIQUEIDENTIFIER NOT NULL UNIQUE
	,NUM INT IDENTITY(1,1)
)

	IF(@Type = 0)

	BEGIN

	INSERT INTO #TMP_OBJ(ID)
	SELECT DISTINCT RecipeID
	FROM RDS.T_RECIPE r  
	WHERE EXISTS(SELECT 1 FROM RDS.T_EXPORT_FRLLO_RECIPE_DATA efrd WHERE efrd.ObjId = r.RecipeID AND efrd.ExportFrlloRecipe = @ExportId and efrd.FrlloError is null)

	WHILE EXISTS(SELECT TOP 1 1 FROM #TMP_OBJ)
		BEGIN

			UPDATE r
				SET r.FrlloType = CASE WHEN r.FrlloType = 0 THEN 2 ELSE 0 END
			FROM RDS.T_RECIPE r
			WHERE EXISTS(SELECT 1 FROM #TMP_OBJ T WHERE T.ID = r.RecipeID AND T.NUM <= @NUM)
			
			DELETE #TMP_OBJ
			WHERE NUM <= @NUM
			
			SET @NUM = @NUM + 50000
	
		END
	END

	ELSE
	BEGIN

	INSERT INTO #TMP_OBJ(ID)
	SELECT DISTINCT RecipeElementID
	FROM RDS.T_RECIPE_ELEMENT r  
	WHERE EXISTS(SELECT 1 FROM RDS.T_EXPORT_FRLLO_RECIPE_DATA efrd WHERE efrd.ObjId = r.RecipeElementID AND efrd.ExportFrlloRecipe = @ExportId)

	WHILE EXISTS(SELECT TOP 1 1 FROM #TMP_OBJ)
		BEGIN

			UPDATE r
				SET r.FrlloType = CASE WHEN r.FrlloType = 0 THEN 2 ELSE 0 END
			FROM RDS.T_RECIPE_ELEMENT r
			WHERE EXISTS(SELECT 1 FROM #TMP_OBJ T WHERE T.ID = r.RecipeElementID AND T.NUM <= @NUM)

			DELETE #TMP_OBJ
			WHERE NUM <= @NUM
			
			SET @NUM = @NUM + 50000

		END
	END

	
end
END;