import { isString } from "@vue/shared";
import { isNumber } from "@vueuse/core";

//获取图片
export function getImg(url: string): string {
  return new URL(`../assets/images/${url}`, import.meta.url).href;
}

//字符串转数组 总数
export function countFormat(val: any, total = 0) {
  let str = String(val);
  let numArr = str.split("");
  if (total === 0) return numArr;
  let c = numArr.length <= total && total - numArr.length;
  let arr = [];
  if (c || c === 0) {
    for (let i = 0; i < c; i++) {
      numArr.unshift("0");
      // console.log(numArr);
    }
    return numArr;
  } else {
    for (let i = 0; i < total; i++) {
      arr.push("9");
    }
    return arr;
  }
}

//hex2转rgba
export const hex2Rgba = (bgColor: string | any[], alpha = 1) => {
  let color = bgColor.slice(1); // 去掉'#'号
  let rgba = [
    parseInt("0x" + color.slice(0, 2)),
    parseInt("0x" + color.slice(2, 4)),
    parseInt("0x" + color.slice(4, 6)),
    alpha,
  ];
  return "rgba(" + rgba.toString() + ")";
};

export function addUnit(value: unknown, defaultUnit = "px") {
  if (!value) return "";
  if (isString(value)) {
    return value;
  } else if (isNumber(value)) {
    return `${value}${defaultUnit}`;
  }
  //   debugWarn(SCOPE, "binding value must be a string or number");
}

//计算百分比
export const getPercent = (value: number, total: number, fixed = 0) => {
  return total && Number(((value / total) * 100).toFixed(fixed));
};

export function numToStr(num: number, fixed = 2) {
  const million = 10000; // 一万
  const billion = 100000000; // 一亿
  let unit = "";
  let result = Number(num);
  if (num >= billion) {
    unit = "亿";
    result = num / billion;
  } else if (num >= million) {
    unit = "万";
    result = num / million;
  }
  return result.toFixed(fixed) + unit;
}

export const strToNum = (str: any) => {
  const million = 10000; // 一万
  const billion = 100000000; // 一亿
  const string = String(str);
  // console.log(string);
  let num = parseFloat(string.replace(/[^\d\.]/g, ""));
  if (string.indexOf("亿") !== -1) {
    num *= billion;
  } else if (string.indexOf("万") !== -1) {
    num *= million;
  }
  return num;
};

export const getNumber = (string: string) => {
  return parseFloat(string.replace(/[^\d\.]/g, ""));
};

// 抽离成公共方法
export const awaitWrap = async (promise: Promise<any>) => {
  try {
    const data = await promise;
    return [null, data];
  } catch (err) {
    return [err, null];
  }
};

//随机数
export const genRandom = (min: number, max: number) =>
  ((Math.random() * (max - min + 1)) | 0) + min;
