const CryptoJS = require('./crypto-js');

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatDuring = s => {
  const days = parseInt(s / (60 * 60 * 24))
  const hours = parseInt((s % (60 * 60 * 24)) / (60 * 60))
  const minutes = parseInt((s % (60 * 60)) / (60))
  const seconds = (s % (60))
  if (days > 0) {
    return formatNumber(days) + '天 ' + formatNumber(hours) + ':' + formatNumber(minutes) + ':' + formatNumber(seconds)
  } else if (hours > 0) {
    return formatNumber(hours) + ':' + formatNumber(minutes) + ':' + formatNumber(seconds)
  } else {
    return formatNumber(minutes) + ':' + formatNumber(seconds)
  }
}

/**
 * 获取当前日期
 */
const getCurrentDate = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

/**
 * 获取精确到秒的时间戳 10位
 */
const getTimastamp = () => {
  return Math.round(Date.parse(new Date()) / 1000);
}

/**
 * 生成随机id
 */
const getRandomId = () => {
  return Math.round(Date.parse(new Date()));
}

/**
 * 去除字符串两端空白
 */
function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "")
}

/**
 * md5
 */
const md5 = str => {
  return CryptoJS.MD5(str).toString(CryptoJS.enc.Hex)
}

/**
 * sha1
 */
const sha1 = str => {
  return CryptoJS.SHA1(str).toString(CryptoJS.enc.Hex)
}

/**
 * sha256
 */
const sha256 = str => {
  return CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex)
}

/**
 * params object sort to String
 */
const objToStr = obj => {
  // 对参数名进行字典排序  
  let params = [];
  for (let key in obj) {
    params.push(key);
  }
  params.sort();

  // 拼接有序的参数名-值串
  let str = '';
  params.forEach((val, idx, arr) => {
    str += (val + "=" + obj[val])
  })
  return str
}

/**
 * 加密请求数据
 */
const sign = obj => {
  let timestamp = getTimastamp()
  let signature = sha1(objToStr({
    ...obj,
    timestamp
  }))
  return {
    ...obj,
    timestamp,
    sign: signature
  }
}

/**
 * 随机获取hex颜色值
 */
const getRandomColor = () => {
  let rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}

/**
 * 判断字符串类型
 * @param {内容} s
 */
const isString = (s) => {
  return (typeof s === 'string') && (Object.prototype.toString.call(s) === '[object String]')
}

/**
 * 判断数字类型
 * @param {内容} n
 */
const isNumber = (n) => {
  return (typeof n === 'number') && (Object.prototype.toString.call(n) === '[object Number]')
}

/**
 * 判断数组类型
 * @param {内容} a
 */
const isArray = (a) => {
  return (typeof a === 'object') && (Object.prototype.toString.call(a) === '[object Array]')
}

/**
 * 判断对象类型
 * @param {内容} o
 */
const isObject = (o) => {
  return (typeof o === 'object') && (Object.prototype.toString.call(o) === '[object Object]')
}

/**
 * 判断函数类型
 * @param {内容} f
 */
const isFunc = (f) => {
  return (typeof f === 'function') && (Object.prototype.toString.call(f) === '[object Function]')
}

/**
 * 判断 Boolean 类型
 * @param {内容} b
 */
const isBoolean = (b) => {
  return (typeof b === 'boolean') && (Object.prototype.toString.call(b) === '[object Boolean]')
}

/**
 * 判断 Undefined 类型
 * @param {内容} u
 */
const isUndefined = (u) => {
  return (typeof u === 'undefined') && (Object.prototype.toString.call(u) === '[object Undefined]')
}

/**
 * 判断 Null 类型
 * @param {内容} n
 */
const isNull = (n) => {
  return (typeof n === 'object') && (Object.prototype.toString.call(n) === '[object Null]')
}

/**
 * 去除字符串前面的空格
 * @param {字符串} s
 */
const ltrim = (s) => {
  if (!isString(s)) {
    throw new Error('string must be given')
  }
  return s.replace(/(^\s*)/g, '')
}

/**
 * 去除字符串后面的空格
 * @param {字符串} s
 */
const rtrim = (s) => {
  if (!isString(s)) {
    throw new Error('string must be given')
  }
  return s.replace(/(\s*$)/g, '')
}

/**
 * 检查某对象是否在数组中
 * @param {被查询的数组} arr
 * @param {被检测的对象} obj
 */
const inArray = (arr, obj) => {
  if (!isArray(arr)) {
    throw new Error('array must be given')
  }
  if (isNull(obj) || isUndefined(obj)) {
    throw new Error('the value to be found must be provided')
  }
  var len = arr.length
  while (len--) {
    if (arr[len] === obj) {
      return true
    }
  }
  return false
}

module.exports = {
  formatTime: formatTime,
  getCurrentDate: getCurrentDate,
  formatDuring: formatDuring,
  trim: trim,
  md5: md5,
  sha1: sha1,
  sha256: sha256,
  objToStr: objToStr,
  getTimastamp: getTimastamp,
  getRandomId: getRandomId,
  sign: sign,
  getRandomColor: getRandomColor,
  isString: isString,
  isNumber: isNumber,
  isArray: isArray,
  isNull: isNull,
  isObject: isObject,
  isFunc: isFunc,
  isBoolean: isBoolean,
  isUndefined: isUndefined,
  inArray: inArray,
  ltrim: ltrim,
  rtrim: rtrim
}
