// @ts-nocheck
import {defineStore} from "pinia";

import {store} from "@/store";

let websock = null;
let heartbeatTimer = null; // 心跳定时器
// 开始心跳定时器
function startHeartbeat() {
    const data = {
        restPing: {
            ping: 'ping'
        }
    };
    heartbeatTimer = setInterval(function () {
        websock.send(JSON.stringify(data))
    }, 30000)
}

// 停止心跳定时器
function stopHeartbeat() {
    clearInterval(heartbeatTimer)
}

export const webSocketStore = defineStore("webSocket", () => {
    function initWebSocket(url) {
        websock = new WebSocket(url)
        websock.onopen = function () {
            // console.log('WebSocket 已连接')
            startHeartbeat()
        }
        websock.onmessage = function (msg) {
            const msgData = msg.data
            const msgContent = JSON.parse(msgData)
            if (msgContent.message != 'PONG') {
                //处理自定义消息
            }
        }
        websock.onerror = function (e) { // 错误
            console.log('ws错误!')
            // console.log(e)
        }
        websock.onclose = function (e) { // 关闭
            console.log('ws关闭！')
            // 停止心跳定时器
            stopHeartbeat()

            setTimeout(function () {
                console.log('WebSocket 尝试重新连接')
                initWebSocket(url)
            }, 3 * 1000)
        }
    }

    return {
        initWebSocket,
    };
});

// 非setup
export function webSocketStoreHook() {
    return webSocketStore(store);
}
