import getMaxNum from "./getMaxNum";
import formatTwoNum from "./formatTwoNum";
export default function formatEcharts(chartRef, leftArr, rightArr) {
  return {
    legendselectchanged: (params) => {
      const echarts_instance = chartRef.getEchartsInstance(),
        option = echarts_instance.getOption(),
        { yAxis, series } = option,
        { selected } = params,
        selectArr = [];
      for (let i in selected) {
        if (selected[i]) {
          selectArr.push(i);
        }
      }
      let newSeries = series.filter((it) => selectArr.indexOf(it.name) > -1),
        leftSeries = newSeries.filter((it) => leftArr?.indexOf(it.name) > -1),
        rightSeries = newSeries.filter((it) => rightArr?.indexOf(it.name) > -1),
        leftData = [],
        rightData = [];
      leftSeries.forEach((it) => {
        leftData = [...leftData, ...it.data];
      });
      rightSeries.forEach((it) => {
        rightData = [...rightData, ...it.data];
      });
      let leftMax = getMaxNum(leftData, "left"),
        rightMax = getMaxNum(rightData, "right"),
        leftInterval = formatTwoNum(leftMax / 5),
        rightInterval = formatTwoNum(rightMax / 5);

      if (leftSeries.length) {
        yAxis[0].axisLabel = {
          ...yAxis[0]?.axisLabel,
          show: true,
        };
        yAxis[0].max = leftMax;
        yAxis[0].interval = leftInterval;
      } else {
        yAxis[0].axisLabel = {
          ...yAxis[0]?.axisLabel,
          show: false,
        };
        yAxis[0].max = 0;
        yAxis[0].interval = 0;
      }
      if (yAxis.length > 1) {
        if (rightSeries.length) {
          yAxis[1].axisLabel = {
            ...yAxis[1]?.axisLabel,
            show: true,
          };
          yAxis[1].max = rightMax;
          yAxis[1].interval = rightInterval;
        } else {
          yAxis[1].axisLabel = {
            ...yAxis[1]?.axisLabel,
            show: false,
          };
          yAxis[1].max = 0;
          yAxis[1].interval = 0;
        }
      }

      option.yAxis = [...yAxis];
      echarts_instance.setOption(option);
    },
  };
}
