import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

interface propsData {
  xData: string[];
  yData: string[];
  color: string;
  width: string;
  height: string;
}

const LineChart: React.FC<propsData> = (props) => {
  const chartRef: any = useRef();
  const { xData, yData, color, width, height } = props;

  // 初始化
  useEffect(() => {
    const chart = echarts.init(chartRef.current);
    const options = {
      legend: {
        show: false,
      },
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        top: '5%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: xData,
          axisLine: {
            lineStyle: {
              color: '#ddd',
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            rotate: 45,
            interval: 0,
            textStyle: {
              color: '#333',
            },
            margin: 15,
          },
          boundaryGap: false,
        },
      ],
      yAxis: [
        {
          type: 'value',
          axisTick: {
            show: false,
          },
          axisLine: {
            lineStyle: {
              color: '#ddd',
            },
          },
          axisLabel: {
            textStyle: {
              color: '#333',
            },
          },
          splitLine: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: '',
          type: 'line',
          data: yData,
          symbolSize: 6,
          symbol: 'circle',
          smooth: true,
          lineStyle: {
            color: color,
          },
          itemStyle: {
            normal: {
              color: color,
              borderColor: color,
            },
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: color + 'b3',
              },
              {
                offset: 1,
                color: color + '03',
              },
            ]),
          },
          emphasis: {
            itemStyle: {
              color: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.5,
                colorStops: [
                  {
                    offset: 0,
                    color: color,
                  },
                  {
                    offset: 1,
                    color: '#fff',
                  },
                ],
              },
              borderColor: color,
              borderWidth: 2,
            },
          },
        },
      ],
    };

    chart.setOption(options);
  }, []);

  return <div style={{ width: width, height: height }} ref={chartRef} />;
};
export default LineChart;
