const isType = function (type) {
  return function (arg) {
    return Object.prototype.toString.call(arg) === `[object ${type}]`;
  };
};

export const isFunction = isType('Function');

export const isObject = isType('Object');

export const isString = isType('String');

export const isArray = isType('Array');

export const isDate = isType('Date');

/**
 * 为10以内的数字补0
 */
export function addZero(n) {
  if (n >= 10) {
    return n + '';
  } else if (n < 10 && n >= 0) {
    return '0' + n;
  } else {
    return n;
  }
}

// 数组去重
export function uniqueArray(arr) {
  return [...new Set(arr)];
}

// 节流
export function throttle(fn, delay = 200) {

  let isThrottled = false;
  let saveArgs = null;
  let saveThis = null;

  return function wrapper(...args) {
    if (isThrottled) {
      saveArgs = args;
      saveThis = this;
      return;
    }

    isThrottled = true;
    fn.apply(this, args);

    setTimeout(() => {
      isThrottled = false;
      if (saveArgs) {
        wrapper.apply(saveThis, saveArgs);
        saveArgs = saveThis = null;
      }
    }, delay);
  }
}

// 防抖
export function debounce(fn, delay = 200) {
  let timer = null;

  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 获取页面URL参数
export function getLocationParams(name) {
  const pages = getCurrentPages();
  const curPage = pages[pages.length - 1];
  return name ? curPage.options[name] : curPage.options;
}

export function stringToDate(str) {
  // 字符串必需符合以下规则：
  // 按照年月日时分秒顺序；
  // 至少需指定到日，日与时之间需要加空格；
  // 连接符只能是一个字符，只有日的或者最后一个的连接符可以省略。
  // 例如如：2018-01-2 00:0:3，2018年2月20日 12时30，2018-2-1。
  const reg = /^(\d{1,4})\D(0[^0]|1[012]|[^0])\D(0[^0]|[12]\d|3[01]|[^0])(?:[^\d\s])?(?:\s|$)(?:([01]\d|2[0-3]|[^0])|$)(?:\D|$)(?:([0-5]\d|[^0])|$)(?:\D|$)(?:([0-5]\d|[^0])|$)(?:\D|$)(?:(\d{1,3})|$)\D?$/;
  if (!reg.test(str)) {
    throw new Error('字符串格式错误');
  }
  let year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
  str.replace(reg, (...arg) => {
    year = Number(arg[1]);
    month = Number(arg[2]) - 1;
    day = Number(arg[3]);
    if (arg[4]) {
      hours = Number(arg[4]);
    }
    if (arg[5]) {
      minutes = Number(arg[5]);
    }
    if (arg[6]) {
      seconds = Number(arg[6]);
    }
    if (arg[7]) {
      milliseconds = Number(arg[7]);
    }
  });
  return new Date(year, month, day, hours, minutes, seconds, milliseconds);
}

/**
 * 将时间转换成字符串
 *
 * format可选格式：
 * yyyy替换年，MM替换月，dd替换天，HH替换时，mm替换分，ss替换秒，都可缺省
 * 中间的间隔单位只能使用一个字符，单位都可缺省
 * 例如：yyyy年MM月dd日 HH时mm分ss秒，yyyy-MM-dd HH:mm:ss，MM dd HH, yyyyMMdd
 */
export function dateToString(date, format = 'yyyy-MM-dd HH:mm:ss') {
  if (!isDate(date)) {
    throw new Error("第一个参数请传入Date类型");
  }
  const reg = /^(y{4})?[^yMdHms]?(M{2})?[^yMdHms]?(d{2})?[^yMdHms]?\s?(H{2})?[^yMdHms]?(m{2})?[^yMdHms]?(s{2})?[^yMdHms]?$/;
  if (!reg.test(format)) {
    throw new Error("第二个参数请传入yyyy-MM-dd HH:mm:ss格式的字符串");
  }
  format = format.replace(reg, (...arg) => {
    let match = arg[0];
    if (arg[1]) {
      let year = date.getFullYear();
      match = match.replace(arg[1] + "", year + "");
    }
    if (arg[2]) {
      let month = addZero(date.getMonth() + 1);
      match = match.replace(arg[2] + "", month);
    }
    if (arg[3]) {
      let day = addZero(date.getDate());
      match = match.replace(arg[3] + "", day);
    }
    if (arg[4]) {
      let hour = addZero(date.getHours());
      match = match.replace(arg[4] + "", hour);
    }
    if (arg[5]) {
      let min = addZero(date.getMinutes());
      match = match.replace(arg[5] + "", min);
    }
    if (arg[6]) {
      let second = addZero(date.getSeconds());
      match = match.replace(arg[6] + "", second);
    }
    return match;
  });
  return format;
}

/**
 * 格式化时间格式字符串
 * 字符串规则以及format规则同stringToDate，dateToString函数
 */
export function formatDateString(str, format) {
  return dateToString(stringToDate(str), format);
}

export function timeToNow(time) {
  const dValue = Date.now() - stringToDate(time).valueOf();
  const minutes = dValue / 1000 / 60;
  const hour = minutes / 60;
  const day = hour / 24;
  const month = day / 30;
  let val = '';
  if (minutes < 1) {
    val = "刚刚";
  } else if (minutes < 60) {
    val = Math.round(minutes) + "分钟前";
  } else if (hour < 24) {
    val = Math.round(hour) + "小时前";
  } else if (month < 1) {
    val = Math.round(day) + "天前";
  } else {
    val = Math.round(month) + "月前";
  }
  return val;
}

//时间截取日期2021-12-22 13:12:12 截取成为2021-12-12
export function timeToDate(time) {
  // let time = time.split('-').join('/');
  if (time.indexOf(' ') !== -1) {
    return time.slice(0, time.indexOf(' '));
  } else {
    return time;
  }
}

//时间截取日期2021-12-22 13:12:12 截取成为2021-12-12
export function timeToTime(time) {
  return time.slice(11, 16);
}

//时间戳格式化 2019-08-26 形式
export function stamp2Date(value) {
  var b = new Date(value);
  var year = b.getFullYear() + '-';
  var month = (b.getMonth() + 1);
  var date = b.getDate();
  month = month < 10 ? '0' + (b.getMonth() + 1) + '-' : (b.getMonth() + 1) + '-';
  date = date < 10 ? '0' + (b.getDate()) : date;
  var str = String(year) + String(month) + String(date) + '';
  return str;
}

//深拷贝
export function deepCopy(data) {
  if (!Array.isArray(data) && !isObject(data)) {
    return data;
  } else if (Array.isArray(data)) {
    return data.map(item => deepCopy(item));
  } else if (isObject(data)) {
    let ret = {};
    Object.keys(data).forEach(key => {
      ret[key] = deepCopy(data[key]);
    });
    return ret;
  }
}


/**
 * 生成一个唯一的字符串ID，每次执行结果必定不一样
 */
export function getUid() {
  const random = "0123456789abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0; i < 4; i++) {
    str += random[getRandom(0, 35)];
  }
  return new Date().valueOf() + str;
}

/**
 * 生成 n - m 之间的随机数
 */
export function getRandom(n, m) {
  return Math.floor(Math.random() * (m - n + 1) + n);
}

