import * as echarts from 'echarts'

/** 政策追踪「研究领域变化趋势」图例分页：每页条数（与概览数量变化趋势逻辑一致，条数按产品要求为 4） */
export const POLICY_TRACKING_LEGEND_PAGE_SIZE = 4

const colorList = [
  'rgba(5, 95, 194, 1)',
  'rgba(19, 168, 168, 1)',
  'rgba(250, 140, 22, 1)',
  'rgba(114, 46, 209, 1)',
  'rgba(115, 209, 61, 1)',
  'rgba(206, 79, 81, 1)',
  'rgba(145, 202, 255, 1)',
  'rgba(95, 101, 108, 1)',
  'rgba(250, 84, 28, 1)',
  'rgba(47, 84, 235, 1)',
  'rgba(64, 150, 255, 1)',
  'rgba(34, 41, 52, 1)',
  'rgba(173, 198, 255, 1)',
  'rgba(255, 169, 64, 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
 * @param {{ legendShowCount?: number, legendPageIndex?: number }} [options]
 */
const getMultiLineChart = (chartInput, options = {}) => {
  const title = chartInput.title
  const series = chartInput.data || []

  const legendShowCount =
    typeof options.legendShowCount === 'number' && options.legendShowCount > 0
      ? options.legendShowCount
      : POLICY_TRACKING_LEGEND_PAGE_SIZE
  const rawPageIndex = Number(options.legendPageIndex) || 0
  const allNames = series.map((item) => item.name)
  const pageCount = Math.max(1, Math.ceil(allNames.length / legendShowCount))
  const legendPageIndex = Math.min(Math.max(0, rawPageIndex), pageCount - 1)
  const legendStart = legendPageIndex * legendShowCount
  const legendData = allNames.slice(legendStart, legendStart + legendShowCount)

  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 ||
      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)` },
          { 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: 50,
      right: 10,
      bottom: 0,
      left: 20,
      containLabel: true
    },
    legend: {
      show: true,
      type: 'plain',
      data: legendData,
      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
    },
    color: colorList,
    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',
        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
