// 绘制echarts图表
import getMonthRange from './getMonthRange'
import getQuarterRange from './getQuarterRange';
import * as echarts from 'echarts'
import 'echarts-wordcloud';
import router from '@/router/index'

const LEGEND_ARROW_NAMES = new Set(['__legend_prev__', '__legend_next__'])

const shouldShowLegendPagingArrows = (chart, option) => {
  const w = typeof chart?.getWidth === 'function' ? chart.getWidth() : 0
  const legendOpt = option?.legend
  const legend = Array.isArray(legendOpt) ? legendOpt[0] : legendOpt
  if (!legend || legend.type !== 'scroll') return false
  const names = Array.isArray(legend.data) ? legend.data : []
  if (!names.length) return false

  const resolveSize = (val, base) => {
    if (val == null) return 0
    if (typeof val === 'number' && Number.isFinite(val)) return val
    const s = String(val).trim()
    if (!s) return 0
    if (s.endsWith('%')) {
      const n = parseFloat(s.slice(0, -1))
      return Number.isFinite(n) ? (base * n) / 100 : 0
    }
    const n = Number(s)
    return Number.isFinite(n) ? n : 0
  }

  const available = resolveSize(legend.width, w) || Math.floor(w * 0.82)
  if (!available || available <= 0) return true

  const fontSize = Number(legend?.textStyle?.fontSize || 14)
  const fontFamily = legend?.textStyle?.fontFamily || 'Source Han Sans CN'
  const fontWeight = legend?.textStyle?.fontWeight || 400
  const iconW = Number(legend?.itemWidth || 12)
  const gap = 10
  const paddingPerItem = iconW + gap + 10

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) return true
  ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`

  const total = names.reduce((sum, n) => {
    const text = String(n ?? '')
    const textW = ctx.measureText(text).width || 0
    return sum + textW + paddingPerItem
  }, 0)

  return total > available
}

const applyLegendPagingArrowVisibility = (chart, option) => {
  const shouldShow = shouldShowLegendPagingArrows(chart, option)
  const graphic = option?.graphic
  if (!Array.isArray(graphic) || graphic.length === 0) return
  const nextGraphic = graphic.map((g) => {
    if (!g || !LEGEND_ARROW_NAMES.has(g.name)) return g
    return {
      ...g,
      invisible: !shouldShow,
      silent: !shouldShow
    }
  })
  chart.setOption({ graphic: nextGraphic }, false, true)
}

const setChart = (option, chartId, allowClick, selectParam) => {
  let chartDom = document.getElementById(chartId);
  if (!chartDom) {
    return null;
  }
  chartDom.removeAttribute("_echarts_instance_");
  let chart = echarts.init(chartDom);
  chart.setOption(option);

  // 处理自定义图例分页箭头（左右分布，隐藏页码）
  // 约定：graphic 元素 name 为 __legend_prev__ / __legend_next__
  chart.on('click', function (params) {
    if (params?.componentType !== 'graphic') return;
    if (!LEGEND_ARROW_NAMES.has(params?.name)) return;

    const opt = chart.getOption?.() || {};
    const legend = Array.isArray(opt.legend) ? opt.legend[0] : null;
    if (!legend || legend.type !== 'scroll') return;

    const dataLen = Array.isArray(legend.data) ? legend.data.length : 0;
    if (dataLen <= 0) return;

    const cur = Number(legend.scrollDataIndex || 0);
    const nextIndex = params.name === '__legend_prev__' ? Math.max(0, cur - 1) : Math.min(dataLen - 1, cur + 1);
    if (nextIndex === cur) return;

    chart.dispatchAction({
      type: 'legendScroll',
      scrollDataIndex: nextIndex
    });
  });

  // 初次渲染后判断是否需要显示左右箭头（可一行展示则隐藏）
  applyLegendPagingArrowVisibility(chart, option)

  if (allowClick) {
    chart.on('click', function (params) {
      // 图例分页箭头只负责翻页，不走任何跳转
      if (params?.componentType === 'graphic' && LEGEND_ARROW_NAMES.has(params?.name)) {
        return
      }
      switch (selectParam.moduleType) {
        case '国会法案':
          if (selectParam.key === 1) {
            // console.log('当前点击', selectParam, params.seriesName, params.name);
            selectParam.selectedStatus = params.seriesName
            selectParam.selectedDate = JSON.stringify(getMonthRange(params.name))
            const route = router.resolve({
              path: "/dataLibrary/countryBill",
              query: selectParam
            });
            window.open(route.href, "_blank");
            return
          } else if (selectParam.key === 2) {
            selectParam.domains = params.name
            const route = router.resolve({
              path: "/dataLibrary/countryBill",
              query: selectParam
            });
            window.open(route.href, "_blank");
            return
          } else if (selectParam.key === 3) {
            if (params.name === '众议院' || params.name === '参议院') {
              selectParam.selectedCongress = params.name
              selectParam.selectedOrg = '全部委员会'
              if (selectParam.selectedDate.length === 4) {
                selectParam.selectedDate = JSON.stringify([selectParam.selectedDate + '-01-01', selectParam.selectedDate + '-12-31'])
              }
            } else {
              selectParam.selectedOrg = params.name
              selectParam.selectedCongress = '全部议院'
              if (selectParam.selectedDate.length === 4) {
                selectParam.selectedDate = JSON.stringify([selectParam.selectedDate + '-01-01', selectParam.selectedDate + '-12-31'])
              }
            }
            const route = router.resolve({
              path: "/dataLibrary/countryBill",
              query: selectParam
            });
            window.open(route.href, "_blank");
            return
          } else {
            selectParam.selectedStatus = params.name
            const route = router.resolve({
              path: "/dataLibrary/countryBill",
              query: selectParam
            });
            window.open(route.href, "_blank");
          }
          break

        case '政令':
          if (params.componentType === 'series' && params.seriesType === 'pie') {
            selectParam.domains = params.name
            const route = router.resolve({
              path: "/dataLibrary/dataDecree",
              query: selectParam
            });
            window.open(route.href, "_blank");
          } else if (params.componentType === 'series' && params.seriesType === 'bar') {
            const year = params.name.slice(0, 4)
            const quatarNum = Number(params.name[params.name.length - 1])
            selectParam.selectedDate = JSON.stringify(getQuarterRange(year, quatarNum))
            const route = router.resolve({
              path: "/dataLibrary/dataDecree",
              query: selectParam
            });
            window.open(route.href, "_blank");
          }
          break

        case '科技智库报告':
          if (selectParam.key === 1) {
            selectParam.domains = params.seriesName
            const year = params.name.slice(0, 4)
            const quatarNum = Number(params.name[params.name.length - 1])
            selectParam.selectedDate = JSON.stringify(getQuarterRange(year, quatarNum))
            const route = router.resolve({
              path: "/dataLibrary/dataThinkTank",
              query: selectParam
            });
            window.open(route.href, "_blank");
            return
          } else if (selectParam.key === 2) {
            selectParam.domains = params.name
            const route = router.resolve({
              path: "/dataLibrary/dataThinkTank",
              query: selectParam
            });
            window.open(route.href, "_blank");
            return
          }
      }

    });
  }
  // 容器可能受布局/异步渲染影响，强制一次 resize 保证 canvas 与容器一致
  setTimeout(() => {
    chart.resize();
    applyLegendPagingArrowVisibility(chart, option)
  }, 0);
  return chart;
};

export default setChart