import { METRIC_UNIT, DEFAULT_DECIMAL } from "@bdlite/chart-config/lib/dataModel";
import { PIE, RINGPIE } from "@bdlite/chart-config/lib/chartTypes";
import { isArray } from "lodash-es";
import moment from "moment";
const defaultFormat = (value) => {
  if (value >= 10000) {
    return `${value / 10000}万`;
  } else {
    return value;
  }
};
const valueEum = (arr, unit) => {
  // let obj = {}
  // arr.forEach((v) => {
  //   obj[v.value] = v.value != '0' ? v.label : ''
  // })
  const current = arr.find((item) => item.value == unit);
  return parseInt(current.value)
    ? current
    : {
        number: 1,
        label: "",
      };
};
function toThousands(val) {
  let num = val.toString().split(".")[0],
    result = "";
  while (num.length > 3) {
    result = "," + num.slice(-3) + result;
    num = num.slice(0, num.length - 3);
  }
  if (num) {
    result = num + result;
  }
  val.toString().split(".")[1] &&
    (result += `.${val.toString().split(".")[1]}`);
  return result;
}

const transNumFormat = (
  value,
  { unit, decimalNum, suffix, prefix, money, prefixString, thousandths }
) => {
  let result = value;
  const formateUnit = valueEum(METRIC_UNIT, unit);
  result = result / formateUnit.number;
  // 按照配置的格式相除
  if (decimalNum != DEFAULT_DECIMAL) {
    // 设置了小数位数
    result = result.toFixed(Number(decimalNum));
  }

  if (thousandths) {
    result = toThousands(result);
  }
  let template = `${result}${formateUnit.label}${suffix}`,
    pre = "";
  pre =
    prefix == "money"
      ? `${money}`
      : prefix == "customize"
      ? `${prefixString} `
      : "";
  template = pre + template;
  return template;
};
const transPercentFormat = (value, { decimalNum, thousandths }) => {
  let result = value * 100;
  if (decimalNum != DEFAULT_DECIMAL) {
    // 设置了小数位数
    result = result.toFixed(Number(decimalNum));
  }
  if (thousandths) {
    result = toThousands(result);
  }
  return result + "%";
};
const transTimeFormat = (value, { timetrans }) => {
  // timetrans: "1000" 毫秒转时分秒， timetrans: 1 秒转时分秒
  let duration = "",
    format = "";
  if (timetrans === "1000") {
    duration = "milliseconds";
    format = "HH:mm:ss";
  } else {
    duration = "seconds";
    format = "mm:ss";
  }
  const time = moment.duration(value, duration);
  const hours = time.hours();
  const minutes = time.minutes();
  const seconds = time.seconds();

  return moment({ h: hours, m: minutes, s: seconds }).format(format);
};
export const FormatFn = (type) => {
  let fn = {};
  switch (type) {
    case "number":
      fn = transNumFormat;
      break;
    case "percent":
      fn = transPercentFormat;
      break;
    case "time":
      fn = transTimeFormat;
      break;
  }
  return fn;
};

// 标签不需要加format的组件
const NOT_LABEL = ["sankey", "diagram", "funnel", "wordCloud", ""];
// 不同数据格式
// const SOURCE_TYPE_DATA = ['lineBar', 'twoLineArea', 'scatter', 'airScatter', 'tranDoubleBar', '']

// 横向图表

const TRANS_ECHART = ["tranBar", "tranGroupBar", "tranDoubleBar"];
// 只有tooltip要加的组件
const FOR_TOOLTIP = [
  PIE,
  RINGPIE,
  "shufflRingPie",
  "funnel",
  "sankey",
  "wordCloud",
  "lineRadar",
  "areaRadar",
  "diagram",
  "pointerInstrument",
  "waveInstrument",
];

const multipleYaxis = (component) => {
  if (component.chartType == "lineBar") {
    // 多个坐标系
    const columns = ["metricOne", "metricTwo"];
    for (let i = 0; i < columns.length; i++) {
      if (
        component.dataConfig &&
        component.dataConfig[columns[i]] &&
        component.dataConfig[columns[i]][0]?.config?.format
      ) {
        // 修改y轴
        component.iconConfig.options.yAxis[i].axisLabel.formatter = (value) => {
          if (
            component.dataConfig &&
            component.dataConfig[columns[i]] &&
            component.dataConfig[columns[i]][0]?.config?.format
          ) {
            const _data = component.dataConfig[columns[i]][0]?.config?.format;
            if (_data) {
              return FormatFn(_data.type)(value, _data.data);
            }
          } else {
            // delete component.iconConfig.options.yAxis[i].axisLabel.formatter
            component.iconConfig.options.yAxis[i].axisLabel.formatter =
              defaultFormat;
          }
        };
      } else {
        // delete component.iconConfig.options.yAxis[i].axisLabel.formatter
        component.iconConfig.options.yAxis[i].axisLabel.formatter =
          defaultFormat;
      }
    }

    // 修改系列中的label

    component.iconConfig.options.series.forEach((v) => {
      // 修改label
      v.label.formatter = (params) => {
        const _dataIndex = params.componentSubType == "line" ? 1 : 0;
        if (
          component.dataConfig &&
          component.dataConfig[columns[_dataIndex]][0]?.config?.format
        ) {
          const _data =
            component.dataConfig[columns[_dataIndex]][0]?.config?.format;
          // 当前value值
          if (_data) {
            let value = params.value[params.encode.y[0]];
            return FormatFn(_data.type)(value, _data.data);
          }
        } else {
          delete v.label.formatter;
        }
      };
      // 需要区分不同系列配置tooltip的value
      v.tooltip.valueFormatter = (value) => {
        // line在y2轴
        const _dataIndex = v.type == "line" ? 1 : 0;
        const _data =
          component.dataConfig[columns[_dataIndex]][0]?.config?.format;
        // const value = params.value[params.encode.y[0]]
        if (_data) {
          return FormatFn(_data.type)(value, _data.data);
        } else {
          // 确保tooltip一定有值
          return value;
        }
      };
    });
  }
  return component.iconConfig.options;
};

