import * as echarts from 'echarts';

/**
 * @param {{ title: unknown[], data: Array<{ name: string, value: unknown[], color?: string }> }} data
 */
const getMultiLineChart = (data) => {
  // 提取标题和系列数据
  const title = data.title
  const series = data.data

  const allNames = series.map((item) => item.name)
  const legendSplitAt = Math.ceil(allNames.length / 2)
  const legendFirstLine = allNames.slice(0, legendSplitAt)
  const legendSecondLine = allNames.slice(legendSplitAt)

  // 定义配色数组
  const colorList = [
    'rgba(5, 95, 194, 1)',    // #055fc2
    'rgba(19, 168, 168, 1)',  // #13a8a8
    'rgba(250, 140, 22, 1)',  // #fa8c16
    'rgba(114, 46, 209, 1)',  // #722ed1
    'rgba(115, 209, 61, 1)',  // #73d13d
    'rgba(206, 79, 81, 1)',   // #ce4f51
    'rgba(145, 202, 255, 1)', // #91caff
    'rgba(95, 101, 108, 1)',  // #5f656c
    'rgba(250, 84, 28, 1)',   // #fa541c
    'rgba(47, 84, 235, 1)',   // #2f54eb
    'rgba(64, 150, 255, 1)',  // #4096ff
    'rgba(34, 41, 52, 1)',    // #222934
    'rgba(173, 198, 255, 1)', // #adc6ff
    'rgba(255, 169, 64, 1)'   // #ffa940
  ];

  // 解析 RGBA 颜色的辅助函数
  const parseRgba = (colorStr) => {
    // 匹配 rgba(r, g, b, a) 格式
    const match = colorStr.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+(\.\d+)?)\)/);
    if (match) {
      return {
        r: parseInt(match[1]),
        g: parseInt(match[2]),
        b: parseInt(match[3]),
        a: parseFloat(match[4])
      };
    }
    // 默认返回黑色
    return { r: 0, g: 0, b: 0, a: 1 };
  };

  // 动态生成 series 配置
  const echartsSeries = series.map((item, index) => {
    // 获取当前系列的颜色（优先使用item.color，否则用预设颜色，再否则随机）
    const baseColor = item.color || colorList[index % colorList.length] || `rgba(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, 1)`;
    const { r, g, b } = parseRgba(baseColor);

    return ({
      name: item.name,
      type: 'line',
      smooth: true,
      // 新增/优化：面积填充渐变效果
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,        // 顶部
            color: `rgba(${r}, ${g}, ${b}, 0.3)` // 0.3 透明度
          },
          {
            offset: 1,        // 底部
            color: `rgba(${r}, ${g}, ${b}, 0)`   // 0 透明度
          }
        ])
      },
       
      symbolSize: 8,  
      emphasis: {
        focus: 'series'
      },
      data: item.value
    });
  });

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    /* 顶部预留足够空间：多行图例 + Y 轴标题「数量」在纵轴顶端，避免与图例重合 */
    grid: {
      top: '34%',
      right: '3%',
      bottom: '5%',
      left: '2%',
      containLabel: true
    },
    legend: [
      {
        show: true,
        type: 'plain',
        data: legendFirstLine,
        top: 8,
        left: 'center',
        icon: 'circle',
        textStyle: {
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 14,
          lineHeight: 24,
          letterSpacing: 0,
          align: 'left'
        }
      },
      {
        show: legendSecondLine.length > 0,
        type: 'plain',
        data: legendSecondLine,
        top: 32,
        left: 'center',
        icon: 'circle',
        textStyle: {
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 14,
          lineHeight: 24,
          letterSpacing: 0,
          align: 'left'
        }
      }
    ],
    color: colorList, // 使用预设的配色数组
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: title
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        /* 纵轴：end = 坐标轴最大值一端，即竖轴上方 */
        nameLocation: 'end',
        /* 在默认基础上再向左约 20px：nameGap 为轴标题与轴线间距（左侧 Y 轴顶端时增大则标题更靠左） */
        nameGap: 20,
        nameRotate: 0,
        nameTextStyle: {
          color: 'rgba(170, 173, 177, 1)',
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 14,
          lineHeight: 22,
          letterSpacing: 0,
          align: 'right',
          verticalAlign: 'bottom'
        },
        splitLine: {
          show: true, // 显示网格线
          lineStyle: {
            color: 'rgba(231, 241, 255, 1)',
            type: 'dashed',
            width: 1 
          }
        }
      }
    ],
    series: echartsSeries
  };
};

export default getMultiLineChart;