// 绘制echarts图表
import getMonthRange from './getMonthRange'
import getQuarterRange from './getQuarterRange';
import * as echarts from 'echarts'
import 'echarts-wordcloud';
import router from '@/router/index'
import { goToDataCountryBill, goToDataDecree,goToDataThinkTank } from './goToPage';
const setChart = (option, chartId, allowClick, selectParam, otherAreaList) => {
  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
    });
  });



  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))
          } else if (selectParam.key === 2) {
            if(params.name === '其他') {
              selectParam.selectedAreaList = JSON.stringify(otherAreaList)
              selectParam.domains = null
            } else {
              selectParam.domains = params.name
              selectParam.selectedAreaList = null
            }
          } 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'])
              }
            }
          } else {
            selectParam.selectedStatus = params.name
          }
            goToDataCountryBill(selectParam)
          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");
          }
          goToDataDecree(selectParam)
          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))
            goToDataThinkTank(selectParam);
            return
          } else if (selectParam.key === 2) {
            selectParam.domains = params.name
           goToDataThinkTank(selectParam);
            return
          }
      }

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

export default setChart