// 聚合折线图 https://g2.antv.antgroup.com/zh/examples/general/line/#line-aggregated-label

import { Chart } from '@antv/g2';
import { useEffect } from 'react';
import { crateContainer } from '../../common';

// ListData类型约束不确定，不同的数据格式可能不同，根据config来配置图表与数据的对应关系
interface ListData {
  [key: string]: any;
}

interface config {
  container: string; // 容器id
  width?: number; // 图表宽度
  height?: number; // 图表高度
  customColor?: boolean; // 通道颜色
  colorMap?: any; // 自定义颜色
  autoFit?: boolean; // 是否填充容器
  xAxisLabel: string; // X轴标识
  yAxisLabel: string; // Y轴标识
  legend?: boolean; // 图例隐藏
  symbol: string; // 折线标识
}

interface ChartData {
  listData: ListData[]; // 图表数据
  config: config; // 图表配置
}

type Props = { chartData: ChartData };
const AggregatedLabelLine: React.FC<Props> = ({ chartData }) => {
  const container = crateContainer(chartData.config.container);
  useEffect(() => {
    const { listData, config } = chartData;
    const chart = new Chart({
      container: config.container,
      theme: 'classic',
      autoFit: config.autoFit,
      width: config.width,
      height: config.height,
      legend: config.legend,
    });

    // 声明可视化
    const line = chart.line(); // 创建一个 line 标记
    line
      .data(listData)
      .transform({ type: 'groupX', y: 'mean' })
      .encode({
        x: config.xAxisLabel,
        y: config.yAxisLabel,
        color: config.symbol,
      })
      .label({
        text: config.yAxisLabel,
        transform: [{ type: 'overlapDodgeY' }],
        style: {
          fontSize: 10,
        },
      });

    if (config.customColor) {
      line.scale('color', { range: config.colorMap }); // 指定值域
    }

    // 渲染可视化
    setTimeout(() => {
      chart.render();
    }, 100);
  }, [chartData]);

  return container;
};

export default AggregatedLabelLine;
