import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.locale('zh-cn') // 设置为中文
// 使用相对时间插件
dayjs.extend(relativeTime)
export function RelativeTime(time: number) {
  return dayjs(time * 1000).fromNow()
}

export const getShowDay = (day: string) => {
  const weekMap = {
    0: '星期日',
    1: '星期一',
    2: '星期二',
    3: '星期三',
    4: '星期四',
    5: '星期五',
    6: '星期六'
  }
  const targetDate = dayjs(day).startOf('day')
  const today = dayjs().startOf('day')
  const yesterday = today.subtract(1, 'day')
  const tomorrow = today.add(1, 'day')
  const weekDay = weekMap[targetDate.day()]

  if (targetDate.isSame(today, 'day')) {
    return `今天 ${weekDay}`
  } else if (targetDate.isSame(yesterday, 'day')) {
    return `昨天 ${weekDay}`
  } else if (targetDate.isSame(tomorrow, 'day')) {
    return `明天 ${weekDay}`
  } else {
    return `${day} ${weekDay}`
  }
}
export function ShowLastTime(time: string) {
  return time ? dayjs(time).fromNow() : '-'
}

export function showDay(time: number) {
  return time ? dayjs(time).format('YYYY-MM-DD') : '-'
}

export function getDay(num?: number) {
  if (num) {
    const yesterday = dayjs().subtract(num, 'day')
    console.log(yesterday.format('YYYY-MM-DD'))
    return yesterday.format('YYYY-MM-DD')
  }
  return dayjs().format('YYYY-MM-DD')
}

export function getTime() {
  return dayjs().format('YYYY-MM-DD HH:mm:ss')
}

export function getOverDay(num: number, type: string) {
  const currentDate = dayjs()
  const formattedCurrentDate = currentDate.format('YYYY-MM-DD')
  console.log('当前日期:', formattedCurrentDate)
  if (type === 'day') {
    //获取过去num天的日期
    const pastFifteenDays = dayjs().subtract(num, 'day')
    const formattedPastFifteenDays = pastFifteenDays.format('YYYY-MM-DD')
    return [formattedPastFifteenDays, formattedCurrentDate]
  }
  if (type === 'month') {
    // 获取过去num个月的日期
    const pastTwelveMonths = dayjs().subtract(num, 'month')
    const formattedPastTwelveMonths = pastTwelveMonths.format('YYYY-MM-DD')
    return [formattedPastTwelveMonths, formattedCurrentDate]
  }
}

export function getThreeMonthsLater(num = 3, dateString: string) {
  const date = dayjs(dateString)
  const threeMonthsLater = date.add(num || 3, 'month')
  return threeMonthsLater.format('YYYY-MM-DD')
}

export function isSameDay(day: string) {
  //是否是当天-还款日期
  const date1 = new Date(day)
  const date2 = new Date()
  return (
    date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
  )
}

export function getTimeStatus(endTime: string) {
  const now = dayjs()
  const end = dayjs(endTime)

  if (end.isBefore(now)) {
    // 已超时
    const hours = now.diff(end, 'hour')
    const minutes = now.diff(end, 'minute') % 60

    let label = '已过期望处理时间：'
    if (hours > 0) {
      label += `${hours}个小时`
    }
    if (minutes > 0) {
      label += `${minutes}分钟`
    }

    return {
      label: label,
      status: '4',
      color: '#EA0000'
    }
  } else {
    // 还未到结束时间
    const diffHours = end.diff(now, 'hour')
    const diffMinutes = end.diff(now, 'minute') % 60

    let status
    let color
    if (diffHours >= 24) {
      status = '1'
      color = '#24BC21'
    } else if (diffHours >= 2) {
      status = '2'
      color = '#0082FA'
    } else {
      status = '3'
      color = '#F97316'
    }

    const days = Math.floor(diffHours / 24)
    const hours = diffHours % 24

    let label = '上门时间还剩：'
    if (days > 0) {
      label += `${days}天`
    }
    if (hours > 0) {
      label += `${hours}个小时`
    }
    if (diffMinutes > 0) {
      label += `${diffMinutes}分钟`
    }

    return {
      label: label,
      status: status,
      color: color
    }
  }
}

