/**
 * 十六进制颜色转rgb
 * @param str 
 * @returns 
 */
export const set16ToRgb = (str) => {
  if (!str) return
  var reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
  if (!reg.test(str)) { return; }
  let newStr = (str.toLowerCase()).replace(/\#/g, '')
  let len = newStr.length;
  if (len == 3) {
    let t = ''
    for (var i = 0; i < len; i++) {
      t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1))
    }
    newStr = t
  }
  let arr = []; //将字符串分隔，两个两个的分隔
  for (var i = 0; i < 6; i = i + 2) {
    let s = newStr.slice(i, i + 2)
    arr.push(parseInt("0x" + s))
  }
  return arr;
}

/**
 * 数字转换为汉字（0-10）
 * @param num 0-10
 * @returns 
 */
export const numToChinese = (num) => {
  const numMap = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  return numMap[num]
}
/** 加载游戏资源 */
export const loadGameResources = async () => {
  return new Promise((resolve, reject) => {
    cc.resources.preloadDir('images', cc.SpriteFrame, (err, res) => {
      console.log('111', res)
      resolve(res, err)
    })
  })
}

/**
 *  获取区间随机数 [min,max)
 * @export
 * @param {*} min
 * @param {*} max
 * @return {*} 
 */
export function randomNum(min, max):number {
  return Math.floor(Math.random() * (max - min)) + min
}

/**
 * 从数组里随机取元素
 * @param arr
 * @param count
 */
export function getRandomArrayElements(arr, count) {
  if (arr.length <= count) return arr;

  let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
  while (i-- > min) {
    index = (i + 1) * Math.random() >> 0;
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}

/**
 * 获取概率
 * @param pro 1-100
 */
export function getProbability(pro) {
  const randomAry = [
    ...Array(100-pro).fill(false),
    ...Array(pro).fill(true)
  ]
  const num = Math.floor(randomNum(0,99))
  return randomAry[num]
}

/**
 * 获取url参数
 * @param {string} name
 */
export function getUrlParam(name) {
  const search = window.location.search;
  const matched = search
      .slice(1)
      .match(new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'));
  return search.length ? matched && matched[2] : null;
}

