// 数组去重
export function arrayUnique(arr) {
  arr.filter((element, index, arr) => {
    return arr.indexOf(element) === index
  })
}

// 数组去重，数组中值是对象
export function arrayUnique2(arr, name) {
  const hash = {}
  return arr.reduce(function(item, next) {
    hash[next[name]] ? '' : hash[next[name]] = true && item.push(next)
    return item
  }, [])
}

// 时间转时间戳
export function timeToStamp(time) {
  const date = new Date(time)
  return date.getTime()
}

// 数组的深度拷贝
export function arrDeepCopy(arr) {
  const newArr = []
  for (const prop in arr) newArr[prop] = typeof arr[prop] === 'object' ? arrDeepCopy(arr[prop]) : arr[prop]
  return newArr
}

// 对象的深度拷贝
export function objDeepCopy(obj) {
  const newObj = {}
  for (const prop in obj) newObj[prop] = typeof obj[prop] === 'object' ? objDeepCopy(obj[prop]) : obj[prop]
  return newObj
}

function zeroFill(i) {
  if (i >= 0 && i <= 9) {
    return '0' + i
  } else {
    return i
  }
}
// 获取当前时间
export function getNowTime() {
  const date = new Date()
  const month = zeroFill(date.getMonth() + 1)
  const day = zeroFill(date.getDate())
  const hour = zeroFill(date.getHours())
  const minute = zeroFill(date.getMinutes())
  const second = zeroFill(date.getSeconds())
  const time = date.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  return time
}

// 判断类型
export function type(target) {
  const ret = typeof (target)
  const template = {
    '[object Array]': 'array',
    '[object Object]': 'object',
    '[object String]': 'string - object',
    '[object Number]': 'Number - object',
    '[object Boolean]': 'Boolean - object'
  }
  if (target === null) {
    return 'null'
  }
  if (ret === 'object') {
    const str = Object.prototype.toString.call(target)
    return template[str]
  } else {
    return ret
  }
}

export function SectionToChinese(section) {
  const chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const chnUnitChar = ['', '十', '百', '千']
  let strIns = ''
  let chnStr = ''
  let unitPos = 0
  let zero = true
  while (section > 0) {
    const v = section % 10
    if (v === 0) {
      if (!zero) {
        zero = true
        chnStr = chnNumChar[v] + chnStr
      }
    } else {
      zero = false
      strIns = chnNumChar[v]
      strIns += chnUnitChar[unitPos]
      chnStr = strIns + chnStr
    }
    unitPos++
    section = Math.floor(section / 10)
  }
  return chnStr
}

export function sleep(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}
