"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const ErrorMessage_1 = tslib_1.__importDefault(require("./ErrorMessage"));
const ErrorPage_1 = require("../../../types/ErrorPage");
const ErrorPage_2 = tslib_1.__importDefault(require("./ErrorPage"));
class ErrorBoundary extends react_1.default.Component {
    state = {
        hasError: false,
        error: undefined,
        info: undefined,
    };
    handler = null;
    static getDerivedStateFromError(error) {
        return { hasError: true };
    }
    componentDidCatch(error, errorInfo) {
        console.error('ErrorBoundary caught an error:', error, errorInfo);
        // 这里可以记录错误
        if (this.props.disabled) {
            return;
        }
        this.setState({
            error,
            info: errorInfo,
        });
    }
    componentDidMount() {
        if (this.props.disabled) {
            return;
        }
        this.handler = (event) => {
            const customEvent = event;
            const error = new Error(`vite:preloadError`);
            console.error('ErrorBoundary caught an error:', error, customEvent);
            this.setState({
                error: error,
                info: customEvent,
            });
        };
        window.addEventListener('vite:preloadError', this.handler);
    }
    componentWillUnmount() {
        if (this.props.disabled) {
            return;
        }
        if (this.handler) {
            window.removeEventListener('vite:preloadError', this.handler);
        }
    }
    get errorCode() {
        const { error } = this.state;
        if (error instanceof Error) {
            const isChunkError = error.name === 'ChunkLoadError' ||
                error.message?.includes('ChunkLoadError') ||
                error.message?.includes('vite:preloadError') ||
                error.message?.includes('Failed to fetch dynamically imported module');
            if (isChunkError)
                return ErrorPage_1.ECode.pageUpdate;
        }
        return ErrorPage_1.ECode.pageCrash;
    }
    render() {
        if (this.props.disabled || !this.state.hasError) {
            return this.props.children;
        }
        return (<ErrorPage_2.default code={this.errorCode} content={<ErrorMessage_1.default error={this.state.error}/>}>
            </ErrorPage_2.default>);
    }
}
exports.default = ErrorBoundary;
