import React from 'react';
import './index.less';

class ErrorBoundary extends React.Component {
  constructor() {
    super();
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.error(`ErrorBoundary 捕获组件内部错误！`, error, info);
  }

  render() {
    if (this.state.hasError) {
      return <div className="ErrorBoundary" />;
    }
    return this.props.children;
  }
}

/**
 * 错误边界处理
 * @param {Component} WrappedComponent
 */
export default function errorBoundary(WrappedComponent) {
  class ErrorBoundaryWithComponent extends React.Component {
    render() {
      const { forwardRef, ...props } = this.props;
      return (
        <ErrorBoundary>
          <WrappedComponent {...props} ref={forwardRef} />
        </ErrorBoundary>
      );
    }
  }
  return React.forwardRef((props, ref) => <ErrorBoundaryWithComponent {...props} forwardRef={ref} />);
}
