import sysConfig from "@/config";
import tools from "@/utils/tools";

const ws = {
    websocket: null,
    timer: null,
    init: function () {
		let token = tools.data.get("TOKEN");
		ws.websocket = new WebSocket(sysConfig.WS_URL + "?Authorization=" + token);
		ws.websocket.onopen = ws.open;
		return ws
    },
    open: function () {
		if (ws.timer) {
			clearInterval(ws.timer); // 停止心跳
		}
		ws.startBeat()
    },
    startBeat: function (){
        ws.timer = setInterval(() => {
            if (ws.websocket && ws.websocket.readyState === WebSocket.OPEN) {
                ws.websocket.send("ping");
            }
        }, 30000);
    },
    send: function (message){
        ws.websocket.send(JSON.stringify(message))
    }
}

export default ws;
