import React from 'react';
import { Button, Result } from 'antd';

interface AppErrorBoundaryProps {
  children: React.ReactNode;
  /** 自定义降级内容；不传则使用默认错误卡片 */
  fallback?: React.ReactNode;
}

interface AppErrorBoundaryState {
  hasError: boolean;
}

/**
 * 全局渲染错误兜底：捕获子树内的渲染异常，展示可恢复的错误卡片，
 * 避免单个页面/组件崩溃导致整个应用白屏。
 */
export class AppErrorBoundary extends React.Component<
  AppErrorBoundaryProps,
  AppErrorBoundaryState
> {
  state: AppErrorBoundaryState = { hasError: false };

  static getDerivedStateFromError(): AppErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: React.ErrorInfo): void {
    console.error('[AppErrorBoundary] 渲染异常:', error, info.componentStack);
  }

  render(): React.ReactNode {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback;
      return (
        <Result
          status="error"
          title="页面出现异常"
          subTitle="请刷新页面重试；若问题持续，请联系管理员。"
          extra={
            <Button type="primary" onClick={() => window.location.reload()}>
              刷新页面
            </Button>
          }
        />
      );
    }
    return this.props.children;
  }
}

export default AppErrorBoundary;
