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'
    }

    const LOG_PREFIX = '[workflow-socket]';

    // 订阅 workflow 相关 room
    const subscribeWorkflowRooms = (reason) => {
        console.log(LOG_PREFIX, 'subscribe rooms, reason:', reason);
        socket.emit(SocketCommands.subscribe, {
            roomParts: SocketRoomParts.badgeChange,
            individual: true
        });
        socket.emit(SocketCommands.subscribe, {
            roomParts: SocketRoomParts.instanceRecordChange,
            individual: true
        });
    };

    // 初始连接时立即订阅
    if(socket.connected){
        subscribeWorkflowRooms('initial-connected');
    }

    // 始终注册 connection-init listener，确保重连后也能重新订阅
    socket.on("connection-init", ()=>{
        console.log(LOG_PREFIX, 'connection-init received, socketId:', socket.id);
        subscribeWorkflowRooms('connection-init');
    });

    socket.on("disconnect", (reason)=>{
        console.warn(LOG_PREFIX, 'disconnected, reason:', reason);
    });

    socket.on("connect", ()=>{
        console.log(LOG_PREFIX, 'connected, socketId:', socket.id);
    });

    // 记录上一次 badge 数据，用于比较是否真正发生变化
    let lastBadgeJson = null;
    let isFirstRun = true;
    socket.on(SocketEvents.badgeChange, (data)=>{
        // 角标数字更新：无条件执行，确保 UI 始终同步
        window.postMessage({ type: "page.dataProvider.setData", data: { badges: data }}, "*")

        const currentBadgeJson = JSON.stringify(data);
        const badgeChanged = lastBadgeJson !== null && currentBadgeJson !== lastBadgeJson;
        lastBadgeJson = currentBadgeJson;

        // 列表和菜单刷新：仅在 badge 数据实际变化时触发
        // 避免 socket 重连后服务端推送相同 badge 数据导致不必要的重载
        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) {
          console.log(LOG_PREFIX, 'badge:change (first run, skip reload)', data);
        } else if (!badgeChanged) {
          console.log(LOG_PREFIX, 'badge:change (data unchanged, skip reload)', data);
        } else if (!shouldReloadView()) {
          console.log(LOG_PREFIX, 'badge:change (not on approval page, skip reload)', data);
        } else {
          console.log(LOG_PREFIX, 'badge:change (data changed, triggering reload)', data);
          window.$(".list-view-btn-reload").click()
          window.postMessage({ type: "approval-tree-menu:reload" }, "*")
        }
        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()) {
          // 仅刷新列表。审批中心左侧菜单（approval-tree-menu）的角标/分类
          // 完全派生自 badge 数据，由 badge:change 链路负责广播 reload；
          // 此处不再额外广播 approval-tree-menu:reload，避免同一次提交动作
          // 触发两次 nav 接口请求（issue: steedos/steedos-widgets#627）。
          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')
                        }
                    }
                })
            }
        }
    });
})