import { getAccessToken } from '@/utils/auth'
import { diceCode } from '@/utils'

const SOCKET_BASE = import.meta.env.VITE_SOCKET_PATH


class TrafficSocket {

  #LINKS = {
    IN_CAR: SOCKET_BASE + '/qxsd/realTimeCar',
    IN_EVENT: SOCKET_BASE + '/qxsd/realTimeEvent',
    OUT_CAR: SOCKET_BASE + '/qxsd/realTimeCar1',
    OUT_EVENT: SOCKET_BASE + '/qxsd/realTimeEvent1'
  }

  isManualClose = false
  link = null
  socket = null
  callmap = {}
  
  constructor(link) {
    this.link = this.#LINKS[link]
  }

  start (fuc) {

    this.socket = new WebSocket(this.link + '?token=' + getAccessToken())
    
    this.socket.addEventListener('open', () => {
      console.log('socket start')
    })

    this.socket.addEventListener('message', res => {
      // console.log(JSON.parse(res.data))
      fuc(JSON.parse(res.data))
    })

    this.socket.addEventListener('close', (e) => {
      if (!this.isManualClose) {
        console.log('🚀 ~ WebSocket异常断开，尝试重连...')
        this.start(fuc)
      } else {
        console.log('🚀 ~ WebSocket手动关闭')
      }
    })

  }

  close () {
    this.isManualClose = true // 设置手动关闭标志
    this.socket.close()
  }


}

export default TrafficSocket

// export const insocketCar = new TrafficSocket('IN_CAR')
// export const insocketEvent = new TrafficSocket('IN_EVENT')

// export const outsocketCar = new TrafficSocket('OUT_CAR')
// export const outsocketEvent = new TrafficSocket('OUT_EVENT')
