import * as echarts from 'echarts'
import { MUTICHARTCOLORS } from "@/common/constant.js";

const parseHexToRgb = (hex) => {
  const h = String(hex || '').replace('#', '').trim()
  if (h.length !== 6) return { r: 0, g: 0, b: 0 }
  return {
    r: parseInt(h.slice(0, 2), 16),
    g: parseInt(h.slice(2, 4), 16),
    b: parseInt(h.slice(4, 6), 16),
  }
}

/**
 * @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 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 = MUTICHARTCOLORS[index % MUTICHARTCOLORS.length] || '#055FC2'
    const { r, g, b } = parseHexToRgb(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: 60,
      right: 10,
      bottom: 0,
      left: 20,
      containLabel: true
    },
    legend: {
      show: true,
      type: 'scroll',
      orient: 'horizontal',
      left: 8,
      top: 6,
      width: '95%',
      height: 24,
      padding: [0, 24, 0, 24],
      icon: 'circle',
      itemWidth: 12,
      itemHeight: 12,
      data: allNames,
      // 隐藏内置分页按钮与页码（使用 graphic 自定义左右箭头）
      pageButtonPosition: 'end',
      pageIconSize: 0,
      pageButtonGap: 0,
      pageFormatter: () => '',
      pageTextStyle: { fontSize: 0, color: 'transparent' },
      textStyle: {
        fontFamily: 'Source Han Sans CN',
        fontWeight: 400,
        fontSize: 14,
        lineHeight: 24,
        letterSpacing: 0,
        align: 'left',
        color: 'rgb(95, 101, 108)'
      }
    },
    graphic: [
      {
        type: 'polygon',
        name: '__legend_prev__',
        left: 10,
        top: 14,
        shape: { points: [[8, 0], [0, 6], [8, 12]] },
        style: { fill: 'rgb(95, 101, 108)' },
        cursor: 'pointer',
        tooltip: { show: false },
        silent: false,
        z: 100
      },
      {
        type: 'polygon',
        name: '__legend_next__',
        right: 10,
        top: 14,
        shape: { points: [[0, 0], [8, 6], [0, 12]] },
        style: { fill: 'rgb(95, 101, 108)' },
        cursor: 'pointer',
        tooltip: { show: false },
        silent: false,
        z: 100
      }
    ],
    // 不使用全局 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
