import React from "react";
import styles from "../styles/traffic_line.less";
import * as echarts from "echarts";

class LineChart extends React.Component {
  constructor(props) {
    super(props);
    this.chartRef = React.createRef();
    this.chartInstance = null;
  }

  componentDidMount() {
    this.initChart();
    window.addEventListener("resize", this.chartResize);
  }

  componentDidUpdate(prevProps) {
    this.initChart();
  }

  componentWillUnmount() {
    if (this.chartInstance) {
      window.removeEventListener("resize", this.chartResize);
      this.chartInstance.dispose();
    }
  }

  chartResize() {
    if (this.chartInstance) {
      this.chartInstance.resize();
    }
  }

  initChart() {
    if (!this.chartInstance) {
      this.chartInstance = echarts.init(this.chartRef.current);
    }
    const option = {
      backgroundColor: "transparent",
      tooltip: {
        trigger: "axis",
        textStyle: {
          fontSize: 25, // 设置字体大小
          fontWeight: "bold", // 可选：加粗
          // color: "#fff", // 可选：字体颜色
        },
      },
      legend: {
        top: 0,
        itemGap: 30,
        textStyle: { color: "#fff", fontSize: "12px" },
        data: this.props.legendData,
      },
      grid: {
        left: "4%",
        right: "4%",
        bottom: "8%",
        top: "10%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: true,
        axisLine: { lineStyle: { color: "#666" } },
        axisLabel: { color: "#fff", fontSize: 12, fontWeight: 'bold' },
        splitLine: {
          // x 轴竖直方向虚线
          show: true,
          lineStyle: {
            type: "dashed",
            color: "#ccc",
            width: 0.3
          },
        },
        data: this.props.xAxisData,
      },
      yAxis: {
        type: "value",
        axisLine: { show: false },
        axisLabel: { color: "#fff", fontSize: 12, fontWeight: 'bold' },
        splitLine: {
          // y 轴竖直方向虚线
          show: true,
          lineStyle: {
            type: "dashed",
            color: "#ccc",
            width: 0.3
          },
        },
      },
      series: this.props.seriesData,
    };
    this.chartInstance.setOption(option);
  }

  render() {
    return (
      <div style={{ width: "100%", height: "100%" }} ref={this.chartRef} />
    );
  }
}

export default LineChart;
