import * as echarts from 'echarts'

// 按 AreaTag 的颜色规则映射到折线图配色（取 tag 的文字色）
const AREA_TAG_COLOR_BY_NAME = {
  '人工智能': 'rgba(245, 34, 45, 1)', // tag1
  '生物科技': 'rgba(19, 168, 168, 1)', // tag2
  '新一代通信网络': 'rgba(5, 95, 194, 1)', // tag3
  // 兼容常见写法
  '通信网络': 'rgba(5, 95, 194, 1)',
  '量子科技': 'rgba(114, 46, 209, 1)', // tag4
  '新能源': 'rgba(82, 196, 26, 1)', // tag5
  '集成电路': 'rgba(22, 119, 255, 1)', // tag6
  '海洋': 'rgba(15, 120, 199, 1)', // tag7
  '先进制造': 'rgba(250, 173, 20, 1)', // tag8
  '新材料': 'rgba(250, 140, 22, 1)', // tag9
  '航空航天': 'rgba(47, 84, 235, 1)', // tag10
  '太空': 'rgba(47, 84, 235, 1)', // tag11
  '深海': 'rgba(73, 104, 161, 1)', // tag12
  '极地': 'rgba(133, 165, 255, 1)', // tag13
  '核': 'rgba(250, 84, 28, 1)', // tag14
  '其他': 'rgba(82, 196, 26, 1)' // tag15
}

const fallbackColorList = [
  'rgba(5, 95, 194, 1)',
  'rgba(245, 34, 45, 1)',
  'rgba(19, 168, 168, 1)',
  'rgba(250, 140, 22, 1)',
  'rgba(114, 46, 209, 1)',
  'rgba(82, 196, 26, 1)',
  'rgba(22, 119, 255, 1)',
  'rgba(250, 84, 28, 1)',
  'rgba(47, 84, 235, 1)',
  'rgba(133, 165, 255, 1)'
]

const parseRgba = (colorStr) => {
  const match = colorStr.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+(\.\d+)?)\)/)
  if (match) {
    return {
      r: parseInt(match[1], 10),
      g: parseInt(match[2], 10),
      b: parseInt(match[3], 10),
      a: parseFloat(match[4])
    }
  }
  return { r: 0, g: 0, b: 0, a: 1 }
}

/**
 * @param {{ title: unknown[], data: Array<{ name: string, value: unknown[], color?: string }> }} chartInput
 */
const getMultiLineChart = (chartInput) => {
  const title = chartInput.title
  const series = chartInput.data || []

  const allNames = series.map((item) => item.name)
  const lineSize = Math.ceil(allNames.length / 3)
  const legendLine1 = allNames.slice(0, lineSize)
  const legendLine2 = allNames.slice(lineSize, lineSize * 2)
  const legendLine3 = allNames.slice(lineSize * 2)

  const xCount = Array.isArray(title) ? title.length : 0
  const labelFontSize = xCount > 8 ? 10 : xCount > 5 ? 11 : 12
  const labelRotate = xCount > 6 ? 28 : 0

  const echartsSeries = series.map((item, index) => {
    const baseColor =
      item.color ||
      AREA_TAG_COLOR_BY_NAME[item.name] ||
      fallbackColorList[index % fallbackColorList.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,
      lineStyle: { color: baseColor },
      itemStyle: { color: baseColor },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: `rgba(${r}, ${g}, ${b}, 0.1)` },
          { offset: 1, color: `rgba(${r}, ${g}, ${b}, 0)` }
        ])
      },
      symbolSize: 8,
      emphasis: { focus: 'series' },
      data: item.value
    }
  })

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    /* 贴满 #box3Chart：四边 0，由 containLabel 在网格内为轴文字留位，避免左侧/底部大块留白 */
    grid: {
      top: 92,
      right: 10,
      bottom: 0,
      left: 20,
      containLabel: true
    },
    legend: [
      {
        show: true,
        type: 'plain',
        data: legendLine1,
        top: 4,
        left: 'center',
        icon: 'circle',
        textStyle: {
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 14,
          lineHeight: 24,
          letterSpacing: 0,
          align: 'left',
          color: 'rgb(95, 101, 108)'
        },
        itemWidth: 12,
        itemHeight: 12
      },
      {
        show: legendLine2.length > 0,
        type: 'plain',
        data: legendLine2,
        top: 30,
        left: 'center',
        icon: 'circle',
        textStyle: {
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 14,
          lineHeight: 24,
          letterSpacing: 0,
          align: 'left',
          color: 'rgb(95, 101, 108)'
        },
        itemWidth: 12,
        itemHeight: 12
      },
      {
        show: legendLine3.length > 0,
        type: 'plain',
        data: legendLine3,
        top: 56,
        left: 'center',
        icon: 'circle',
        textStyle: {
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 14,
          lineHeight: 24,
          letterSpacing: 0,
          align: 'left',
          color: 'rgb(95, 101, 108)'
        },
        itemWidth: 12,
        itemHeight: 12
      }
    ],
    // 不使用全局 color，改为每条 series 自己定色（与 AreaTag 一致）
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: title,
        axisLine: {
          lineStyle: {
            color: 'rgb(231, 243, 255)'
          }
        },
        axisLabel: {
          color: 'rgb(132, 136, 142)',
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: labelFontSize,
          interval: 0,
          hideOverlap: false,
          rotate: labelRotate,
          margin: 6
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        nameLocation: 'end',
        nameGap: 20,
        nameTextStyle: {
          color: 'rgb(132, 136, 142)',
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 11,
          padding: [0, 0, 0, -20]  // 👈 这个是左移 4px（上、右、下、左）
        },
        splitNumber: 4,
        axisLabel: {
          color: 'rgb(132, 136, 142)',
          fontFamily: 'Source Han Sans CN',
          fontWeight: 400,
          fontSize: 11,
          margin: 6
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgb(231, 243, 255)',
            type: 'dashed'
          }
        }
      }
    ],
    series: echartsSeries
  }
}

export default getMultiLineChart
