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

/**
 * 获取公共配置项属性值
 * @param key 属性名称
 * @returns 属性值
 */
export function getComVal(key: any): any {
  let objKeys = Object.keys(com);
  let returnData = null;
  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;
}

/** 渐变样式 */
export function itemstyle() {
  let colorArr: any[] = [];
  /** 渐变数组长度 */
  let l = getComVal("color_data").length;
  let j = l - 1;
  for (let i = 0; i <= j; i++) {
    colorArr.push({
      offset: (1 / j) * i,
      color: getComVal("color_data")[i],
    });
  }
  return colorArr;
}

/**
 * 加载及更新
 * @param id 元素id
 * @param data 更新数据
 */
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);
  }
}
