import { ref } from 'vue'
export function useWebSocket(url) {
  let socket = ref(null) // socket对象
  let isConnected = ref(false) // 是否连接成功
  let dataRes = ref(null) // 存储推送数据
  let timer=null;
  const connectWebSocket = () => {
    socket.value = new WebSocket(url, 'echo-protocol', {
      headers: {
        Authorization:
          'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImE1OWFmNWYwLTU3OWItNDJkNy1hZDJhLTY0Y2JlODA5ZWI1NiJ9.BTxvu6jUWbN0qONWf5K6VzXopE8T8qXzKuX-mij21VJT4U0LdgnqToyqeNDQ2OyJ6cvpdJBzQ9mEEb-dnwrTpQ'
      }
    })
    socket.value.onopen = () => {
      isConnected.value = true
      console.log('WebSocket connected')
    }
    socket.value.onerror = (error) => {
		connectWebSocket()
      console.error('WebSocket error:', error)
    }
    socket.value.onmessage = (message) => {
      if (JSON.parse(message.data)) {
        let data = JSON.parse(message.data)
        dataRes.value = data
      }
    }
    socket.value.onclose = (event) => {
      isConnected.value = false
      console.log('WebSocket close：',url, event)
      if(!timer){
        timer =setInterval(() => {
          if(!isConnected.value){
            console.log('重连中...')
            connectWebSocket()
          }else if(isConnected.value){
            clearInterval(timer)
            timer = null;
          }
        }, 5000);
      }


    }
  }

  const sendMessage = (message) => {
    if (socket.value && isConnected.value) {
      socket.value.send(message)
    }
  }

  onMounted(() => {
    connectWebSocket()
  })

  onUnmounted(() => {
    if (socket.value) {
      socket.value.close()
    }
  })

  return { socket, dataRes, isConnected, connectWebSocket, sendMessage }
}
