import store from '../store/index'
import { ElMessage } from "element-plus";
let websock = sessionStorage.getItem('isWebSocket')
let wsuri = null
var limitConnect = 3; // 断线重连次数
let isWebSocket = sessionStorage.getItem('isWebSocket')
export function initWebSocket(wsUrl) { //初始化weosocket
    if (isWebSocket != null) {
        return
    } else {
        wsuri = wsUrl;
        websock = new WebSocket(`ws://${wsuri}`);
        sessionStorage.setItem('isWebSocket', websock)
        websock.onmessage = function(e) {
            websocketonmessage(e)
        }
        websock.onopen = function() { websocketonopen() }
        websock.onerror = function() { websocketonerror() }
        websock.onclose = function() { websocketclose() }
    }
}
export function ws() {
    limitConnect = 0; // 断线重连次数
    websock.close()
}

function websocketonopen() { //连接建立之后执行send方法发送数据
    console.warn('连接建立之后执行send方法发送数据');
}

function websocketonerror() { //连接建立失败重连     
    console.warn('连接建立失败重连');
}

function websocketonmessage(e) { //数据接收
    console.warn(e.data);
    let redata = e.data
    store.dispatch('actionsWarning', redata)
}

function websocketclose(e) { //关闭
    if (limitConnect > 0) {
        limitConnect--;
        // 进行重连
        ElMessage.error('与服务器连接失败!重新连接中...')
        setTimeout(function() {
            initWebSocket(wsuri);
        }, 2000);

    } else {
        ElMessage.error('连接已超时,请重新登录!')
        websock.close()
        limitConnect = 0; // 断线重连次数
    }
}