// src/utils/websocket.js

window.websocketData = []

class WebSocketService {
    constructor() {
        // this.url = `wss://${window.global?.wsURL}:9501`;
        this.url = window.global?.wsURL;
        this.socket = null;
        this.isOpen = false;
        this.isReconnecting = false;
        this.reconnectCount = 0;
        this.maxReconnect = 5;
        this.timer = null;
        this.pingInterval = 30000;
        this.eventBus = new EventTarget();
    }

    connect() {
        if (this.isOpen) return;
        let token = localStorage.getItem('token');
        try {
            this.socket = new WebSocket(token ? this.url+'?token='+token : this.url);
        } catch (error) {
            console.error('WebSocket 连接错误:', error);
            return;
        }

        this.socket.onopen = () => {
            // console.log('WebSocket 连接成功');
            this.isOpen = true;
            this.isReconnecting = false;
            this.reconnectCount = 0;
            this.startHeartbeat();
        };

        this.socket.onmessage = (event) => {
            // console.log('WebSocket 收到服务器消息:', event.data);
            try {
                const data = JSON.parse(event.data);

                if(data.type === 'sport_list') {
                    // 1. 提取 Base64 压缩文本
                    const base64String = data.message;
                    // 2. 将 Base64 转换为纯二进制字符串 (浏览器内置的 atob 函数)
                    const binaryString = atob(base64String);
                    // 3. 将二进制字符串转换为 pako 需要的 Uint8Array
                    const uint8Array = new Uint8Array(binaryString.length);
                    for (let i = 0; i < binaryString.length; i++) {
                        uint8Array[i] = binaryString.charCodeAt(i);
                    }
                    try {
                        // 4. 使用 pako 解压
                        // pako.inflate 会自动识别 zlib 格式
                        const decompressedData = pako.inflate(uint8Array);

                        // 5. 将解压出来的 Uint8Array 还原成普通的中英文字符串
                        const textDecoder = new TextDecoder('utf-8');
                        const resultText = textDecoder.decode(decompressedData);

                        this.eventBus.dispatchEvent(new CustomEvent('onSocketMessage', {
                            detail: {
                                ...data,
                                message: JSON.parse(resultText),
                            }
                        }));

                        if(window.websocketData.length < 20) {
                            window.websocketData.push({
                                ...data,
                                message: JSON.parse(resultText),
                            })
                        } else {
                            window.websocketData.splice(0, 1)
                            window.websocketData.push({
                                ...data,
                                message: JSON.parse(resultText),
                            })
                        }


                    } catch (err) {
                    }
                } else {
                    this.eventBus.dispatchEvent(new CustomEvent('onSocketMessage', { detail: data }));
                }

            } catch (error) {
                console.error('解析消息失败:', error);
            }
        };

        this.socket.onclose = () => {
            console.log('WebSocket 连接断开');
            this.isOpen = false;
            this.socket = null;
            this.stopHeartbeat();
            this.reconnect();
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket 连接错误:', error);
            this.isOpen = false;
        };
    }

    send(data) {
        if (this.isOpen && this.socket) {
            const msg = typeof data === 'object' ? JSON.stringify(data) : data;
            this.socket.send(msg);
        } else {
            console.error('WebSocket 尚未连接，消息发送失败');
        }
    }

    onMessage(callback) {
        this.eventBus.addEventListener('onSocketMessage', (event) => {
            callback(event.detail);
        });
    }

    startHeartbeat() {
        this.stopHeartbeat();
        this.timer = setInterval(() => {
            this.send({ type: 'ping' });
        }, this.pingInterval);
    }

    stopHeartbeat() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    reconnect() {
        if (this.isReconnecting) return;
        // if (this.reconnectCount >= this.maxReconnect) {
        //     console.error('WebSocket 重连次数达到上限，放弃重连');
        //     return;
        // }

        this.isReconnecting = true;
        this.reconnectCount++;
        console.log(`WebSocket 正在尝试第 ${this.reconnectCount} 次重连...`);

        setTimeout(() => {
            this.isReconnecting = false;
            this.connect();
        }, 3000);
    }

    close() {
        this.maxReconnect = 0;
        this.stopHeartbeat();
        if (this.isOpen && this.socket) {
            this.socket.close();
        }
    }
}

export default new WebSocketService();
