var WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

function datePolyfill(val) {
  return val < 10 ? '0' + val : val
}

/**
 * 时间戳解析
 * @param ts 单位：ms
 * @param type
 * @returns {string}
 */
function formatTs(ts, type) {
  var date = getDate(ts)
  var obj = {
    YYYY: date.getFullYear(),
    MM: datePolyfill(date.getMonth() + 1),
    DD: datePolyfill(date.getDate()),
    HH: datePolyfill(date.getHours()),
    mm: datePolyfill(date.getMinutes()),
    ss: datePolyfill(date.getSeconds()),
    week: WEEK[date.getDay()]
  }

  if (isNaN(ts)) {
    return ''
  }

  if (type === 'hh:mm:ss') {
    return obj.HH + ':' + obj.mm + ':' + obj.ss
  }

  if (type === 'MM.DD hh:mm') {
    return obj.MM + '.' + obj.DD + ' ' + obj.HH + ':' + obj.mm
  }

  if (type === 'YYYY.MM.DD hh:mm week') {
    return obj.YYYY + '.' + obj.MM + '.' + obj.DD + ' ' + obj.HH + ':' + obj.mm + ' ' + obj.week
  }
  if (type === 'YYYY-MM-DD hh:mm') {
    return obj.YYYY + '-' + obj.MM + '-' + obj.DD + ' ' + obj.HH + ':' + obj.mm
  }

  if (type === 'hh:mm zh') {
    return obj.HH + '小时' + obj.mm + '分'
  }
}

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

function cutDownTime(ts, type) {
  if (ts < 0) {
    return ['0', '00', '00', '00']
  }
  ts = parseInt(ts)
  var D = Math.floor(ts / 24 / 60 / 60)

  // 小时位
  var h = Math.floor((ts - D * 24 * 60 * 60) / 3600)
  // 分钟位
  var m = Math.floor((ts - D * 24 * 3600 - h * 3600) / 60)
  // 秒位
  var s = ts - D * 24 * 3600 - h * 3600 - m * 60

  if (type === 'hh:mm:ss') {
    return formatNumber(D * 24 + h) + ':' + formatNumber(m) + ':' + formatNumber(s)
  }

  if (type === 'hh:mm zh') {
    return (D * 24 + h) + '小时' + m + '分'
  }

  return [D, formatNumber(h), formatNumber(m), formatNumber(s)]
}

function computedFormOrderCarCount(list) {
  var result = 0
  for (var i = 0; i < list.length; i++) {
    result += list[i].car_num
  }
  return result
}

function fen2Yuan(num) {
  return isNaN(num) ? '' : (num * 0.01).toFixed(2) * 1
}

function yuan2Fen(num) {
  if (isNaN(num)) {
    return ''
  }
  var amount = num.toString()
  var index = amount.indexOf('.')
  var arr = amount.split('.')
  var result = arr[0] * 100
  if (index > -1) {
    var temp = arr[1].split('')
    for (var i = 0; i < temp.length; i++) {
      if (i === 0) {
        result += temp[i] * 10
      } else {
        result += temp[i] * 1
      }
    }
  }
  return result
}

function mToKm(distance) {
  if (isNaN(distance)) {
    return ''
  }
  return Math.ceil(distance / 1000) + 'KM'
}

function imgFilter(src) {
  return src.indexOf('http') > -1
    ? src
    : 'https://bashi-1311374120.cos.ap-shanghai.myqcloud.com/wxMini/image' + src
}

module.exports = {
  formatTs: formatTs,
  computedFormOrderCarCount: computedFormOrderCarCount,
  fen2Yuan: fen2Yuan,
  yuan2Fen: yuan2Fen,
  mToKm: mToKm,
  cutDownTime: cutDownTime,
  imgFilter: imgFilter
}
