import {ElMessageBox, ElNotification} from 'element-plus'
import Cookies from 'js-cookie'
import router from '@/router'
import store from '@/store'
import {stringIsBlank} from "./blank-utils";

const socketUrl = import.meta.env.VITE_SOCKET_URL

let webSocket = null
let globalCallback = null

export function closeWebSocket() {
    Cookies.remove('sid')
    if (webSocket !== null) {
        webSocket.close()
        webSocket = null
    }
}

export function setCallback(callback) {
    if (callback !== null) {
        globalCallback = callback
        console.log('global callback settled.')
    }
}

export function initWebSocket(sid) {
    if ('WebSocket' in window) {
        if (webSocket === null) {
            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)
        if (data.name === 'refreshToken') {
            store.commit('user/tokenChange', data.token)
        } else if (data.name === 'systemNotification') {
            ElNotification({
                title: typeof data.title === 'undefined' ? '新消息' : data.title,
                message: data.message,
                dangerouslyUseHTMLString: true,
                type: typeof data.type === 'undefined' ? 'warning' : data.type,
                duration: 0,
            })
            if (data.refreshDelay) {
                setTimeout(() => {
                    location.reload()
                }, data.refreshDelay)
            }
            if (null !== globalCallback) {
                globalCallback(data)
            }
        } else if (data.name === 'jdtMessage') {
            if (null != globalCallback) {
                if (!store.state.app.jdt.isOpen) {
                    store.commit('app/setJdt', {
                        title: Cookies.get('jdtTitle'),
                        isOpen: true,
                        abnormalClosing: true
                    })
                }
                globalCallback(data)
            }
        } else {
            if (null !== globalCallback) {
                globalCallback(data)
            }
        }
    }

    webSocket.onclose = function () {
        webSocket = null
        let sid
        if (router.currentRoute.value.path === '/triageRoomScreen') {
            sid = Cookies.get('room-screen-sid')
        } else {
            sid = store.getters['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连接发生错误')
    }
}
