import dayjs from 'dayjs'

/**
 * @description 小于10的数字前面加0
 * @param {*} number
 * @returns
 */
const zero = (number) => {
  number = number < 10 ? '0' + number : number
  return number
}

/**
 *
 * @param {*} startTime 开始时间 '2022-08-01'
 * @param {*} endTime 结束时间 '2022-08-31'
 * @returns
 */
export const timeInterval = (startTime, endTime) => {
  const ms = new Date(endTime).getTime() - new Date(startTime).getTime()
  const s = ms / 1000
  const day = s / (24 * 60 * 60)
  const timeArr = []
  for (let i = 0; i <= day; i++) {
    timeArr.push(dayjs(startTime).add(i, 'day').format('YYYY-MM-DD'))
  }
  return timeArr
}

/**
 *
 * @description 显示当前的时间(定时器调用)
 * @returns
 */
// 页面调用 => const { year, month, day, h, m, s } = this.cqq.nowTime()
export const nowTime = () => {
  const nowTime = new Date()
  const year = zero(nowTime.getFullYear())
  const month = zero(nowTime.getMonth() + 1)
  const day = zero(nowTime.getDate())
  const h = zero(nowTime.getHours())
  const m = zero(nowTime.getMinutes())
  const s = zero(nowTime.getSeconds())
  let week = nowTime.getDay()
  // 星期日 week 等于 0,根据业务可以进行处理
  if (week === 0) week = 7
  return {
    year: String(year),
    month: String(month),
    day: String(day),
    week: week,
    h: String(h),
    m: String(m),
    s: String(s)
  }
}

export const elDateformate = (nowTime) => {
  const year = zero(nowTime.getFullYear())
  const month = zero(nowTime.getMonth() + 1)
  const day = zero(nowTime.getDate())
  const h = zero(nowTime.getHours())
  const m = zero(nowTime.getMinutes())
  const s = zero(nowTime.getSeconds())
  const str = `${year}-${month}-${day} ${h}:${m}:${s}`
  return str
}

export const elDateformate2 = (nowTime) => {
  const year = zero(nowTime.getFullYear())
  const month = zero(nowTime.getMonth() + 1)
  const day = zero(nowTime.getDate())
  const str = `${year}-${month}-${day}`
  return str
}

export const sort = (data, date, flag) => {
  if (!flag) {
    // 默认升序
    return data.sort((a, b) => Date.parse(a[date].replace(/-/g, '/')) - Date.parse(b[date].replace(/-/g, '/')))
  } else {
    // 降序
    return data.sort((a, b) => Date.parse(b[date].replace(/-/g, '/')) - Date.parse(a[date].replace(/-/g, '/')))
  }
}

export default {
  install (Vue) {
    Vue.prototype.cqq = {
      zero,
      nowTime,
      elDateformate,
      elDateformate2,
      timeInterval,
      sort
    }
  }
}
