import React from 'react';
import * as echarts from '@/subpkg1/components/ec-canvas/echarts';

/**
 * 使用本组件前, 页面组件必须引入 ec-canvas 组件
 * usingComponents: {
 *   'ec-canvas': '@/subpkg1/components/ec-canvas/ec-canvas'
 * }
 */
const Chart = (props) => {
  const { option, className, style } = props;
  
  const [inited, setInited] = React.useState(false);
  const chartRef = React.useRef();
  const canvasId = React.useMemo(() => `canvas-${Math.random().toString(36).substring(2, 7)}`, []);
  const ec = React.useMemo(() => {
    const onInit = (canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
      chartRef.current = chart;
      setInited(true);
    }

    return {
      onInit
    }
  }, []);

  React.useEffect(() => {
    if (inited) {
      chartRef.current.setOption(option);
    }
  }, [option, inited]);

  return (
    <view className={className} style={style}>
      <ec-canvas canvasId={canvasId} ec={ec}></ec-canvas>
    </view>
  )
}

export default Chart;

const getLinearGradient = (...args) => new echarts.graphic.LinearGradient(...args);

export {
  echarts,
  getLinearGradient,
}