// src/composables/useMonitor.js
import { ref } from 'vue'

/**
 * 设备消息监测（含“有消息时暂停，此设备私信发送成功后恢复”）
 * - 每 10s 轮询 getmesNum，但跳过 paused 的设备
 * - 暴露 pause/resume 方法，供外部在 onmessage 分支中调用
 * - 提供 openMonitor()/closeMonitor()/stop() 以适配你现有按钮逻辑
 *
 * @param {object} options
 *  - deviceInformation: ref([]) 设备列表
 *  - runType: ref('')          当前运行模式
 *  - isStop: ref(false)        全局停止标志
 *  - isMonitorOn: ref(false)   监测开关（UI 显示用）
 *  - isShowMes: ref()          定时器引用（外面已有）
 *  - wsActionsRef: () => wsActions  一个函数，返回你动态创建的 wsActions 对象
 *  - onKickOnce?: (udid, index) => void 在恢复后，立刻补一次检测的 hook（默认调用 getmesNum）
 */
export function useMonitor({
    deviceInformation,
    runType,
    isStop,
    isMonitorOn,
    isShowMes,
    wsActionsRef,
    onKickOnce
}) {
    // 用 UDID 做键，避免 index 变化错位
    const pausedDevices = new Set();

    const isPausedByIndex = (index) => {
        const udid = deviceInformation.value[index]?.udid;
        return udid ? pausedDevices.has(udid) : false;
    };

    const pauseMonitorByIndex = (index) => {
        const udid = deviceInformation.value[index]?.udid;
        if (udid) pausedDevices.add(udid);
    };

    const resumeMonitorByIndex = (index) => {
        const udid = deviceInformation.value[index]?.udid;
        if (udid) pausedDevices.delete(udid);
    };

    const clearPaused = () => pausedDevices.clear();

    const openMonitor = () => {
        isStop.value = false;
        // 立即跑一轮
        const wsActions = wsActionsRef?.();
        deviceInformation.value.forEach((device, index) => {
            if (!isPausedByIndex(index)) {
                wsActions?.getmesNum(device.udid, index);
            }
        });

        runType.value = 'listen';
        isMonitorOn.value = true;

        // 每 10s 轮询未暂停设备
        isShowMes.value = setInterval(() => {
            const ws = wsActionsRef?.();
            deviceInformation.value.forEach((device, index) => {
                if (!isPausedByIndex(index)) {
                    ws?.getmesNum(device.udid, index);
                }
            });
        }, 10000);
    };

    const closeMonitor = () => {
        isMonitorOn.value = false;
        runType.value = '';
        if (isShowMes.value) {
            clearInterval(isShowMes.value);
            isShowMes.value = '';
        }
        clearPaused();
    };

    // 兼容你原来的 stop() 会顺手关监测
    const stopAll = () => {
        closeMonitor();
        clearPaused();
        isStop.value = true;
    };

    // 用于“私信成功后立刻恢复并补一次检测”
    const resumeAndKick = (index) => {
        resumeMonitorByIndex(index);
        setTimeout(() => {
            const udid = deviceInformation.value[index]?.udid;
            if (!udid) return;

            if (typeof onKickOnce === 'function') {
                onKickOnce(udid, index);
            } else {
                const ws = wsActionsRef?.();
                ws?.getmesNum(udid, index);
            }
        }, 1500);
    };

    return {
        // state
        pausedDevices,

        // helpers
        isPausedByIndex,
        pauseMonitorByIndex,
        resumeMonitorByIndex,
        clearPaused,

        // controls
        openMonitor,
        closeMonitor,
        stopAll,
        resumeAndKick,
    }
}
