import { ElMessageBox, ElMessage } from 'element-plus'; // 引入 ElementPlus 的 ElMessageBox 和 ElMessage 组件

let socket: WebSocket | null = null;
let reconnectAttempts = 0; // 重连次数计数器
const reconnectInterval = 3000; // 重连间隔时间，单位毫秒
let onMessageList = [] as ((response: Response) => void)[];
let onErrorList = [] as (() => void)[];
interface Response {
    Code: number;
    Message: string;
    Data: any;
}

interface Request {
    type: string;
    data: any;
    config?: any;
}

// 初始化 WebSocket 连接
const wsInit = (finish: () => void) => {
    // 如果已经存在一个WebSocket连接，先关闭它
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.close();
    }
    socket = new WebSocket('ws://localhost:8090');
    socket.addEventListener('open', (event) => {
        finish();
        reconnectAttempts = 0; // 连接成功后重置重连计数器
    });

    // 监听错误事件
    socket.addEventListener('error', (event) => {
        for(let i = 0; i < onErrorList.length; i++){
            onErrorList[i]();
        }
    });
    socket.addEventListener('message', (event) => {
        let parsedMessage: Response = JSON.parse(event.data);
        onMessageList.forEach(callback => {
            callback(parsedMessage);
        });
    });
    socket.onerror = (e) => e.stopImmediatePropagation();
    // 监听连接关闭事件
    socket.addEventListener('close', (event) => {
    });
};

// 设置消息回调函数
const wsSetMessageCallback = (onMessage: (response: Response) => void) => {
    onMessageList.push(onMessage)
};
const wsRemoveMessageCallback = (onMessage: (response: Response) => void) => {
    onMessageList = onMessageList.filter(callback => callback !== onMessage);
};
const wsRemoveAllMessageCallback = () => {
    onMessageList = [];
};
const wsSend = (request: Request) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify(request));
    } else {
        wsInit(()=>{
            wsSend(request);
        })
    }
};

const wsClose = () => {
    if (socket) {
        socket.close();
    }
};

const wsSetErrorCallback=(onError: () => void)=>{
    onErrorList.push(onError)
}
const wsRemoveAllErrorCallback=()=>{
    onErrorList = [];
}

export {
    wsInit,
    wsSetMessageCallback,
    wsRemoveAllMessageCallback,
    wsRemoveMessageCallback,
    wsSend,
    wsClose,
    wsSetErrorCallback,
    wsRemoveAllErrorCallback,
    type Response,
    type Request,
};