"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "SplashScreen", {
    enumerable: true,
    get: function() {
        return SplashScreen;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _antd = require("antd");
const _utils = require("../../utils");
const _initialization = require("../initialization");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 启动页组件
 * 
 * 在启动页中执行初始化，并使用 Ant Design 5 的 Spin 和 Progress 组件展示启动进度
 */ const SplashScreen = /*#__PURE__*/ (0, _react.memo)(({ options, onComplete })=>{
    const [progress, setProgress] = (0, _react.useState)(0);
    const [currentStep, setCurrentStep] = (0, _react.useState)('准备初始化...');
    const [isInitializing, setIsInitializing] = (0, _react.useState)(false);
    const [estimatedTime, setEstimatedTime] = (0, _react.useState)(null);
    const hasCompletedRef = (0, _react.useRef)(false);
    const onCompleteRef = (0, _react.useRef)(onComplete);
    const optionsRef = (0, _react.useRef)(options);
    const startTimeRef = (0, _react.useRef)(Date.now());
    const minDisplayTimeRef = (0, _react.useRef)(options.minSplashScreenTime ?? 500); // 最小显示时间，默认 500ms
    const progressUpdateTimerRef = (0, _react.useRef)(null);
    const rafRef = (0, _react.useRef)(null);
    const lastProgressRef = (0, _react.useRef)(0);
    const progressHistoryRef = (0, _react.useRef)([]);
    // 保持引用最新
    (0, _react.useEffect)(()=>{
        onCompleteRef.current = onComplete;
        optionsRef.current = options;
        minDisplayTimeRef.current = options.minSplashScreenTime ?? 500;
    }, [
        onComplete,
        options
    ]);
    // 自适应防抖进度更新函数（使用 requestAnimationFrame 优化）
    const debouncedProgressUpdate = (0, _react.useCallback)((progressValue, step)=>{
        // 取消之前的更新
        if (rafRef.current !== null) {
            cancelAnimationFrame(rafRef.current);
        }
        // 记录进度历史用于时间预估
        const now = Date.now();
        progressHistoryRef.current.push({
            progress: progressValue,
            time: now
        });
        // 只保留最近10个记录
        if (progressHistoryRef.current.length > 10) {
            progressHistoryRef.current.shift();
        }
        // 计算预估时间
        if (progressHistoryRef.current.length >= 2 && progressValue > 0) {
            const history = progressHistoryRef.current;
            const first = history[0];
            const last = history[history.length - 1];
            const progressDelta = last.progress - first.progress;
            const timeDelta = last.time - first.time;
            if (progressDelta > 0 && timeDelta > 0) {
                const progressPerMs = progressDelta / timeDelta;
                const remainingProgress = 100 - progressValue;
                const estimatedMs = remainingProgress / progressPerMs;
                setEstimatedTime(Math.max(0, Math.round(estimatedMs)));
            }
        }
        // 使用 requestAnimationFrame 优化更新
        rafRef.current = requestAnimationFrame(()=>{
            setProgress(progressValue);
            if (step) {
                setCurrentStep(step);
            }
            lastProgressRef.current = progressValue;
            rafRef.current = null;
        });
    }, []);
    (0, _react.useEffect)(()=>{
        if (hasCompletedRef.current) return;
        hasCompletedRef.current = true;
        startTimeRef.current = Date.now();
        const performInitialization = async ()=>{
            try {
                setIsInitializing(true);
                setProgress(0);
                setCurrentStep('开始初始化...');
                _utils.logger.info('启动页开始执行初始化');
                // 执行初始化，传入防抖的进度回调
                const context = await (0, _initialization.initialization)(optionsRef.current, (progressValue, step)=>{
                    debouncedProgressUpdate(progressValue, step);
                });
                _utils.logger.info('启动页初始化完成', context);
                // 动态调整最小显示时间（如果初始化很快，减少最小显示时间）
                const elapsedTime = Date.now() - startTimeRef.current;
                const dynamicMinTime = elapsedTime < 200 ? Math.min(minDisplayTimeRef.current, 300) : minDisplayTimeRef.current;
                const remainingTime = Math.max(0, dynamicMinTime - elapsedTime);
                if (remainingTime > 0) {
                    await new Promise((resolve)=>setTimeout(resolve, remainingTime));
                }
                // 清理防抖定时器
                if (progressUpdateTimerRef.current) {
                    clearTimeout(progressUpdateTimerRef.current);
                    progressUpdateTimerRef.current = null;
                }
                // 确保进度条显示 100%
                setProgress(100);
                setCurrentStep('初始化完成');
                // 初始化完成，调用回调
                onCompleteRef.current(context);
            } catch (error) {
                _utils.logger.error('启动页初始化失败:', error);
                // 设置错误状态，让 ErrorBoundary 能够捕获
                _initialization.initializationErrorState.setError(error);
                setCurrentStep('初始化失败，请刷新页面重试');
                // 即使失败也调用 onComplete，让应用能够处理错误
                onCompleteRef.current({
                    config: {},
                    progress: 0,
                    isReady: false,
                    duration: 0
                });
            } finally{
                setIsInitializing(false);
            }
        };
        performInitialization();
        // 清理函数
        return ()=>{
            if (progressUpdateTimerRef.current) {
                clearTimeout(progressUpdateTimerRef.current);
            }
            if (rafRef.current !== null) {
                cancelAnimationFrame(rafRef.current);
            }
        };
    }, [
        debouncedProgressUpdate
    ]);
    // 如果提供了自定义启动屏组件，使用自定义组件
    const CustomSplashScreen = optionsRef.current.splashScreen;
    if (CustomSplashScreen) {
        const customProps = {
            progress,
            currentStep,
            isInitializing
        };
        return /*#__PURE__*/ (0, _jsxruntime.jsx)(CustomSplashScreen, {
            ...customProps
        });
    }
    // 默认启动屏 UI
    return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
        role: "status",
        "aria-live": "polite",
        "aria-label": "应用正在加载",
        style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100vh',
            width: '100%',
            gap: 24
        },
        children: [
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_antd.Spin, {
                size: "large",
                spinning: isInitializing,
                "aria-label": "加载中"
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                style: {
                    width: '300px'
                },
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_antd.Progress, {
                    percent: progress,
                    status: isInitializing ? 'active' : 'success',
                    showInfo: true,
                    "aria-label": `加载进度 ${progress}%`
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                role: "status",
                "aria-live": "polite",
                style: {
                    fontSize: 14,
                    color: '#666',
                    textAlign: 'center'
                },
                children: [
                    currentStep,
                    estimatedTime !== null && estimatedTime > 0 && /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                        style: {
                            fontSize: 12,
                            color: '#999',
                            marginTop: 8
                        },
                        children: [
                            "预计还需 ",
                            Math.ceil(estimatedTime / 1000),
                            " 秒"
                        ]
                    })
                ]
            })
        ]
    });
});
SplashScreen.displayName = 'SplashScreen';

//# sourceMappingURL=SplashScreen.js.map