// yesJumpPage.js
var _userdata = require("userdata.js");
var userData = _userdata.userData;
var router = require("@system.router");
var appItem = [];
//console.log("===============factoryYesJumpPage==============");
function initPage(pageAppItem) {
    userData.factoryappItem = pageAppItem;
    
    // //console.log("Initialized appItem data: " + appItem);
    // //console.log("=============================");
    // //console.log("Initialized appItem data: " + appItem[1].index);

}
function testCode(that){
   var activePage =  that.activePage
   //console.log("=======================================activePage: " + activePage)
}

function yesGoToNextPage(currentPageName) {
    // try {
        // 找到当前页面对应的 appItem
        const currentApp = userData.factoryappItem.find(item => item.startup === currentPageName);
        if (!currentApp) {
            //console.log("Current page not found in appItem.");
            router.push({ path: "factory_testList" });
            return;
        }

        //console.log("Current appItem: " + currentPageName);
        //console.log("appItem", userData.factoryappItem);

        const currentIndex = currentApp.index;
        //console.log("Current index: " + currentIndex);

        // 如果当前 index 为 0，直接返回 factory_testList
        if (currentIndex === 0) {
            //console.log("Current item has index 0, no navigation.");
            router.push({ path: "factory_testList" });
            return;
        }

        let nextApp = null;
        let searchIndex = currentIndex + 1;

        // 获取所有存在的 index 值，用于判断 index 是否存在
        const existingIndexes = new Set(userData.factoryappItem.map(item => item.index));

        // 使用 do...while 循环查找下一个 index 存在且 en === 1 的项
        do {
            const found = userData.factoryappItem.find(item => item.index === searchIndex && item.en === 1);
            if (found) {
                nextApp = found;
                break;
            } else {
                searchIndex++;
            }
        } while (existingIndexes.has(searchIndex));

        if (nextApp) {
            router.push({
                path: nextApp.startup
            });
        } else {
            //console.log("No next enabled test item found by increasing index.");
            router.push({ path: "factory_testList" });
        }
    // } catch (error) {
    //     console.error("Error in yesGoToNextPage:", error);
    //     router.push({ path: "factory_testList" });
    // }
}



module.exports = {
    yesGoToNextPage: yesGoToNextPage,
    initPage: initPage,
    testCode: testCode,
}