import { defineStore } from 'pinia'
import { useStorage } from '@vueuse/core'
import { skipHydrate } from 'pinia'
// const userInfoStore = useUserInfoStore()
// const { userInfo } = storeToRefs(userInfoStore)
// userInfoStore.getUserInfo()
export const useChatStore = defineStore('chat', () => {
  const startUrl = ref('wss://your-websocket-url')

  const message = ref(null)

  // WebSocket 服务的实例
  const wsService = ref(null)

  // 使用 `useStorage` 来持久化 WebSocket 的连接状态
  const isConnected = useStorage('isConnected', false)

  // 连接 WebSocket
  const connect = (url) => {
    if (wsService.value) {
      // 如果 WebSocket 已连接，不需要重新连接
      return
    }

    wsService.value = new WebSocket(`${startUrl.value}${url}`)

    wsService.value.connect()

    // 当连接成功时
    wsService.value.onopen = () => {
      isConnected.value = true
      console.log('WebSocket连接已打开')
    }

    // 当连接关闭时
    wsService.value.onclose = () => {
      isConnected.value = false
      console.log('WebSocket连接已关闭')
    }

    // 监听错误事件
    wsService.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
      isConnected.value = false
    }

    // 监听消息
    wsService.value.onMessage((message) => {
      console.log('收到消息:', message)
    })
  }

  // 发送消息
  const sendMessage = (message) => {
    if (wsService.value && wsService.value.readyState === WebSocket.OPEN) {
      wsService.value.sendMessage(message)
    } else {
      console.error('WebSocket未连接，无法发送消息')
    }
  }

  // 断开 WebSocket 连接
  const disconnect = () => {
    if (wsService.value) {
      wsService.value.close()
      wsService.value = null
      isConnected.value = false
      console.log('WebSocket已关闭')
    }
  }

  // 返回 Pinia store 中的数据和方法
  return {
    isConnected: skipHydrate(isConnected), // 保证在服务器端渲染时不与客户端同步
    wsService,
    connect,
    sendMessage,
    disconnect
  }
})
