/**
 * Created by luyanan on 19/3/1.
 */
import { DateFormat } from '@/utils'

/**
 * 上月1号至今的时间
 */
export function dayListFn(fl) {
  var dayList = []
  var preMoth = ''
  var now = new Date()
  var day1 = new Date()
  day1.setMonth(now.getMonth() - 1)
  day1.setDate(1)
  var day2 = new Date()
  day2.setDate(day2.getDate())
  var days = (day2 - day1) / (24 * 60 * 60 * 1000)
  dayList[0] = { time: DateFormat('yyyy-MM-dd', day1) }
  preMoth = DateFormat('yyyyMMdd', day1)
  for (var i = 1; i < days + 1; i++) {
    day1.setDate(day1.getDate() + 1)
    dayList[i] = { time: DateFormat('yyyy-MM-dd', day1) }
  }
  return fl ? preMoth : dayList
}

/**
 * 创建chart对象
 */
export function chartModel($data) {
  var allData = dayListFn()
  allData.forEach(day => {
    var time = (day.time).replace(/-/g, '')
    day.pc = 0
    day.h5 = 0
    $data.forEach(log => {
      if (time === log.day) {
        if (log.source === '1') {
          day.pc = log.pv
        }
        if (log.source === '2') {
          day.h5 = log.pv
        }
      }
      day.num = day.pc + day.h5
    })
  })
  return allData
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
