// src/utils/socket.js
import { ElMessage } from 'element-plus'
import { ROOTPATH2 } from '../comment/httpUrl.js'
var WSS = null // 全局唯一的 WebSocket 实例

/**
 * 连接 WebSocket
 * @param {string} userId 当前用户 ID
 */
export function connectSocket(userId, store, router) {
    if (!userId) return
    // 若已有连接则关闭
    if (WSS) {
        try {
            WSS.close()
        } catch { }
    }

    const wsUrl = `${ROOTPATH2}${userId}`
    WSS = new WebSocket(wsUrl)
    console.log('🔗 WebSocket 连接中:', wsUrl)
    console.log(WSS)
    WSS.onopen = () => {
        console.log('✅ WebSocket 已连接:', wsUrl)
    }

    WSS.onmessage = (event) => {
        if (event.data === 'HeartBeat') return
        let msg
        try {
            msg = JSON.parse(event.data)
        } catch (e) {
            console.warn('非 JSON 消息:', event.data)
            return
        }

        if (msg.type === 'kickOut') {
            ElMessage({
                message: msg.content || '您的账号已在其他设备登录',
                type: 'warning',
                duration: 1500
            })

            // 清空本地存储
            localStorage.removeItem('token')
            localStorage.removeItem('userId')
            localStorage.removeItem('userType')
            localStorage.removeItem('companyId')

            if (store) store.dispatch('SET_DATA')
            if (router) router.push({ name: 'login' })
        }
    }

    WSS.onerror = (err) => {
        console.error('❌ WebSocket 错误:', err)
    }

    WSS.onclose = () => {
        console.log('🔌 WebSocket 已关闭')
    }
}

/** 获取 WebSocket 实例 */
export function getSocket() {
    return WSS
}

/** 发送消息 */
export function sendSocketMsg(data) {
    if (WSS && WSS.readyState === WebSocket.OPEN) {
        WSS.send(data)
    } else {
        console.warn('⚠️ WebSocket 未连接，无法发送')
    }
}

/** 关闭连接 */
export function closeSocket() {
    if (WSS) {
        WSS.close()
        WSS = null
    }
}
