window.waitForThing(window, 'socket').then(()=>{
    const socket = window.socket;
    
    const SocketCommands = {
        subscribe: "subscribe",
    }

    const SocketEvents = {
        badgeChange: 's:workflow:badge:change',
        instanceRecordChange: 's:record:instances:change'
    }

    const SocketRoomParts = {
        badgeChange: 'workflow:badge:change',
        instanceRecordChange: 'record:instances:change'
    }

    if(socket.connected){
        socket.emit(SocketCommands.subscribe, {
            roomParts: SocketRoomParts.badgeChange,
            individual: true
        });

        socket.emit(SocketCommands.subscribe, {
            roomParts: SocketRoomParts.instanceRecordChange,
            individual: true
        });
    }else{
        socket.on("connection-init", ()=>{
            socket.emit(SocketCommands.subscribe, {
                roomParts: SocketRoomParts.badgeChange,
                individual: true
            });
            socket.emit(SocketCommands.subscribe, {
                roomParts: SocketRoomParts.instanceRecordChange
            });
        })
    }
    let isFirstRun = true;
    socket.on(SocketEvents.badgeChange, (data)=>{
        window.postMessage({ type: "page.dataProvider.setData", data: { badges: data }}, "*")
        const shouldReloadView = () => {
            const pathname = window.location.pathname;
            return pathname.endsWith(`/instances`) || pathname.includes(`/instances/view`) || pathname.includes(`/instances/grid`) || pathname.endsWith(`/instance_tasks`) || pathname.includes(`/instance_tasks/view`) || pathname.includes(`/instance_tasks/grid`);
        };
        if (isFirstRun === false && shouldReloadView()) {
          window.$(".list-view-btn-reload").click()
          window.$(".instance-nav-reload").click()
        }
        isFirstRun = false;
    });

    socket.on(SocketEvents.instanceRecordChange, (data)=>{
        console.log(`socket 「${SocketEvents.instanceRecordChange}」`, data)
        const shouldReloadView = () => {
            const pathname = window.location.pathname;
            return pathname.endsWith(`/instances`) || pathname.includes(`/instances/view`) || pathname.includes(`/instances/grid`) || pathname.endsWith(`/instance_tasks`) || pathname.includes(`/instance_tasks/view`) || pathname.includes(`/instance_tasks/grid`);
        };
        if (shouldReloadView()) {
          window.$(".list-view-btn-reload").click()
        }
    });


    window.addEventListener('message', (event)=>{
        const data = event.data;
        // 判断是不是我们发的路由变化消息
        if (data && data.type === 'ROUTE_CHANGE') {
            console.log('📬 收到路由变化消息:', data);
            if(data.path.startsWith('/app/approve_workflow/instances/view/')){
                const recordId = _.last(_.split(data.path, '/'));
                socket.emit(SocketCommands.subscribe, {
                    roomParts: `${SocketRoomParts.instanceRecordChange}-${recordId}`
                });
                socket.on(`${SocketEvents.instanceRecordChange}-${recordId}`, (eventData)=>{
                    if(window.location.pathname.startsWith('/app/approve_workflow/instances/view/'+eventData._id)){
                        if(window.location.search.indexOf("side_listview_id=monitor") > 0){
                            $(".steedos-workflow-reload-btn").trigger('click')
                        }
                    }
                })
            }
        }
    });
})