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

const SOCKET_BASE = import.meta.env.VITE_SOCKET_PATH

const 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'
}

// 链接 map
const scoketMap = {}


class TrafficSocket {

  sign = null // 函数挂载标签
  socket = null // 连接引用
  
  
  constructor(code) {

    if (!scoketMap[code]) {
      scoketMap[code] =  new WebSocket(LINKS[code] + '?token=' + getAccessToken())
    }

    this.socket = scoketMap[code]
  
  }

  start (fuc) {
    
    this.sign = res => {
      fuc(JSON.parse(res.data))
    }
    
    this.socket.addEventListener('message', this.sign)

  }

  close () {

    this.socket.removeEventListener('message', this.sign)

  }


}

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')

// const newConnect = (code) => {

//   scoketMap[code] = {
//     socket: new WebSocket(this.link + '?token=' + getAccessToken()),
//     calls: []
//   }

//   this.socket.addEventListener('open', () => {
//     console.log('socket start')
//   })

// }

// const onStart = (code, call) => {

//   if (!scoketMap[code]) {
//     newConnect(code)
//   }

//   scoketMap[code]

// }



