import { defineStore, acceptHMRUpdate } from "pinia"
import { store } from '@/stores'
import { socketInit } from '@/utils/socket/index.ts'
import type { Socket } from "socket.io-client"

interface UserState {
  socket: Socket | null,
  connected:any,
  reconnectAttempts: number,
}

export const useSocketStore = defineStore('socket', {
  state: (): UserState => ({
    socket: null,
     connected: false,
    reconnectAttempts: 0,
  }),
  getters: {
    SOCKET(state) {
      return state.socket
    },
     isConnected(state) {
      return state.connected
    },
    attempts(state) {
      return state.reconnectAttempts
    }
  },
  actions: {
    // 获取token
    initSocket() {
      console.log('?initSocket')
      const socket = socketInit(true)
      this.$patch((state) => {
        state.socket = socket
      })
       // ===== 事件监听 =====

      socket.on('connect', () => {
        this.connected = true
        console.log('[Socket] 已连接，socket id:', socket.id)
      })

      socket.on('disconnect', (reason) => {
        this.connected = false
        console.log(`[Socket] 已断开，原因: ${reason}`)
      })

      // 重连中，每次尝试都会触发
      socket.io.on('reconnect_attempt', (attempt: number) => {
        this.reconnectAttempts = attempt
        console.log(`[Socket] 重连尝试 #${attempt}`)
      })

      // 重连成功
      socket.io.on('reconnect', (attempt: number) => {
        console.log(`[Socket] 重连成功，尝试次数: ${attempt}`)
      })

      // 重连失败
      socket.io.on('reconnect_failed', () => {
        console.warn('[Socket] 重连失败，放弃继续重连')
      })
    },
    // 清除仓库数据
    cleanStore() {
      this.$reset()
    }
  },
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useSocketStore, import.meta.hot))
}

export const useSocketStoreWithOut = () => {
  return useSocketStore(store)
}
