import { nanoid } from 'nanoid'

// 礼物
const gifts = ['棒棒糖', '墨镜', '鲜花', '亲吻', '兔耳朵']
// 头像
const avatars = [
  '/live/avatar/1.png',
  '/live/avatar/2.png',
  '/live/avatar/3.png',
  '/live/avatar/4.jpeg',
  '/live/avatar/5.jpeg',
  '/live/avatar/6.jpeg',
  '/live/avatar/7.jpeg',
  '/live/avatar/8.jpeg',
  '/live/avatar/9.jpeg',
  '/live/avatar/10.jpeg',
  '/live/avatar/11.jpeg',
  '/live/avatar/12.jpeg',
  '/live/avatar/13.jpeg',
]

export interface Viewer {
  id: string
  name: string
  avatar: string
}

export interface Message {
  id: string
  type: 'like' | 'gift' | 'join' | 'leave'
  content: string
  timestamp: number
  currentTime: number
  user: Viewer
}

export interface UseLiveChatOptions {
  initViewerCount?: number
  autoStart?: boolean
  updateInterval?: number
  defaultMessages?: Message[]
}

export function useLiveChat(options: UseLiveChatOptions = {}) {
  const { initViewerCount = 20, autoStart = false, updateInterval = 1000, defaultMessages } = options
  const viewers = ref<Viewer[]>([])
  const messages = ref<Message[]>([])
  const currentTime = ref(0)
  const stats = reactive({
    totalViewers: 0, // 总在线人数
    peakViewers: 0, // 最高在线人数
    totalGifts: 0, // 总送礼数
    totalLikes: 0, // 总点赞人数
    totalGiftViewers: 0, // 总送礼人数
  })

  // 生成用户
  const generateViewer = () => {
    const id = nanoid(4)
    return { id, name: `用户_${id}`, avatar: avatars[Math.floor(Math.random() * avatars.length)] }
  }

  // 随机获取用户
  const getRandomViewer = () => {
    return viewers.value[Math.floor(Math.random() * viewers.value.length)]
  }

  // 随机加入
  const randomJoin = () => {
    const user = generateViewer()
    addMessage({ type: 'join', content: '来了', user })
  }

  // 随机离开
  const randomLeave = () => {
    const user = generateViewer()
    addMessage({ type: 'leave', content: '离开了', user })
  }

  // 随机送礼物
  const randomGift = () => {
    const user = getRandomViewer()
    const gift = gifts[Math.floor(Math.random() * 5)]
    addMessage({ type: 'gift', content: `送了一个${gift}`, user })
  }

  // 随机点赞
  const randomLike = () => {
    const user = getRandomViewer()
    addMessage({ type: 'like', content: '点赞了', user })
  }

  // 发送消息
  const addMessage = (message: Omit<Message, 'id' | 'currentTime' | 'timestamp'>) => {
    switch (message.type) {
      // 进入直播
      case 'join':
        viewers.value.push(message.user)
        stats.totalViewers++
        stats.peakViewers = Math.max(viewers.value.length, stats.peakViewers)
        break
      // 离开直播
      case 'leave':
        viewers.value = viewers.value.filter((v) => v.id !== message.user.id)
        // stats.totalViewers--
        break
      // 点赞
      case 'like':
        stats.totalLikes++
        break
      // 送礼物
      case 'gift':
        stats.totalGifts++
        stats.totalGiftViewers++
        break
    }
    messages.value.push({ id: nanoid(), currentTime: currentTime.value, timestamp: Date.now(), ...message })
  }

  // 随机事件生成
  const generateRandomEvents = () => {
    const rand = Math.random()
    if (rand < 0.8) randomJoin()
    if (rand < 0.4) randomLeave()
    if (rand < 0.7) randomGift()
    if (rand < 0.8) randomLike()
  }

  let timer: number | null = null
  // 开始
  const start = () => {
    // 初始化观众
    for (let i = 0; i < initViewerCount; i++) {
      randomJoin()
    }
    // 开始定时更新
    timer = setInterval(generateRandomEvents, updateInterval)
  }
  const stop = () => {
    if (timer) clearInterval(timer)
    timer = null
  }
  if (autoStart) start()

  const reset = () => {
    viewers.value = []
    messages.value = []
    Object.assign(stats, {
      totalViewers: 0, // 总在线人数
      peakViewers: 0, // 最高在线人数
      totalGifts: 0, // 总送礼数
      totalLikes: 0, // 总点赞人数
      totalGiftViewers: 0, // 总送礼人数
    })
  }
  watch(
    currentTime,
    () => {
      if (defaultMessages && defaultMessages.length > 0) {
        reset()
        defaultMessages.forEach((message) => {
          if (message.currentTime <= currentTime.value) addMessage(message)
        })
      }
    },
    { immediate: true }
  )

  return { viewers, messages, stats, currentTime, start, stop, reset }
}
