import React, { Component } from 'react';
import isEqual from 'lodash/isEqual';

interface IProps {
  id: number | string;
  data: any;
  width: number;
  height: number;
  top: number;
  left: number;
}

export default class ComErrorBoundary extends Component<IProps, { hasError: boolean }> {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error) {
    this.setState({ hasError: true });
    console.error(`组件发生错误（id:${this.props.id}）:`, error);
  }

  componentDidUpdate(prevProps) {
    const { data: prevData } = prevProps;

    if (!isEqual(prevData, this.props.data) && this.state.hasError) {
      this.setState({
        hasError: false
      });
    }
  }

  render() {
    if (this.state.hasError) {
      const { id, width, height, top, left } = this.props;

      return (
        <div
          className="__easyv-component"
          id={'' + id}
          style={{ position: 'absolute', display: 'flex', justifyContent: 'center', alignItems: 'center', width, height, left, top }}></div>
      );
    }

    return this.props.children;
  }
}
