import Big from 'big.js'
import fecha from 'element-ui/src/utils/date'

/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
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 = 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
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
* 检查是否为数字
* @param  {any} str 待检查数据
* @return {boolean} true表示是有效的数字;false表示不是有效的数字
*/
export function isNum(str) {
  const checkStr = String(str)
  if (checkStr === '') {
    return false
  }
  const reg = /^[-+]?\d*(?:\.\d+)?$/i
  return reg.test(checkStr)
}

/**
* 格式化数字为金额格式
* @param  {string|number} num 数字
* @param  {string} thousandSep  千分隔符
* @param  {string} fixed  保留的小数位数
* @param  {number} roundMode 舍入模式
* @return {any} 格式化后的数字
*/
export function formatNum(num, thousandSep = ',', fixed = 2, roundMode = Big.roundDown) {
  if (!isNum(num)) {
    return num
  }
  const str = String(num)
  const firstChar = str[0]
  const sign = (firstChar === '+' || firstChar === '-' ? firstChar : '')
  const handleStr = sign ? str.substring(1) : str
  const bigInst = new Big(handleStr)
  const fixedStr = bigInst.toFixed(fixed, roundMode)
  const arr = fixedStr.split('.')
  const zs = arr[0]
  const xs = arr[1] || ''
  const reg = /(\d)(?=(\d{3})+$)/g
  const zsFmt = zs.replace(reg, `$1${thousandSep}`)
  const xsFmt = xs ? `.${xs}` : ''
  const completeFmt = `${sign}${zsFmt}${xsFmt}`
  return completeFmt
}

/**
* 触发浏览器下载文件
* @param  {Blob} blob 文件对象
* @param  {string} fileName 文件名
*/
export function saveBlob(blob, fileName) {
  const a = document.createElement('a')
  a.style = 'display:none;'
  document.body.appendChild(a)
  const fileUrl = window.URL.createObjectURL(blob)
  a.href = fileUrl
  a.download = fileName
  a.click()
  window.URL.revokeObjectURL(fileUrl)
  document.body.removeChild(a)
}

/**
* 解析日期字条串为日期对象
* @param  {string} str 日期字符串
* @param  {string} fmt 日期格式
* @return {obj} 日期对象
*/
export function parseDate(str, fmt) {
  return fecha.parse(str, fmt)
}

/**
* 检查日期范围在指定的天数内
* @param  {string} beginDate 开始日期字符串
* @param  {string} beginDateFmt 开始日期格式字符串
* @param  {string} endDate 结束日期字符串
* @param  {string} endDateFmt 结束日期格式字符串
* @param  {number} max 两个日期相隔的最大天数
* @return {boolean} true两个日期相隔的天数小于等于max;false两个日期相隔的天数大于max
*/
export function checkTimeRange(beginDate, beginDateFmt, endDate, endDateFmt, max) {
  const start = parseDate(beginDate, beginDateFmt)
  const stop = parseDate(endDate, endDateFmt)
  const days = (stop.getTime() - start.getTime()) / (24 * 60 * 60 * 1000)
  return days <= max
}

/**
 * 检查值是否不为空
 * @param {*} val
 * @return {boolean} true不为空;false为空
 */
export function isNotBlank(val) {
  return val !== null && val !== undefined && val !== '' && !isNaN(val)
}
