const util = {}

const date = (util.date = util.date || {})

date.format = function (d, pattern) {
  if (Object.prototype.toString.call(d) !== '[object Date]') {
    d = new window.Date(d)
  }
  var i
  pattern = pattern || 'yyyy-MM-dd'
  var y = d.getFullYear()
  var o = {
    'M': d.getMonth() + 1,
    'd': d.getDate(),
    'H': d.getHours(),
    'm': d.getMinutes(),
    's': d.getSeconds()
  }
  pattern = pattern.replace(/(y+)/ig, function (a, b) {
    var len = Math.min(4, b.length)
    return (y + '').substr(4 - len)
  })
  for (i in o) {
    pattern = pattern.replace(new RegExp('(' + i + '+)', 'g'), function (a, b) {
      return (o[i] < 10 && b.length > 1) ? '0' + o[i] : o[i]
    })
  }
  return pattern
}

date.parseDate = function (str) { // 解析形如yyyy-MM-dd HH:mm:ss的日期字符串为Date对象
  if (!str) {
    console.error('dateTime.js # DateTime.parseDate : 没有传入参数！')
    return null
  }
  var regex = /^(\d{4})-(\d{1,2})-(\d{1,2})((?:\s|\u00a0)(\d{1,2}):(\d{1,2})(:(\d{1,2})(\.\d{1,2})?)?)?$/
  if (!regex.test(str)) {
    console.error('dateTime.js # DateTime.parseDate : 参数错误 ' + str)
    return false
  }
  regex.exec(str)
  var y = RegExp.$1
  var M = RegExp.$2
  var d = RegExp.$3
  var h = RegExp.$5
  var m = RegExp.$6
  var s = RegExp.$8
  var dt = new Date(y, M - 1, d)
  if (!h) {
    h = 0
    m = 0
  }
  dt.setHours(h)
  dt.setMinutes(m)
  if (!s) {
    s = 0
  }
  dt.setSeconds(s)
  return dt
}

/**
 * string 相关工具方法
 */
const string = (util.string = util.string || {})

string.escapeReg = function (str) {
  return str.replace(new RegExp('([.*+?^=!:\u0024{}()|[\\]/\\\\])', 'g'), '\\$1')
}

string.htmlEncode = function (str) {
  return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&#32;')
}

string.htmlDecode = function (str) {
  return str.replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&#32;/g, ' ').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&')
}

if (typeof String.prototype.trim === 'function') {
  string.trim = function (str) {
    return str.trim()
  }
} else {
  string.trim = function (str) {
    return str.replace(/^[\s\uFEFF\u00A0]+|[\s\uFEFF\u00A0]+$/g, '')
  }
}

string.isNumber = function (str) {
  if (string.trim(str) === '') {
    return false
  }
  return (/^-?\d+(\.\d+)?$/).test('' + str)
}

string.isInt = function (str) {
  if (string.trim(str) === '') {
    return false
  }
  return (/^-?\d+$/).test('' + str)
}
string.isTime = function (str) {
  if (string.trim(str) === '') {
    return false
  }
  var arr = str.split(':')
  if (arr.length !== 3) {
    return false
  }
  if (!string.isInt(arr[0]) || !string.isInt(arr[1]) || !string.isNumber(arr[2])) {
    return false
  }
  var h = Number(arr[0])
  var m = Number(arr[1])
  var s = Number(arr[2])
  if (h < 0 || h > 24 || m < 0 || m > 60 || s < 0 || s > 60) {
    return false
  }
  var dt = new Date()
  dt.setHours(arr[0])
  dt.setMinutes(arr[1])
  dt.setSeconds(arr[2])
  return dt.toString().indexOf('Invalid') < 0
}
string.isDate = function (str) {
  str = String(str)
  if (string.trim(str) === '') {
    return false
  }
  if (str.indexOf('-') === -1) {
    return false
  }
  var arr = str.split('-')
  if (arr.length !== 3) {
    return false
  }
  if (!string.isInt(arr[0]) || !string.isInt(arr[1]) || !string.isInt(arr[2])) {
    return false
  }
  var y = Number(arr[0])
  var M = Number(arr[1])
  var d = Number(arr[2])
  var isLeapYear = arr[0].substr(arr[0].length - 2, 2) === '00' ? y % 400 : y % 4
  isLeapYear = !isLeapYear
  if (M < 1 || M > 12 || d < 1 || d > 31) {
    return false
  } else if (d > 30 && (M === 4 || M === 6 || M === 9 || M === 11)) {
    return false
  } else if (d > 29 && M === 2 && isLeapYear) {
    return false
  } else if (d > 28 && M === 2 && !isLeapYear) {
    return false
  }
  var dt = new Date()
  dt.setFullYear(arr[0])
  dt.setMonth(arr[1])
  dt.setDate(arr[2])
  return dt.toString().indexOf('Invalid') < 0
}

string.isDateTime = function (str) {
  if (string.trim(str) === '') {
    return false
  }
  if (str.indexOf(' ') < 0) {
    return string.isDate(str)
  }
  var arr = str.split(' ')
  if (arr.length < 2) {
    return false
  }
  return string.isDate(arr[0]) && string.isTime(arr[1])
}

/*
    * 字符串模板
    st:0,1:未找到属性是是否保留

      @param {String} str 模板字符串
      @param {Object} obj 数据对象
      @param {undefined|Number} [st] 未找到属性是是否保留,undefined 或 0 或 1 或其它
      @param {Boolean} [urlencode] 是否用encodeURIComponent方法进行编码
      @return {String}

    eg. "{a} love {b}.".tmpl({a:"I",b:"you"});
    返回 "I love you."
    */
string.tmpl = function (str, obj, st, urlencode) {
  return str.replace(/\{([\w_$]+)\}/g, function (c, $1) {
    var a = obj[$1]
    if (a === undefined || a === null) {
      if (st === undefined || st === null) {
        return ''
      }
      switch (st) {
        case 0:
          return ''
        case 1:
          return $1
        default:
          return c
      }
    }
    if (Object.prototype.toString.call(a) === '[object Function]') {
      a = a($1)
    }
    return urlencode ? encodeURIComponent(a) : a
  })
}
/**
 * 获取字符串Utf8字符数
 */
string.getLengthEx = function (str) {
  var ret = 0
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 255) {
      ret += 3
    } else {
      ret += 1
    }
  }
  return ret
}
/**
 * url 相关工具方法
 */
const url = (util.url = util.url || {})

url.getQueryValue = (url, key) => {
  if (!key) {
    key = url
    url = window.location.href
  }
  var reg = new RegExp('(^|&|\\?|#)' + util.string.escapeReg(key) + '=([^&#]*)(&|\u0024|#)', '')
  var match = ('' + url).match(reg)
  if (match) {
    return match[2]
  }
  return null
}

url.join = (baseURL, path) => {
  baseURL = baseURL.match(/https?:\/\//) ? baseURL : window.location.protocol + '//' + baseURL
  baseURL = baseURL.endsWith('/')
    ? baseURL.substring(0, baseURL.length - 1)
    : baseURL
  path = path.startsWith('/') ? path : `/${path}`

  return baseURL + path
}

if (window.util && window.util.string) {
  for (let k in util){
    if (util[k]){
      Object.assign(util[k], window.util[k])
    } else {
      util[k] = window.util[k]
    }
  }
}

module.exports = util
