import * as Echarts from "echarts";
// import { bindInterActions } from "../eventAction/bindEvents.js";
import { transformDataToOpt, transformXAxisByChartTyps } from "@/utils";
import {
  WORDCLOUD,
  CHOROPLETHMAP,
  LINERADAR,
  ECHARTS_COM,
} from "@bdlite/chart-config/lib/chartTypes";
import {
  axisFormatter,
  tooltipFormatter,
  labelFormatter,
  shufflRingPieLabelFormatter,
} from "./valueFormat";
import { cloneDeep } from "lodash-es";
import svgFlatten from "svg-flatten";

export const initEchartsCom = (chartDom, component) => {
  // const chartDom = chartBoxDom.querySelector(".bi-editor-visual-item");
  const chart = createEchartsInstance(chartDom, component);
  // // 绑定交互事件
  // bindInterActions({
  //   component,
  //   id,
  //   chartBoxDom,
  // });
  return chart;
};

const createEchartsInstance = (dom, component) => {
  const chartType = component.chartType;
  const myCharts = Echarts.init(dom);
  let options = transformDataToOpt(component, chartType, myCharts);
  options = transformXAxisByChartTyps(options, chartType, myCharts);
  component.iconConfig.options = options;
  options = generaterFormatter(component);
  options = hackCircleLegend(options);
  options.animation = false;
  myCharts.setOption(options);
  if (chartType === WORDCLOUD) {
    // 词云添加点击时事件
    myCharts.on("click", "series", (value) => {
      if (value?.data?.url) {
        window.open(value.data.url, "_blank");
      }
    });
  }
  if (chartType === LINERADAR) {
    bindCircleActionByRadar(myCharts, options);
  }

  return myCharts;
};

const generaterFormatter = (component) => {
  if (component.chartType == "shufflRingPie") {
    component.iconConfig.options = shufflRingPieLabelFormatter(component);
    return component.iconConfig.options;
  }
  if (!component.dataConfig || component.chartType == "waveInstrument") {
    // 不来自数据模型
    return cloneDeep(component.iconConfig.options);
  } else {
    component.iconConfig.options = axisFormatter(component);
    component.iconConfig.options = tooltipFormatter(component);
    component.iconConfig.options = labelFormatter(component);
    return component.iconConfig.options;
  }
};

export const updateEchartsCom = (instance, component) => {
  const nextComponent = cloneDeep(component);
  // if (!nextComponent.dataResult) {
  //   console.error('dataresult not found')
  //   return false
  // }
  if (!instance) {
    console.error("update echart config error ===> not found instance");
    return false;
  }
  const { chartType } = nextComponent;

  let options = transformDataToOpt(nextComponent, chartType, instance);
  options = transformXAxisByChartTyps(options, chartType, instance);
  nextComponent.iconConfig.options = options;
  options = generaterFormatter(nextComponent);
  options = hackCircleLegend(options);
  options.animation = false;
  if (ECHARTS_COM.includes(chartType)) {
    instance.setOption(options, {
      notMerge: chartType !== WORDCLOUD,
    });
    // instance.resize({
    //   animation: {
    //     duration: 300,
    //     easing: 'quadraticOut',
    //   },
    // })
    instance.resize();
  } else if ([CHOROPLETHMAP].includes(chartType)) {
    instance.update(options, {
      notMerge: chartType !== WORDCLOUD,
    });
  }
  if (chartType === LINERADAR) {
    bindCircleActionByRadar(instance, options);
  }
};

export const watchChartRenderFinished = (instance, resolve) => {
  instance.on("finished", () => {
    resolve();
  });
};

export const hackCircleLegend = (options) => {
  if (options?.legend?.icon) {
    if (options.legend.icon !== "circle") {
      return options;
    }

    let { itemWidth, itemHeight } = options.legend;

    if (itemHeight === itemWidth) {
      return options;
    }

    let svgString = `<?xml version="1.0" encoding="UTF-8"?>
        <svg xmlns="http://www.w3.org/2000/svg">
            <ellipse cx="0" cy="0" rx="${itemWidth}" ry="${itemHeight}" />
        </svg>`;

    let modifiedSvg = svgFlatten(svgString).pathify().value();

    let match = modifiedSvg.match(/d="(.*?)"/);

    if (!match || !match[1]) {
      return options;
    }

    options.legend.icon = `path://${match[1]}`;
    return options;
  }

  return options;
};

export const bindCircleActionByRadar = (instance, options) => {
  instance.off("mouseover");
  instance.on("mouseover", (params) => {
    try {
      if (params.event.target.shape.symbolType == "circle") {
        let itemIdx = params.event.topTarget.__dimIdx;
        let valueFormatter = options.tooltip.valueFormatter;
        let transValue = params.value[itemIdx];
        if (valueFormatter) {
          transValue = valueFormatter(params.value[itemIdx]);
        }
        let tooltip = {
          ...options.tooltip,
          show: true,
          formatter: function () {
            return `${params.name}<br><div style="display:flex; justify-content:space-between;width:150px;font-size: 14px;line-height: 30px;"><span>${options.radar.indicator[itemIdx].name}</span>  <span>${transValue}</span></div>`;
          },
        };
        options.tooltip = tooltip;
        instance.setOption(options);
      }
    } catch (error) {
      console.log("bindCircleActionByRadar", error);
    }
  });
};
