import emitter from '@/utils/emitter';
import IndexedDB from '@/utils/indexedDBUtil';
import { ElMessage } from 'element-plus';
import {ref} from "vue";

export let isModified = ref(false)

// ---- 窗口切换统计 ----
export interface WindowSwitchEvent {
    eventType: 'hidden' | 'visible';
    timestamp: string;
}

export interface WindowSwitchData {
    studentId: number;
    assignmentId: number;
    switchCount: number;
    switchEvents: WindowSwitchEvent[];
}

// 离开窗口的总次数（visibilityState 变为 hidden 的次数）
export const windowSwitchCount = ref(0)
// 每次切换的详细记录
export const windowSwitchEvents = ref<WindowSwitchEvent[]>([])

let visibilityChangeHandler: (() => void) | null = null

export const setupWindowSwitchListener = () => {
    visibilityChangeHandler = () => {
        const eventType = document.visibilityState === 'hidden' ? 'hidden' : 'visible'
        if (eventType === 'hidden') {
            windowSwitchCount.value++
        }
        windowSwitchEvents.value.push({
            eventType,
            timestamp: new Date().toISOString()
        })
    }
    document.addEventListener('visibilitychange', visibilityChangeHandler)
}

export const removeWindowSwitchListener = () => {
    if (visibilityChangeHandler) {
        document.removeEventListener('visibilitychange', visibilityChangeHandler)
        visibilityChangeHandler = null
    }
}

export const resetWindowSwitchData = () => {
    windowSwitchCount.value = 0
    windowSwitchEvents.value = []
}

export const getWindowSwitchData = (studentId: number, assignmentId: number): WindowSwitchData => ({
    studentId,
    assignmentId,
    switchCount: windowSwitchCount.value,
    switchEvents: [...windowSwitchEvents.value]
})
// ---- 窗口切换统计结束 ----

// 处理word区鼠标移动的记录
// export const setupWordMouseMoveListener = (indexedDB: IndexedDB) => {
//     emitter.on("word-mouse-move", (event: any) => {
//         // indexedDB.addData(event)
//         // console.log(event);
//     });
// };


// 处理AI对话点击发送按钮事件的监听函数
export const setupClickAISendButtonListener = (indexedDB: IndexedDB) => {

};

// 处理is-modified事件的监听函数
export const setupIsModifiedListener = () => {
    emitter.on("is-modified", (state) => {
        isModified.value = state;
    });
};

// 可以根据后续需要继续添加更多的事件监听设置函数

// 统一注册所有事件监听的函数
export const registerAllEventListeners = (indexedDB: IndexedDB) => {
    // 后续若有其他事件监听，在此处添加调用对应的设置函数即可
    setupClickAISendButtonListener(indexedDB);
    setupIsModifiedListener();
    setupWindowSwitchListener();
    // setupWordMouseMoveListener(indexedDB)
};

// 统一移除所有事件监听的函数
export const removeAllEventListeners = () => {
    // 后续如有更多事件监听，在此处添加移除对应事件的代码
    emitter.off("click-ai-send-button");
    emitter.off("is-modified");
    removeWindowSwitchListener();
    // emitter.off("word-mouse-move");
};