"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 ErrorBoundary () {
        return ErrorBoundary;
    },
    get useErrorHandler () {
        return useErrorHandler;
    },
    get withErrorBoundary () {
        return withErrorBoundary;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _reacterrorboundary = require("react-error-boundary");
const _antd = require("antd");
const _utils = require("../../utils");
const _errors = require("../../utils/errors");
const _initialization = require("../initialization");
const _ErrorHandler = require("./ErrorHandler");
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;
}
function ErrorBoundary({ children, fallback, onError, showInConsole = true, resetKeys, onReset, onResetKeysChange }) {
    // 使用 ref 存储重试计数，在多次错误之间保持状态
    const retryCountRef = (0, _react.useRef)(0);
    // 优化：使用统一的错误处理器
    const errorHandler = (0, _react.useMemo)(()=>(0, _ErrorHandler.getDefaultErrorHandler)(), []);
    // 处理错误，将标准 Error 转换为 FrameworkError
    const handleError = (0, _react.useCallback)(async (error, errorInfo)=>{
        const normalizedError = _errors.errorUtils.normalizeError(error);
        // 将 react-error-boundary 的 errorInfo 转换为 React 的 ErrorInfo 格式
        const reactErrorInfo = {
            componentStack: errorInfo.componentStack || ''
        };
        // 使用统一的错误处理器处理错误
        const handleResult = await errorHandler.handleError(normalizedError, {
            componentStack: reactErrorInfo.componentStack,
            source: 'ErrorBoundary'
        });
        // 如果错误处理器没有处理错误，使用默认处理
        if (!handleResult.handled) {
            _utils.logger.error('错误边界捕获到错误:', {
                error: normalizedError.toJSON(),
                errorInfo: {
                    componentStack: reactErrorInfo.componentStack
                }
            });
        }
        // 调用错误回调
        if (onError) {
            onError(normalizedError, reactErrorInfo);
        }
        // 在控制台显示错误（如果配置了）
        if (showInConsole) {
            console.error('错误边界捕获到错误:', normalizedError);
            console.error('错误信息:', reactErrorInfo);
        }
    }, [
        errorHandler,
        onError,
        showInConsole
    ]);
    // 处理重置
    const handleReset = ()=>{
        // 清除初始化错误状态
        _initialization.initializationErrorState.clearError();
        // 调用用户提供的重置回调
        if (onReset) {
            onReset();
        }
    };
    // 默认 fallback UI（使用 antd 组件）
    // 使用内部组件来管理重试计数状态，使用 React.memo 优化性能
    const DefaultFallbackComponent = /*#__PURE__*/ _react.default.memo(({ error, resetErrorBoundary })=>{
        const normalizedError = _errors.errorUtils.normalizeError(error);
        const [retryCount, setRetryCount] = (0, _react.useState)(retryCountRef.current);
        const [showDetails, setShowDetails] = (0, _react.useState)(false);
        // 同步 ref 的值到 state，确保组件重新创建时能读取到最新的重试计数
        (0, _react.useEffect)(()=>{
            setRetryCount(retryCountRef.current);
        }, []);
        const handleRetry = (0, _react.useCallback)(()=>{
            // 增加重试计数
            const newCount = retryCount + 1;
            retryCountRef.current = newCount;
            setRetryCount(newCount);
            // 执行重置
            handleReset();
            resetErrorBoundary();
        }, [
            retryCount,
            resetErrorBoundary
        ]);
        const handleReload = (0, _react.useCallback)(()=>{
            // 刷新页面
            window.location.reload();
        }, []);
        // 构建用户友好的错误提示
        const userFriendlyMessage = (0, _react.useMemo)(()=>{
            // 根据错误类型提供不同的提示
            if (normalizedError.code === 'NETWORK_ERROR') {
                return '网络连接失败，请检查您的网络设置后重试';
            }
            if (normalizedError.code === 'TIMEOUT_ERROR') {
                return '请求超时，请稍后重试';
            }
            if (normalizedError.code === 'VALIDATION_ERROR') {
                return '数据验证失败，请检查输入内容';
            }
            // 默认提示
            return '应用运行时发生了错误，请稍后重试';
        }, [
            normalizedError.code
        ]);
        // 构建按钮数组
        const extraButtons = (0, _react.useMemo)(()=>{
            const buttons = [
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_antd.Button, {
                    type: "primary",
                    onClick: handleRetry,
                    "aria-label": "重试加载应用",
                    children: "重试"
                }, "retry"),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_antd.Button, {
                    onClick: ()=>setShowDetails(!showDetails),
                    "aria-label": showDetails ? '隐藏错误详情' : '显示错误详情',
                    children: showDetails ? '隐藏详情' : '查看详情'
                }, "details")
            ];
            // 如果重试次数 >= 1，添加刷新页面按钮（提前显示）
            if (retryCount >= 1) {
                buttons.push(/*#__PURE__*/ (0, _jsxruntime.jsx)(_antd.Button, {
                    onClick: handleReload,
                    "aria-label": "刷新页面",
                    children: "刷新页面"
                }, "reload"));
            }
            return buttons;
        }, [
            retryCount,
            handleRetry,
            handleReload,
            showDetails
        ]);
        return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
            role: "alert",
            "aria-live": "assertive",
            "aria-atomic": "true",
            style: {
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                minHeight: '100vh',
                padding: '24px'
            },
            children: [
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_antd.Result, {
                    status: "error",
                    title: "出错了",
                    subTitle: userFriendlyMessage,
                    extra: extraButtons
                }),
                showDetails && /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                    style: {
                        marginTop: 24,
                        padding: 16,
                        backgroundColor: '#f5f5f5',
                        borderRadius: 4,
                        maxWidth: 800,
                        width: '100%',
                        maxHeight: 400,
                        overflow: 'auto'
                    },
                    children: [
                        /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                            style: {
                                marginBottom: 8,
                                fontWeight: 'bold'
                            },
                            children: "错误详情："
                        }),
                        /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                            style: {
                                fontFamily: 'monospace',
                                fontSize: 12
                            },
                            children: [
                                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                    children: [
                                        /*#__PURE__*/ (0, _jsxruntime.jsx)("strong", {
                                            children: "错误类型："
                                        }),
                                        normalizedError.name
                                    ]
                                }),
                                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                    children: [
                                        /*#__PURE__*/ (0, _jsxruntime.jsx)("strong", {
                                            children: "错误代码："
                                        }),
                                        normalizedError.code
                                    ]
                                }),
                                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                    children: [
                                        /*#__PURE__*/ (0, _jsxruntime.jsx)("strong", {
                                            children: "错误信息："
                                        }),
                                        normalizedError.message
                                    ]
                                }),
                                normalizedError.stack && /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                    style: {
                                        marginTop: 8
                                    },
                                    children: [
                                        /*#__PURE__*/ (0, _jsxruntime.jsx)("strong", {
                                            children: "堆栈信息："
                                        }),
                                        /*#__PURE__*/ (0, _jsxruntime.jsx)("pre", {
                                            style: {
                                                whiteSpace: 'pre-wrap',
                                                wordBreak: 'break-word'
                                            },
                                            children: normalizedError.stack
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                })
            ]
        });
    });
    DefaultFallbackComponent.displayName = 'DefaultFallbackComponent';
    const defaultFallback = ({ error, resetErrorBoundary })=>{
        return /*#__PURE__*/ (0, _jsxruntime.jsx)(DefaultFallbackComponent, {
            error: error,
            resetErrorBoundary: resetErrorBoundary
        });
    };
    // 如果提供了自定义 fallback，使用自定义的
    const fallbackRender = fallback ? ({ error, resetErrorBoundary })=>{
        const normalizedError = _errors.errorUtils.normalizeError(error);
        return fallback(normalizedError, ()=>{
            handleReset();
            resetErrorBoundary();
        });
    } : defaultFallback;
    // 处理重置时清除重试计数
    const handleResetWithCount = ()=>{
        retryCountRef.current = 0;
        handleReset();
    };
    // 处理 resetKeys 变化时清除重试计数
    const handleResetKeysChange = (prevKeys, nextKeys)=>{
        retryCountRef.current = 0;
        if (onResetKeysChange) {
            onResetKeysChange(prevKeys, nextKeys);
        }
    };
    // 构建 react-error-boundary 的 props
    const errorBoundaryProps = {
        fallbackRender,
        onError: handleError,
        onReset: handleResetWithCount,
        resetKeys,
        onResetKeysChange: handleResetKeysChange
    };
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(_reacterrorboundary.ErrorBoundary, {
        ...errorBoundaryProps,
        children: children
    });
}
function withErrorBoundary(Component, errorBoundaryProps) {
    const WrappedComponent = (props)=>{
        return /*#__PURE__*/ (0, _jsxruntime.jsx)(ErrorBoundary, {
            ...errorBoundaryProps,
            children: /*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
                ...props
            })
        });
    };
    WrappedComponent.displayName = `withErrorBoundary(${Component.displayName || Component.name || 'Component'})`;
    return WrappedComponent;
}
function useErrorHandler() {
    return (error)=>{
        // 将错误设置到初始化错误状态
        // InitializationErrorThrower 组件会检测到错误并抛出，让 ErrorBoundary 捕获
        _initialization.initializationErrorState.setError(error);
    };
}

//# sourceMappingURL=ErrorBoundary.js.map