/**
 * 路由预加载管理器
 * 提供路由组件的预加载功能
 */ "use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get PreloadStrategy () {
        return PreloadStrategy;
    },
    get RoutePreloader () {
        return RoutePreloader;
    },
    get getRoutePreloader () {
        return getRoutePreloader;
    }
});
const _utils = require("../../../utils");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
var PreloadStrategy = /*#__PURE__*/ function(PreloadStrategy) {
    /**
   * 不预加载
   */ PreloadStrategy["NONE"] = "none";
    /**
   * 预加载当前路由的下一级路由
   */ PreloadStrategy["NEXT_LEVEL"] = "next-level";
    /**
   * 预加载所有路由
   */ PreloadStrategy["ALL"] = "all";
    /**
   * 预加载可见路由（根据路由配置的优先级）
   */ PreloadStrategy["VISIBLE"] = "visible";
    return PreloadStrategy;
}({});
let RoutePreloader = class RoutePreloader {
    /**
   * 注册路由用于预加载
   */ registerRoute(route) {
        if (!route.page && !route.layout) {
            return;
        }
        const priority = route.handle?.order ?? 999;
        // 根据策略决定是否注册
        if (this.config.strategy === "none") {
            return;
        }
        if (this.config.strategy === "visible" && priority > this.config.priorityThreshold) {
            return;
        }
        // 注册页面组件
        if (route.page && typeof route.page === 'function') {
            this.tasks.set(`${route.name}_page`, {
                importFn: route.page,
                routeName: route.name,
                priority,
                status: 'pending'
            });
        }
        // 注册布局组件
        if (route.layout && typeof route.layout === 'function') {
            this.tasks.set(`${route.name}_layout`, {
                importFn: route.layout,
                routeName: route.name,
                priority,
                status: 'pending'
            });
        }
        // 递归注册子路由
        if (route.children) {
            route.children.forEach((child)=>this.registerRoute(child));
        }
    }
    /**
   * 注册多个路由
   */ registerRoutes(routes) {
        routes.forEach((route)=>this.registerRoute(route));
    }
    /**
   * 预加载指定路由
   */ async preloadRoute(routeName) {
        const tasks = Array.from(this.tasks.values()).filter((task)=>task.routeName === routeName && task.status === 'pending');
        if (tasks.length === 0) {
            return;
        }
        await Promise.all(tasks.map((task)=>this.preloadTask(task)));
    }
    /**
   * 预加载任务
   */ async preloadTask(task) {
        if (task.status !== 'pending') {
            return;
        }
        task.status = 'loading';
        task.startTime = Date.now();
        try {
            // 设置超时
            const timeoutPromise = new Promise((_, reject)=>{
                setTimeout(()=>reject(new Error('预加载超时')), this.config.timeout);
            });
            // 执行预加载
            await Promise.race([
                task.importFn(),
                timeoutPromise
            ]);
            task.status = 'loaded';
            const duration = Date.now() - (task.startTime || 0);
            _utils.logger.debug(`路由组件预加载成功: ${task.routeName} (${duration}ms)`);
        } catch (error) {
            task.status = 'failed';
            _utils.logger.warn(`路由组件预加载失败: ${task.routeName}`, error);
        }
    }
    /**
   * 开始预加载（根据策略）
   */ startPreload() {
        if (this.config.strategy === "none") {
            return;
        }
        // 延迟预加载，避免影响初始渲染
        this.preloadTimer = setTimeout(()=>{
            this.executePreload();
        }, this.config.delay);
    }
    /**
   * 执行预加载
   */ async executePreload() {
        const tasks = Array.from(this.tasks.values()).filter((task)=>task.status === 'pending').sort((a, b)=>a.priority - b.priority);
        if (tasks.length === 0) {
            return;
        }
        _utils.logger.debug(`开始预加载 ${tasks.length} 个路由组件`);
        // 根据策略决定预加载哪些任务
        let tasksToPreload = [];
        switch(this.config.strategy){
            case "all":
                tasksToPreload = tasks;
                break;
            case "next-level":
                // 只预加载优先级最低的（最可能访问的）
                tasksToPreload = tasks.slice(0, Math.min(5, tasks.length));
                break;
            case "visible":
                tasksToPreload = tasks.filter((task)=>task.priority <= this.config.priorityThreshold);
                break;
            default:
                return;
        }
        // 并行预加载（限制并发数）
        const concurrency = 3;
        for(let i = 0; i < tasksToPreload.length; i += concurrency){
            const batch = tasksToPreload.slice(i, i + concurrency);
            await Promise.all(batch.map((task)=>this.preloadTask(task)));
        }
        _utils.logger.debug('路由组件预加载完成');
    }
    /**
   * 停止预加载
   */ stopPreload() {
        if (this.preloadTimer) {
            clearTimeout(this.preloadTimer);
            this.preloadTimer = null;
        }
    }
    /**
   * 清空所有任务
   */ clear() {
        this.tasks.clear();
        this.stopPreload();
        _utils.logger.debug('路由预加载任务已清空');
    }
    /**
   * 获取预加载统计信息
   */ getStats() {
        const stats = {
            total: this.tasks.size,
            pending: 0,
            loading: 0,
            loaded: 0,
            failed: 0
        };
        for (const task of this.tasks.values()){
            stats[task.status]++;
        }
        return stats;
    }
    constructor(config = {}){
        _define_property(this, "tasks", new Map());
        _define_property(this, "config", void 0);
        _define_property(this, "preloadTimer", null);
        this.config = {
            strategy: config.strategy ?? "next-level",
            delay: config.delay ?? 1000,
            priorityThreshold: config.priorityThreshold ?? 10,
            timeout: config.timeout ?? 5000
        };
    }
};
/**
 * 获取路由预加载管理器单例
 */ let routePreloaderInstance = null;
function getRoutePreloader(config) {
    if (!routePreloaderInstance) {
        routePreloaderInstance = new RoutePreloader(config);
    }
    return routePreloaderInstance;
}

//# sourceMappingURL=RoutePreloader.js.map