export function generateTimeSlots(externalDate = null) {
  // 如果没有外部传入日期，使用当前日期
  const baseDate = externalDate ? dayjs(externalDate) : dayjs()
  const now = externalDate ? dayjs(externalDate) : dayjs() // 使用相同的日期作为当前时间
  const startHour = 8 // 开始时间 8:00
  const endHour = 18 // 结束时间 18:00
  const interval = 2 // 间隔2小时
  const currentTime = now.valueOf() // 当前时间的时间戳
  const slots = []
  let currentStart = startHour
  // 生成所有时间段
  while (currentStart < endHour) {
    const currentEnd = Math.min(currentStart + interval, endHour)
    // 使用基准日期设置具体时间
    const startTime = baseDate.hour(currentStart).minute(0).second(0)
    const endTime = baseDate.hour(currentEnd).minute(0).second(0)

    const startStr = startTime.format('HH:mm')
    const endStr = endTime.format('HH:mm')

    // 检查当前时间是否在这个时间段内
    const isCurrentPeriod = currentTime >= startTime.valueOf() && currentTime < endTime.valueOf()

    // 只有当时间段还未结束时才显示
    if (endTime.valueOf() > currentTime) {
      slots.push({
        label: isCurrentPeriod ? '两个小时内' : `${startStr}-${endStr}`,
        str: startStr,
        end: endStr,
        isCurrent: isCurrentPeriod,
        date: baseDate.format('YYYY-MM-DD'),
        startTimestamp: startTime.valueOf(),
        endTimestamp: endTime.valueOf()
      })
    }

    currentStart = currentEnd
  }
  console.log('slots', slots)
  return slots
}

export function getCurrentHour() {
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()
  console.log(currentHour, currentMinute, 'dayjs().hour()')
  return { currentHour, currentMinute }
  // return dayjs().hour()
}
export function getTheFutureDay(num = 1) {
  //获取未来num天的日期
  const pastFifteenDays = dayjs().add(num, 'day')
  return pastFifteenDays.format('YYYY-MM-DD')
}

export function showCurrentTime() {
  return dayjs().format('HH:mm')
}

export function isDatePassed(fixedDate: string) {
  //判断固定日期是否已过
  console.log(dayjs().isAfter(dayjs(fixedDate)), 'dayjs().isAfter(dayjs(fixedDate))')
  return dayjs().isAfter(dayjs(fixedDate), 'day')
}

export function showWeekDay() {
  const weekMap = {
    0: '星期日',
    1: '星期一',
    2: '星期二',
    3: '星期三',
    4: '星期四',
    5: '星期五',
    6: '星期六'
  }
  const today = weekMap[dayjs().day()]
  return today
}

export function getDayTime(time?: string) {
  if (time) {
    let dataTime = time?.replace(/-/g, '/')
    return dayjs(dataTime).format('YYYY-MM-DD HH:mm')
  }
  return dayjs().format('YYYY-MM-DD HH:mm')
}

export function specificTime(targetTime: string) {
  let dataTime = targetTime?.replace(/-/g, '/')
  const now = dayjs()
  const target = dayjs(dataTime)
  let hoursDiff = Math.abs(target.diff(now, 'hour', true)) <= 2 || target.isBefore(now)
  console.log(hoursDiff, 'hoursDiff')
  //是否在2小时内的
  return hoursDiff
}

export function isOverHalfHourPast(targetTime: string) {
  let dataTime = targetTime?.replace(/-/g, '/')
  // 获取当前时间 [citation:5]，是否超过目标时间30分钟
  const now = dayjs()
  const target = dayjs(dataTime)

  // 计算当前时间与目标时间的时间差（分钟）
  const diffInMinutes = now.diff(target, 'minute')

  // 判断是否超过30分钟
  return diffInMinutes > 30
}
export function isWithinTimeRange(targetTime: string, minutesRange = 30) {
  let dataTime = targetTime?.replace(/-/g, '/')
  // 判断当前时间是否在目标时间的当天24小时内
  console.log(targetTime, dataTime, 'targetTime')
  const now = dayjs()
  // 构建打卡时间
  const checkTime = dayjs(dataTime)

  // 计算可打卡时间范围 - 当天0点到24点
  const startTime = checkTime.startOf('day') // 当天0点
  const endTime = checkTime.endOf('day') // 当天23:59:59

  // 判断当前时间是否在范围内
  return now.isAfter(startTime) && now.isBefore(endTime)
}
export function showTime(time: string) {
  let dataTime = time?.replace(/-/g, '/')
  return dataTime ? dayjs(dataTime).format('HH:mm') : ''
}

export function isCanCheckIn(startTime: string, endTime: string) {
  let dataTimeStr = startTime?.replace(/-/g, '/')
  let dataTimeEnd = endTime?.replace(/-/g, '/')

  const now = dayjs()
  const nowTimestamp = now.valueOf() // 获取时间戳

  // 解析传入的开始和结束时间
  const startTimeObj = dayjs(dataTimeStr)
  const endTimeObj = dayjs(dataTimeEnd)

  // 验证时间格式
  if (!startTimeObj.isValid()) {
    console.error('开始时间格式无效:', startTime)
    return false
  }

  if (!endTimeObj.isValid()) {
    console.error('结束时间格式无效:', endTime)
    return false
  }

  // 检查结束时间是否早于开始时间
  if (endTimeObj.valueOf() < startTimeObj.valueOf()) {
    console.error('结束时间不能早于开始时间')
    return false
  }

  // 获取时间戳进行比较
  const startTimestamp = startTimeObj.valueOf()
  const endTimestamp = endTimeObj.valueOf()

  // 判断当前时间是否在时间范围内（包含开始和结束时间）
  return nowTimestamp >= startTimestamp && nowTimestamp <= endTimestamp
}
