CREATE OR REPLACE PROCEDURE rds.sp_updatefrllorecipeprocess(
    exportid uuid,
    type int
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_exportid uuid := exportid;
    p_type     int  := type;
    v_unloaded boolean;
    v_num      int  := 50000;
BEGIN
    
    SELECT unloaded
    INTO v_unloaded
    FROM rds.t_export_frllo_recipe
    WHERE exportfrllorecipeid = p_exportid;
    
    IF (v_unloaded = FALSE) THEN
        
        UPDATE rds.t_export_frllo_recipe
        SET unloaded = TRUE
        WHERE exportfrllorecipeid = p_exportid;
        
        CREATE TEMP TABLE temp_obj
        (
            id  uuid PRIMARY KEY,
            num serial
        );
        
        IF (p_type = 0) THEN
            
            INSERT INTO temp_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 = p_exportid
                         );
            
            WHILE EXISTS(SELECT 1 FROM temp_obj)
                LOOP
                    
                    UPDATE rds.t_recipe r
                    SET r.frllotype = CASE WHEN r.status = 1 THEN 1 ELSE 0 END
                    WHERE EXISTS (SELECT 1 FROM temp_obj t WHERE t.id = r.recipeid AND t.num <= v_num);
                    
                    DELETE FROM temp_obj WHERE num <= v_num;
                    
                    v_num := (v_num + 50000);
                
                END LOOP;
        
        ELSE
            
            INSERT INTO temp_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 = p_exportid
                         );
            
            WHILE EXISTS(SELECT 1 FROM temp_obj)
                LOOP
                    
                    UPDATE rds.t_recipe_element r
                    SET r.frllotype = r.deleted
                    WHERE EXISTS (SELECT 1 FROM temp_obj t WHERE t.id = r.recipeelementid AND t.num <= v_num);
                    
                    DELETE FROM temp_obj WHERE num <= v_num;
                    
                    v_num := (v_num + 50000);
                
                END LOOP;
        
        END IF;
    ELSE
    
    END IF;
END;
$$;