import React, { memo, useMemo } from 'react';
import { ConfigProvider } from 'antd';
import classNames from 'classnames';
import ReactEcharts from 'echarts-for-react';
import { omit } from 'lodash';
import buildOption from './utils';

const ECharts = memo(
  React.forwardRef((props, ref) => {
    const { getPrefixCls } = React.useContext(ConfigProvider.ConfigContext);
    const prefixCls = getPrefixCls('basic-chart');

    const chartProps = omit(props, ['className', 'option']);
    const option = useMemo(() => {
      return buildOption(props.option);
    }, [props.option]);

    // const chartProps = pick(props, ['option', 'notMerge', 'lazyUpdate', 'style', 'className', 'theme', 'onChartReady', 'loadingOption', 'showLoading', 'onEvents', 'opts']);
    if (ref && ref.current && ref.current.getEchartsInstance) {
      ref.current.getEchartsInstance().clear();
      ref.current.getEchartsInstance().setOption(option);
      ref.current.getEchartsInstance().resize();
    }
    return (
      <ReactEcharts
        ref={ref}
        className={classNames(prefixCls, props.className)}
        option={option}
        style={{ width: '100%', height: '100%' }}
        {...chartProps}
      />
    );
  }),
);

export default ECharts;