export function getQueryString(name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return window.decodeURIComponent(r[2]);
  }
  return null;
}

export function getQueryStringByUrl(url = "", name = "") {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = url.split("?")[1].match(reg);
  if (r != null) {
    return window.decodeURIComponent(r[2]);
  }
  return null;
}

export const isInApp = !!navigator.userAgent.includes('denet');

export const appVersionCode = +getQueryString('appVersionCode');

export function debounce(fn, delay) {
  let timer; // 定时器
  return function (...args) {
    // 形成闭包
    // args 为函数调用时传的参数。
    let context = this;
    timer && clearTimeout(timer); // 当函数再次执行时，清除定时器，重新开始计时
    // 利用定时器，让指定函数延迟执行。
    timer = setTimeout(function () {
      // 执行传入的指定函数，利用apply更改this绑定和传参
      fn.apply(context, args);
    }, delay);
  };
}

export function throttle(fn, thresh) {
  var timeout;
  var start = new Date();
  var threshhold = thresh || 500;
  return function () {
    var context = this,
      args = arguments,
      curr = new Date() - 0;

    clearTimeout(timeout); //总是干掉事件回调
    if (curr - start >= threshhold) {
      fn.apply(context, args); //只执行一部分方法，这些方法是在某个时间段内执行一次
      start = curr;
    } else {
      // 让方法在脱离事件后也能执行一次
      timeout = setTimeout(function () {
        fn.apply(context, args);
      }, threshhold);
    }
  };
}

export function setStorage(key, value) {
  return localStorage.setItem(key, JSON.stringify(value));
}

export function getStorage(key) {
  const item = localStorage.getItem(key);
  try {
    return item ? JSON.parse(item) : "";
  } catch (e) {
    return item;
  }
}

export function guid() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

export function scaleNumber(num) {
  let length = num.toString().split(".")[1].length;

  let scale = "1";

  for (let i = 0; i < length; i++) {
    scale += "0";
  }

  let val = num * scale;
  return {
    val,
    scale,
  };
}

export function getBit(value) {
  const reg = /([0-9]+\.[0-9]{4})[0-9]*/;
  if (value) {
    let str = value.toString();
    str = str.replace(reg, "$1");
    return str;
  } else {
    return value;
  }
}

export function getCookie(name) {
  var strcookie = document.cookie; //获取cookie字符串
  var arrcookie = strcookie.split("; "); //分割
  //遍历匹配
  for (var i = 0; i < arrcookie.length; i++) {
    var arr = arrcookie[i].split("=");
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return "";
}

export function nextTick(fn, time = 50) {
  return new Promise((resolve) => {
    setTimeout(() => {
      if (fn) fn();
      resolve();
    }, time);
  });
}

export function getBrowser() {
  let browser;
  let UserAgent = navigator.userAgent.toLowerCase();
  if (UserAgent.indexOf("chrome") > -1 && UserAgent.indexOf("safari") > -1) {
    browser = `Chrome`;
  } else if (UserAgent.indexOf("firefox") > -1) {
    browser = `Firefox`;
  } else if (UserAgent.indexOf("opera") > -1) {
    browser = `Opera`;
  } else if (
    UserAgent.indexOf("safari") > -1 &&
    UserAgent.indexOf("chrome") == -1
  ) {
    browser = `Safari`;
  } else if (UserAgent.indexOf("edge") > -1) {
    browser = `Edge`;
  } else {
    browser = `Other`;
  }
  return browser;
}

export function getOffsetRect(element) {
  var oTop = element.offsetTop;
  var oLeft = element.offsetLeft;
  var current = element.offsetParent;
  while (current !== null) {
    oTop += current.offsetTop;
    oLeft += current.offsetLeft;
    current = current.offsetParent;
  }
  return {
    top: oTop,
    left: oLeft,
  };
}

export function formatSecondsAsTime(secs) {
  if (secs <= 0) {
    return "00:00:00";
  }
  var hr = Math.floor(secs / 3600);
  var min = Math.floor((secs - hr * 3600) / 60);
  var sec = Math.floor(secs - hr * 3600 - min * 60);
  var text;
  if (hr < 10) {
    hr = "0" + hr;
  }
  if (min < 10) {
    min = "0" + min;
  }
  if (sec < 10) {
    sec = "0" + sec;
  }
  text = hr + ":" + min + ":" + sec;

  return text;
}

// 抽奖红包 left
export function formatSecondsAsDaysOrTime(secs, showLeft = true) {
  if (secs <= 0) {
    return "00:00:00";
  }
  let text = "";
  var hr = Math.floor(secs / 3600);
  if (hr >= 24) {
    let day = parseInt(hr / 24)
    text = showLeft ? `${day} days left` : `${day} days`
  } else {
    text = formatSecondsAsTime(secs);
  }
  return text;
}

// 时间格式化 => *d *h
export function formatSecondsAsDayHour(secs) {
  let text = "";
  if (secs <= 0) {
    return "0h";
  }

  var hr = Math.floor(secs / 3600);
  if (hr >= 24) {
    let day = parseInt(hr / 24);
    text += `${day}d `;
  }
  let hour = parseInt(hr % 24);
  if (hour > 0) {
    text += `${hour}h`;
  }
  return text;
}

export function checkURL(URL) {
  var str = URL;
  //判断URL地址的正则表达式为:http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
  // /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/
  // eslint-disable-next-line no-useless-escape
  var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
  var objExp = new RegExp(Expression);
  if (objExp.test(str) == true) {
    return true;
  } else {
    return false;
  }
}

let $_data = []
export function $(key, cache = true) {
  if (!key || typeof(key) != 'string') {
    return null
  }
  // 不使用缓存
  if (!cache) {
    return document.querySelector(key)
  }

  let _dom
  for (let i in $_data) {
    if ($_data[i].key == key) {
      _dom = $_data[i].element
      break
    }
  }

  // 没有缓存
  if (!_dom) {
    _dom = document.querySelector(key)
    if (_dom) {
      $_data.push({ key, element: _dom })
    }
  }
  return _dom
}

export const iframeId = getQueryString('iframeId');