export const axisFormatter = (component) => {
  if (FOR_TOOLTIP.indexOf(component.chartType) != -1) {
    // 没有轴线
    return component.iconConfig.options;
  }
  if (component.chartType == "lineBar") {
    return multipleYaxis(component);
  }

  const axis =
    TRANS_ECHART.indexOf(component.chartType) != -1 ? "xAxis" : "yAxis";
  let target = component.iconConfig.options[axis];
  // 多组轴线
  if (isArray(component.iconConfig.options[axis])) {
    target = target[0];
  }

  if (isExitFormatConfig(component)) {
    // 配置了数据格式 修改轴线label格式
    // 可能是对象，可能是数组
    target.axisLabel.formatter = (value) => {
      const _data = component.dataConfig?.metric[0]?.config?.format;
      if (_data) {
        return FormatFn(_data.type)(value, _data.data);
      }
    };
  } else {
    // 未配置，清空配置
    // if (target) {
    //   delete target.axisLabel.formatter
    // }
    target.axisLabel.formatter = defaultFormat;
  }
  // 至此修改完系列1
  if (isArray(component.iconConfig.options[axis])) {
    const _d = component.iconConfig.options[axis][0].axisLabel.formatter;
    component.iconConfig.options[axis].forEach((v, i) => {
      if (i == 0) {
        return;
      }
      component.iconConfig.options[axis][i].axisLabel.formatter = _d;
    });
  }
  return component.iconConfig.options;
};

export const tooltipFormatter = (component) => {
  if (component.chartType == "lineBar") {
    return component.iconConfig.options;
  }
  if (isExitFormatConfig(component)) {
    // 修改y轴格式
    component.iconConfig.options.tooltip.valueFormatter = (value) => {
      const _data = component.dataConfig?.metric[0]?.config?.format;
      return FormatFn(_data.type)(value, _data.data);
    };
  } else {
    if (component.iconConfig.options.tooltip) {
      delete component.iconConfig.options.tooltip.formatter;
    }
  }
  return component.iconConfig.options;
};
export const labelFormatter = (component) => {
  if (NOT_LABEL.indexOf(component.chartType) != -1) {
    return component.iconConfig.options;
  }
  if ([PIE, RINGPIE].includes(component.chartType)) {
    return pieLabelFormatter(component);
  }
  if (isExitFormatConfig(component)) {
    // 修改y轴格式
    component.iconConfig.options.series.forEach((v) => {
      let target = v.label;
      if (v.type == "gauge") {
        target = v.detail;
      }
      target.formatter = (params) => {
        if (isExitFormatConfig(component)) {
          const _data = component.dataConfig?.metric[0]?.config?.format;
          // 当前value值
          let value = "";
          if (v.type == "gauge") {
            value = params;
          } else {
            if (params.seriesIndex + 1 > 0) {
              value =
                params.value[params.dimensionNames[params.seriesIndex + 1]];
            }
          }
          return FormatFn(_data.type)(value, _data.data);
        } else {
          delete target.formatter;
        }
      };
    });
  }
  return component.iconConfig.options;
};

export const shufflRingPieLabelFormatter = (component) => {
  if (component.chartType == "shufflRingPie") {
    // 修改label样式
    component.iconConfig.options.series.forEach((item) => {
      let label = item.label;
      label.formatter = (params) => {
        let arr = {
          name: label.rich.name.show ? params.name + "\n" : "",
          num: label.rich.num.show
            ? params.value[1] +
              label.suffix +
              `${label.rich.name.show && label.wrap ? "" : "\n"}`
            : "",
          percent: label.rich.percent.show ? params.percent : "",
        };
        return `{name|${arr.name}}{num|${arr.num}}{percent|${
          arr.percent
        }}{symbol|${label.rich.percent.show ? "%" : ""}}`;
      };
      label.rich.name.padding = [label.rich.name.y, 0, 0, label.rich.name.x];
      label.rich.num.padding = [label.rich.num.y, 0, 0, label.rich.num.x];
      label.rich.percent.padding = [
        label.rich.percent.y,
        0,
        0,
        label.rich.percent.x,
      ];
      label.rich.symbol.padding = [
        label.rich.symbol.y,
        0,
        0,
        label.rich.symbol.x,
      ];
      if (label.rich.name.show && label.wrap) {
        label.overflow = "break";
      } else {
        label.overflow = "none";
      }
      return item;
    });
  }

  return component.iconConfig.options;
};
// 饼图、环图
export const pieLabelFormatter = (component) => {
  // 修改label样式
  // if (isExitFormatConfig(component)) {
  const [dimensionName, seriesName] = component?.dataResult?.dimensions || [];
  const _data = component.dataConfig?.metric[0]?.config?.format;
  component.iconConfig.options.series.forEach((item) => {
    let label = item.label;
    label.normal.formatter = (params) => {
      if (!isExitFormatConfig(component)) {
        return `${params.value[dimensionName]},${params.value[seriesName]},(${params.percent}%)`;
      } else {
        return `${params.value[dimensionName]},${FormatFn(_data.type)(
          params.value[seriesName],
          _data.data
        )},(${params.percent}%)`;
      }
    };
    return item;
  });
  // }

  return component.iconConfig.options;
};

const isExitFormatConfig = (component) => {
  return (
    component.dataConfig?.metric &&
    component.dataConfig?.metric[0]?.config?.format
  );
};
