import { useWebSocket } from '@vueuse/core'
import { ref, computed, watchEffect } from 'vue'
import { getRefreshToken } from '@/utils/auth'
const message = useMessage() // 消息弹窗

const wsUrl = (
  import.meta.env.VITE_BASE_URL + '/infra/ws'
).replace('http', 'ws') + '?token=' + getRefreshToken()

const messageList = ref<{ time: number; text: string }[]>([
  { time: new Date().getTime(), text: '【系统通知】：欢迎使用websocket' }
])
console.log('ws连接')
const { status, data, send, open, close } = useWebSocket(wsUrl, {
  autoReconnect: true,
  heartbeat: true 
})

const getIsOpen = computed(() => status.value === 'OPEN')
send('123');
watchEffect(() => {
  if (!data.value) {
    return
  }
  try {
    // 1. 收到心跳
    if (data.value === 'pong') {
      // state.recordList.push({
      //   text: '【心跳】',
      //   time: new Date().getTime()
      // })
      return
    }

    // 2.1 解析 type 消息类型
    const jsonMessage = JSON.parse(data.value)
    const type = jsonMessage.type
    const content = JSON.parse(jsonMessage.content)
    if (!type) {
      message.error('未知的消息类型：' + data.value)
      return
    }
    // 2.2 消息类型：demo-message-receive
    if (type === 'demo-message-receive') {
      const single = content.single
      if (single) {
        messageList.value.push({
          text: `【单发】用户编号(${content.fromUserId})：${content.text}`,
          time: new Date().getTime()
        })
      } else {
        messageList.value.push({
          text: `【群发】用户编号(${content.fromUserId})：${content.text}`,
          time: new Date().getTime()
        })
      }
      return
    }
    // 2.3 消息类型：notice-push
    if (type === 'notice-push') {
      messageList.value.push({
        text: `【系统通知】：${content.title}`,
        time: new Date().getTime()
      })
      console.log(messageList.value)
      // alert('系统通知：' + content.title)
      return
    }
    message.error('未处理消息：' + data.value)
  } catch (error) {
    message.error('处理消息发生异常：' + data.value)
    console.error(error)
  }
})

export function useGlobalWebSocket() {
  return {
    send,
    open,
    close,
    messageList,
  }
}
