export function _stopPropagation(e: Event) {
  e.stopImmediatePropagation()
  e.stopPropagation()
  e.preventDefault()
}

export function _notice(val: string) {
  const div = document.createElement('div')
  div.classList.add('global-notice')
  div.textContent = val
  document.body.append(div)
  setTimeout(() => {
    document.body.removeChild(div)
  }, 1000)
}

export function _no() {
  _notice('未实现')
}

/** 与 douyin-vue 一致：相对路径封面走 CDN */
const IMG_BASE = 'https://dy.ttentau.top/imgs/images/'

export function _formatNumber(num?: number) {
  if (!num) return '0'
  if (num > 100000000) return (num / 100000000).toFixed(1) + '亿'
  if (num > 10000) return (num / 10000).toFixed(1) + '万'
  return String(num)
}

function _dateFormat(time: number, type = 'Y-M-D') {
  const date = new Date(Number(time))
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const mStr = month < 10 ? `0${month}` : String(month)
  const dayStr = day < 10 ? `0${day}` : String(day)
  if (type === 'M_D') return `${mStr}-${dayStr}`
  return `${year}-${mStr}-${dayStr}`
}

/** 2025年11月1日 */
export function _formatChineseDate(time?: number | string): string {
  if (time === undefined || time === null || time === '') return ''
  let ts = Number(time)
  if (String(time).length === 10) ts *= 1000
  const d = new Date(ts)
  if (Number.isNaN(d.getTime())) return ''
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
}

export function _time(time: number | string) {
  let ts = Number(time)
  if (String(time).length === 10) ts *= 1000
  const date = new Date(ts)
  const now = new Date()
  const d = now.valueOf() - date.valueOf()
  if (d < 1000 * 60) return '刚刚'
  if (d < 1000 * 60 * 60) return `${Math.floor(d / (1000 * 60))}分钟前`
  if (d < 1000 * 60 * 60 * 24) return `${Math.floor(d / (1000 * 60 * 60))}小时前`
  if (d < 1000 * 60 * 60 * 24 * 2) return '1天前'
  if (d < 1000 * 60 * 60 * 24 * 3) return '2天前'
  if (d < 1000 * 60 * 60 * 24 * 4) return '3天前'
  if (date.getFullYear() === now.getFullYear()) return _dateFormat(ts, 'M_D')
  return _dateFormat(ts, 'D')
}

export function _sleep(duration: number) {
  return new Promise<void>((resolve) => setTimeout(resolve, duration))
}

export function random(min: number, max: number) {
  const minCeiled = Math.ceil(min)
  const maxFloored = Math.floor(max)
  return Math.floor(Math.random() * (maxFloored - minCeiled + 1) + minCeiled)
}

export function sampleSize<T>(arr: T[], num: number) {
  const list: T[] = []
  const indexs: number[] = []
  while (list.length !== num && arr.length > 0) {
    const j = random(0, arr.length - 1)
    if (!indexs.includes(j)) {
      indexs.push(j)
      list.push(arr[j])
    }
  }
  return list
}

export function _checkImgUrl(url?: string) {
  if (!url) return ''
  if (
    url.includes('assets/img') ||
    url.includes('file://') ||
    url.includes('data:image') ||
    url.startsWith('http')
  ) {
    return url
  }
  return IMG_BASE + url
}
