export function parseTime (time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  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 *= 1000
    }
    date = new Date(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 time_str = 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 time_str
}

export function createListOptions (params) {
  return {
    list: [],
    totalCount: 0,
    loading: false,
    error: false,
    params: {
      pageNum: 1,
      pageSize: 10,
      ...params
    }
  }
}

const units = ['bit', 'KB', 'M', 'G']
export function parseByte (byte) {
  const edge = 1024
  let i = 0
  while (i < units.length - 1) {
    if (byte >= edge / 2) {
      byte /= edge
      i += 1
    } else {
      break
    }
  }
  return `${parseInt(byte * 100) / 100}${units[i]}`
}

export function parseDuration (duration) {
  if (!duration) {
    return '-'
  }
  const seconds = `${duration % 60}`
  const minutes = `${duration / 60 | 0}`
  return `${minutes.padStart(2, '0')}:${seconds.padStart(2, '0')}`
}
