import { com } from "./common";
import * as echarts from "echarts";

/** x轴分割线 */
export function splitLineX() {
  let d = {
    show: getComVal("splitLine_x_show"),
    lineStyle: {
      color: getComVal("splitLine_x_color"),
      width: getComVal("splitLine_x_width"),
      type: getComVal("splitLine_x_type"),
    },
  };
  return d;
}
/** y轴分割线 */
export function splitLineY() {
  let d = {
    show: getComVal("splitLine_y_show"),
    lineStyle: {
      color: getComVal("splitLine_y_color"),
      width: getComVal("splitLine_y_width"),
      type: getComVal("splitLine_y_type"),
    },
  };
  return d;
}

/**
 * 获取公共配置项属性值
 * @param key 属性名称
 * @returns 属性值
 */
export function getComVal(key: string): any {
  let objKeys = Object.keys(com);
  let returnData: any;
  if (objKeys.indexOf(key) != -1) {
    returnData = com[key];
  } else {
    Object.values(com).forEach((e: any) => {
      if (key in e) {
        returnData = e[key];
      }
    });
  }
  return returnData;
}

/**
 * 生成随机数
 * @param m 随机数1
 * @param n 随机数2
 * @returns 处理后的随机数
 */
export function RandomNumber(m: number, n: number): number {
  let num = Math.floor(Math.random() * (m - n) + n);
  return num;
}

/**
 * 渐变样式
 * @param colorArr 颜色组
 * @param direction 渐变方向(默认自上到下)
 * @returns 渐变对象
 */
/**
 * 渐变
 * @param colorArr 颜色组
 * @param x 终点x坐标
 * @param y 终点y坐标
 * @param x2 起点x坐标
 * @param y2 起点y坐标
 * @returns 渐变对象
 */
export function LinearGradient(
  colorArr: string[],
  x?: number,
  y?: number,
  x2?: number,
  y2?: number
) {
  let _colorArr: any[] = []; // colorStops
  let len = colorArr.length; // 颜色组长度
  let cArr: any = colorArr ? colorArr : getComVal("colorData"); // 颜色组
  let j = len - 1;
  for (let i = 0; i <= j; i++) {
    _colorArr.push({
      offset: (1 / j) * i,
      color: cArr[i],
    });
  }
  // 渐变
  let gradientColor: any = new echarts.graphic.LinearGradient(
    x ? x : 0,
    y ? y : 0,
    x2 ? x2 : 0,
    y2 ? y2 : 1,
    _colorArr
  );
  return gradientColor;
}

/**
 * 加载及更新
 * @param id 元素id
 * @param data 更新数据
 * @return 返回实例
 */
export function chartsLoad(id: string, data: any) {
  let element = document.getElementById(id);
  if (element == null) {
    return;
  }
  let existInstance = echarts.getInstanceByDom(element);
  if (echarts.getInstanceByDom(element)) {
    existInstance?.setOption(data, true);
  } else {
    let myChart = echarts.init(element);
    myChart.setOption(data, true);

    // 监听窗口变化
    window.addEventListener("resize", () => {
      myChart.resize();
    });

    return myChart;
  }
}
