function randomNumber() {
  const random = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
  };
  if (arguments.length === 1) {
    let [length] = arguments;
    // 生成指定长度的随机数字，首位一定不是 0
    let nums = [...Array(length).keys()].map((i) =>
      i > 0 ? random(0, 9) : random(1, 9)
    );
    return parseInt(nums.join(""));
  } else if (arguments.length >= 2) {
    let [min, max] = arguments;
    return random(min, max);
  } else {
    return Number.NaN;
  }
}
function randomString(length, chats) {
  if (!length) length = 1;
  if (!chats) chats = "0123456789qwertyuioplkjhgfdsazxcvbnm";
  let str = "";
  for (let i = 0; i < length; i++) {
    let num = randomNumber(0, chats.length - 1);
    str += chats[num];
  }
  return str;
}
function randomUUID() {
  let chats = "0123456789abcdef";
  return randomString(32, chats);
}
// 请求公用pc端的接口，通过postMessage通信
let promiseArr = {};
export function setPromise(name, res) {
  if (promiseArr[name]) {
    promiseArr[name][0](res);
    promiseArr[name] = null;
  }
}
export function globalRequest(type, params) {
  let newType = type;
  return new Promise((resolve, reject) => {
    if (!promiseArr[type]) {
      promiseArr[newType] = [resolve, reject];
    } else {
      newType = `${newType}@${randomUUID()}`;
      promiseArr[newType] = [resolve, reject];
    }
    const apiDomain = window.top.location.origin;
    window.top.postMessage({ type: newType, params }, apiDomain);
  });
}
