/**
 * 获取随机字符串
 * @param {number} length
 * @returns {String}
 */
export function getNonce(length) {
  typeof length !== 'number' && (length = 16)
  const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y', 'z', 2, 3, 4, 5, 6, 7, 8]
  const charsLen = chars.length;
  let str = ''
  for (let i = 0; i < length; i++) {
    const idx = parseInt(charsLen * Math.random())
    let _char = chars[idx];
    if (typeof _char === 'string' && idx % 2) {
      _char = _char.toUpperCase()
    }
    str += _char
  }
  return str
}
/**
 * 将时间字符串、时间戳转成日期对象
 * @param {(object|string|number)} time
 * @returns {Date Object}
 */
export function formatToDate(time) {
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  return date
}
/**
 * 将时间戳转成年月日时分秒
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function dateFormat(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  const date = formatToDate(time)
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}
