import {ElMessageBox} from 'element-plus'
import Cookies from 'js-cookie'
import router from '@/router'
import store from '@/store'

const socketUrl = import.meta.env.VITE_SOCKET_URL

let webSocket = null
let globalCallback = new Map()

let unwantedSocket = ['emrEditor']

export function closeWebSocket() {
    store.commit('user/closeSid')
    if (webSocket !== null) {
        webSocket.close()
        webSocket = null
    }
}

export function setCallback(messageName, callback) {
    if (globalCallback.has(messageName)) {
        globalCallback.get(messageName).push(callback)
    } else {
        globalCallback.set(messageName, [callback])
    }
    console.log(`websocket 监听通道 ${messageName},已监听 ${globalCallback.get(messageName).length} 个`)
}

export function delCallback(messageName) {
    globalCallback.delete(messageName)
    console.log(`websocket 监听通道关闭 ${messageName}`)
}


function sendAMessage(name, data) {
    if (globalCallback.has(name)) {
        globalCallback.get(name).forEach(item => {
            item(data)
        })
    }
}

export function initWebSocket(sid, force) {

    if ('WebSocket' in window) {
        if (webSocket === null || force) {
            const url = socketUrl + sid
            webSocket = new WebSocket(url)
        }
    } else {
        alert('该浏览器不支持websocket!')
        webSocket = 'unsupport'
    }

    webSocket.onopen = function () {
        console.log('WebSocket连接成功')
    }


    webSocket.onmessage = function (e) {
        let data = JSON.parse(e.data)
        sendAMessage(data.name, data.message)
    }

    webSocket.onclose = function () {
        webSocket = null
        let sid
        if (router.currentRoute.value.path === '/triageRoomScreen') {
            sid = Cookies.get('room-screen-sid')
        } else {
            sid = store.state.user.sid
        }
        if (!sid) {
            if (router.currentRoute.value.path === '/login') {
                return
            }
            ElMessageBox.confirm('未检测到WebSocket连接的sid，请重新登录。', '提示', {
                showCancelButton: false,
                type: 'warning',
            }).then(() => {
                router.push('/login')
            })
        } else {
            if (router.currentRoute.value.path === '/triageFloorScreen') {
                sid += '-triageFloorScreen'
            }
            setTimeout(() => {
                initWebSocket(sid)
            }, 3000)
        }
    }

    webSocket.onerror = function () {
        console.error('WebSocket连接发生错误')
    }
}
