// Timer Worker - 独立的定时器工作线程
let intervalId = null;
let intervalTime = 30000;
let startTime = null;
let executionCount = 0;
let isRunning = false;

// 监听主线程消息
self.onmessage = function(e) {
    const { action, interval, options } = e.data;

    try {
        switch (action) {
            case 'start':
                startTimer(interval, options);
                break;
            case 'stop':
                stopTimer();
                break;
            case 'pause':
                pauseTimer();
                break;
            case 'resume':
                resumeTimer();
                break;
            case 'status':
                sendStatus();
                break;
            case 'setInterval':
                setNewInterval(interval);
                break;
            default:
                sendError(`未知操作: ${action}`);
        }
    } catch (error) {
        sendError(`执行操作失败: ${error.message}`);
    }
};

// 启动定时器
function startTimer(interval = 30000, options = {}) {
    if (isRunning) {
        sendMessage('warning', '定时器已在运行中');
        return;
    }

    intervalTime = interval;
    startTime = Date.now();
    executionCount = 0;
    isRunning = true;

    // 立即发送第一次tick
    sendTick();

    // 启动定时器
    intervalId = setInterval(() => {
        sendTick();
    }, intervalTime);

    sendMessage('status', `Worker定时器已启动，间隔: ${intervalTime}ms`);
}

// 停止定时器
function stopTimer() {
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
    }
    isRunning = false;
    sendMessage('status', 'Worker定时器已停止');
}

// 暂停定时器
function pauseTimer() {
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
        sendMessage('status', 'Worker定时器已暂停');
    }
}

// 恢复定时器
function resumeTimer() {
    if (!intervalId && isRunning) {
        intervalId = setInterval(() => {
            sendTick();
        }, intervalTime);
        sendMessage('status', 'Worker定时器已恢复');
    }
}

// 设置新的间隔时间
function setNewInterval(newInterval) {
    if (newInterval && newInterval > 0) {
        intervalTime = newInterval;
        if (isRunning) {
            stopTimer();
            startTimer(intervalTime);
        }
        sendMessage('status', `间隔时间已更新为: ${intervalTime}ms`);
    } else {
        sendError('无效的间隔时间');
    }
}

// 发送tick消息
function sendTick() {
    executionCount++;
    self.postMessage({
        type: 'tick',
        timestamp: Date.now(),
        executionCount: executionCount,
        intervalTime: intervalTime
    });
}

// 发送状态信息
function sendStatus() {
    const uptime = startTime ? Date.now() - startTime : 0;
    self.postMessage({
        type: 'status',
        data: {
            isRunning: isRunning,
            intervalTime: intervalTime,
            executionCount: executionCount,
            uptime: uptime,
            startTime: startTime,
            averageInterval: executionCount > 1 ? uptime / (executionCount - 1) : 0
        }
    });
}

// 发送普通消息
function sendMessage(type, message) {
    self.postMessage({
        type: type,
        message: message,
        timestamp: Date.now()
    });
}

// 发送错误消息
function sendError(message) {
    self.postMessage({
        type: 'error',
        message: message,
        timestamp: Date.now()
    });
}

// 全局错误处理
self.onerror = function(error) {
    sendError(`Worker运行错误: ${error.message}`);
};

// Worker启动消息
sendMessage('ready', 'Timer Worker已就绪');
