/*
 * @Title:
 * @Author: hongmye
 * @Date: 2023-09-27 11:51:16
 */
import { ConfigProvider } from 'antd';
import classNames from 'classnames';
import ReactEcharts from 'echarts-for-react';
import { omit } from 'lodash';
import ResizeObserver from 'rc-resize-observer';
import React, { memo, useMemo, useState } from 'react';
import buildOption from './utils';

const ECharts = memo(
  React.forwardRef((props, ref) => {
    const { getPrefixCls } = React.useContext(ConfigProvider.ConfigContext);
    const prefixCls = getPrefixCls('basic-chart');
    const [isShow, setIsShow] = useState('hidden');
    const chartProps = omit(props, ['className', 'option']);

    const option = useMemo(() => {
      return buildOption(props.option);
    }, [props.option]);
    if (ref && ref.current && ref.current.getEchartsInstance) {
      ref.current.getEchartsInstance().clear();
      ref.current.getEchartsInstance().setOption(option);
      ref.current.getEchartsInstance().resize();
    }

    const onResize = ({ width, height }) => {
      if (width && height) {
        setIsShow('visible');
        ref?.current?.getEchartsInstance && ref.current.getEchartsInstance().resize();
      } else {
        setIsShow('hidden');
      }
    };
    return (
      <ResizeObserver onResize={onResize}>
        <div style={{ width: '100%', height: '100%', visibility: isShow }}>
          <ReactEcharts
            ref={ref}
            className={classNames(prefixCls, props.className)}
            style={{ width: '100%', height: '100%' }}
            option={option}
            {...chartProps}
          />
        </div>
      </ResizeObserver>
    );
  }),
);

export default ECharts;
