// stores/websocketStore.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useWebSocketStore = defineStore('websocket', () => {
    const messages = ref<string[]>([]);
    const showModal = ref(false);
    const currentMessage = ref('');
    let socket: WebSocket | null = null;

    const connect = () => {
        try {
            socket = new WebSocket('ws://192.168.10.14:8000/ws/logs/');

            socket.addEventListener('open', () => {
                console.log('WebSocket 连接已打开');
            });

            socket.addEventListener('message', (event) => {
                messages.value.push(JSON.parse(event.data));
                currentMessage.value = event.data;
                showModal.value = true;
            });

            socket.addEventListener('close', () => {
                console.log('WebSocket 连接已关闭，尝试重连...');
                // setTimeout(connect, 5000);
            });

            socket.addEventListener('error', (error) => {
                console.error('WebSocket 连接出错:', error);
                socket?.close();
                // setTimeout(connect, 5000);
            });
        } catch (err) {
            console.error('创建 WebSocket 实例时出错:', err);
            // setTimeout(connect, 5000);
        }
    };

    connect();

    return { messages, showModal, currentMessage };
});