import { useWebSocket } from '@vueuse/core'
import { onMounted } from 'vue'

import { useMubiao } from './mubiao'

const { updateMubiaoPos } = useMubiao()
export const useMuBiaoPositionWS = () => {
  onMounted(() => {
    initWebSocket()
  })
}

const initWebSocket = () => {
  const {
    status: wsStatus,
    data: eventData,
    send,
    close,
  } = useWebSocket(`ws://192.168.10.187:8080/message/ts`, {
    autoReconnect: {
      retries: 5,
      delay: 5000,
      onFailed: () => {
        console.log('mubiao WS ====> 连接失败')
      },
    },
    heartbeat: {
      message: 'ping',
      interval: 5000,
      pongTimeout: 10000,
    },
  })

  watch(wsStatus, newStatus => {
    switch (newStatus) {
      case 'OPEN':
        console.log('mubiao WS ====> 连接成功')
        break
      case 'CLOSED':
        console.log('mubiao WS ====> 连接关闭')
        break
      default:
        console.log('mubiao WS ====> 连接中...')
        break
    }
  })

  watch(eventData, newEventData => {
    // console.log('eventData =====> ', typeof newEventData)

    if (typeof newEventData === 'string') {
      const newEventDataObj = JSON.parse(newEventData)
      if (newEventDataObj.code === '200') {
        const { data } = newEventDataObj
        // console.log('data =====> ', data)
        updateMubiaoPos(data)
      }
    }
  })
}
