export { parseTime, formatTime } from '@/utils'

/**
 * Show plural label if time is plural number
 * @param {number} time
 * @param {string} label
 * @return {string}
 */
function pluralize(time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

/**
 * @param {number} time
 */
export function timeAgo(time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

/**
 * Number formatting
 * like 10000 => 10k
 * @param {number} num
 * @param {number} digits
 */
export function numberFormatter(num, digits) {
  const si = [
    { value: 1E18, symbol: 'E' },
    { value: 1E15, symbol: 'P' },
    { value: 1E12, symbol: 'T' },
    { value: 1E9, symbol: 'G' },
    { value: 1E6, symbol: 'M' },
    { value: 1E3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
    }
  }
  return num.toString()
}

/**
 * 10000 => "10,000"
 * @param {number} num
 */
export function toThousandFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

/**
 * Upper case first char
 * @param {String} string
 */
export function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}
export function numFilter(value) {
  if(value){
    const realVal = parseFloat(value).toFixed(2)
    return realVal
  }else{
    return '—'
  }
}
export function PercentFilter(value) {
  if(value > 0){
    const realVal = parseFloat(value).toFixed(2)
    return realVal+'%'
  }else{
    return '—'
  }
}
export function exchangerFilter(value) {
  if(value){
    const realVal = parseFloat(value).toFixed(2)
     return realVal
  }else{
    return ''
  }
}
export function RecordFilter(value){
  if(value){
    return value.substring(0,8)+'****'+value.substring(value.length-8)
  }return ''
}
export function HeightFilter(value){
  if(value){
    return (value/10)+'rem'
  }
}
//过滤设备监控速度、位置
export function equipmentFilter(num,len =5){
  let numStr = typeof(num) == "number" ? `${num}` : num // 判断类型，统一转字符串处理
  if(!numStr)return ''; // 空值return 空字符串
  numStr=numStr.replace(/[^0-9.]/g,'') // 限制值只能为0-9和字符‘.’
  let isDecimalIndex = numStr.indexOf('.') // 判断存不存在小数位
  if(isDecimalIndex === -1)return `${Number(numStr)}` // 不存在小数位，返回处理后的数字
  let integer = numStr.slice(0,isDecimalIndex) // 获取整数位
  let Decimals = numStr.slice(isDecimalIndex+1) // 获取小数位
  Decimals=Decimals.replace(/[^0-9]/g,'').slice(0,len) // 处理小数位中的无效字符，并截取指定长度
  return `${Number(integer)}.${Decimals || ''}` // 组装数据。并在处理小数位事，将无效字符处理成空串
}