// ═══════════════════════════════════════════════════════════════
//  性能优化模块 - Performance Optimizer
//  用途：定时器优化 + API请求缓存
// ═══════════════════════════════════════════════════════════════

/**
 * 智能定时器管理器
 * 功能：页面不可见时自动停止定时器，节省CPU和内存
 */
class SmartTimer {
    constructor() {
        this.timers = new Map();
        this.isActive = !document.hidden;
        this.setupVisibilityListener();
        console.log('⚡ SmartTimer初始化完成');
    }

    /**
     * 创建智能定时器
     * @param {string} name - 定时器名称（用于调试）
     * @param {Function} callback - 回调函数
     * @param {number} interval - 间隔时间（毫秒）
     * @returns {string} 定时器ID
     */
    create(name, callback, interval) {
        // 如果已存在同名定时器，先清除
        if (this.timers.has(name)) {
            this.clear(name);
        }

        const timer = {
            name: name,
            callback: callback,
            interval: interval,
            intervalId: null,
            isRunning: false
        };

        this.timers.set(name, timer);

        // 如果页面可见，立即启动
        if (this.isActive) {
            this._startTimer(timer);
        }

        console.log(`⏱️ 创建定时器: ${name} (${interval}ms)`);
        return name;
    }

    /**
     * 清除指定定时器
     */
    clear(name) {
        const timer = this.timers.get(name);
        if (timer) {
            this._stopTimer(timer);
            this.timers.delete(name);
            console.log(`🗑️ 清除定时器: ${name}`);
        }
    }

    /**
     * 清除所有定时器
     */
    clearAll() {
        this.timers.forEach(timer => this._stopTimer(timer));
        this.timers.clear();
        console.log('🗑️ 清除所有定时器');
    }

    /**
     * 启动指定定时器
     */
    start(name) {
        const timer = this.timers.get(name);
        if (timer && !timer.isRunning) {
            this._startTimer(timer);
        }
    }

    /**
     * 停止指定定时器
     */
    stop(name) {
        const timer = this.timers.get(name);
        if (timer && timer.isRunning) {
            this._stopTimer(timer);
        }
    }

    /**
     * 内部方法：启动定时器
     */
    _startTimer(timer) {
        if (timer.isRunning) return;

        timer.intervalId = setInterval(() => {
            try {
                timer.callback();
            } catch (error) {
                console.error(`❌ 定时器执行错误 [${timer.name}]:`, error);
            }
        }, timer.interval);

        timer.isRunning = true;
        console.log(`▶️ 启动定时器: ${timer.name}`);
    }

    /**
     * 内部方法：停止定时器
     */
    _stopTimer(timer) {
        if (!timer.isRunning) return;

        if (timer.intervalId) {
            clearInterval(timer.intervalId);
            timer.intervalId = null;
        }

        timer.isRunning = false;
        console.log(`⏸️ 停止定时器: ${timer.name}`);
    }

    /**
     * 设置页面可见性监听
     */
    setupVisibilityListener() {
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAll();
            } else {
                this.resumeAll();
            }
        });

        // iframe失去焦点（用于iframe内的页面）
        window.addEventListener('blur', () => {
            if (!document.hidden) {
                console.log('⏸️ 窗口失去焦点，暂停定时器');
                this.pauseAll();
            }
        });

        // iframe获得焦点
        window.addEventListener('focus', () => {
            if (!document.hidden) {
                console.log('▶️ 窗口获得焦点，恢复定时器');
                this.resumeAll();
            }
        });

        // 页面卸载时清理
        window.addEventListener('beforeunload', () => {
            this.clearAll();
        });
    }

    /**
     * 暂停所有定时器
     */
    pauseAll() {
        if (!this.isActive) return;
        this.isActive = false;
        
        this.timers.forEach(timer => {
            this._stopTimer(timer);
        });
        
        console.log('⏸️ 暂停所有定时器（页面不可见）');
    }

    /**
     * 恢复所有定时器
     */
    resumeAll() {
        if (this.isActive) return;
        this.isActive = true;
        
        this.timers.forEach(timer => {
            this._startTimer(timer);
        });
        
        console.log('▶️ 恢复所有定时器（页面可见）');
    }

    /**
     * 获取统计信息
     */
    getStats() {
        const total = this.timers.size;
        let running = 0;
        this.timers.forEach(timer => {
            if (timer.isRunning) running++;
        });

        return {
            total: total,
            running: running,
            paused: total - running,
            isActive: this.isActive
        };
    }
}


/**
 * API请求缓存管理器
 * 功能：缓存API响应，减少重复请求
 */
class APICache {
    constructor(options = {}) {
        this.cache = new Map();
        this.defaultTTL = options.ttl || 60000; // 默认1分钟
        this.maxSize = options.maxSize || 100; // 最多缓存100条
        this.cleanupInterval = options.cleanupInterval || 120000; // 2分钟清理一次
        
        this.stats = {
            hits: 0,
            misses: 0,
            errors: 0,
            saves: 0
        };

        this.startCleanup();
        console.log('📦 APICache初始化完成', {
            ttl: this.defaultTTL + 'ms',
            maxSize: this.maxSize
        });
    }

    /**
     * 生成缓存键
     */
    _generateKey(url, params = {}) {
        const paramStr = JSON.stringify(params);
        return `${url}::${paramStr}`;
    }

    /**
     * 获取缓存数据
     */
    get(url, params = {}) {
        const key = this._generateKey(url, params);
        const cached = this.cache.get(key);
        const now = Date.now();

        if (!cached) {
            this.stats.misses++;
            console.log('📭 缓存未命中:', url);
            return null;
        }

        // 检查是否过期
        if (now - cached.timestamp > cached.ttl) {
            this.cache.delete(key);
            this.stats.misses++;
            console.log('⏰ 缓存已过期:', url);
            return null;
        }

        this.stats.hits++;
        const age = ((now - cached.timestamp) / 1000).toFixed(1);
        console.log(`📦 缓存命中: ${url} (${age}s前)`);
        
        return cached.data;
    }

    /**
     * 设置缓存数据
     */
    set(url, data, params = {}, ttl = null) {
        const key = this._generateKey(url, params);
        
        // 如果超过最大容量，删除最旧的
        if (this.cache.size >= this.maxSize) {
            const firstKey = this.cache.keys().next().value;
            this.cache.delete(firstKey);
            console.log('🗑️ 缓存已满，删除最旧条目');
        }

        this.cache.set(key, {
            url: url,
            data: data,
            timestamp: Date.now(),
            ttl: ttl || this.defaultTTL
        });

        this.stats.saves++;
        console.log(`💾 缓存已保存: ${url} (TTL: ${(ttl || this.defaultTTL) / 1000}s)`);
    }

    /**
     * 清除指定缓存
     */
    clear(url, params = {}) {
        const key = this._generateKey(url, params);
        this.cache.delete(key);
        console.log(`🗑️ 清除缓存: ${url}`);
    }

    /**
     * 清除所有缓存
     */
    clearAll() {
        const count = this.cache.size;
        this.cache.clear();
        console.log(`🗑️ 清除所有缓存 (${count}条)`);
    }

    /**
     * 带缓存的fetch封装
     */
    async fetch(url, options = {}) {
        const {
            params = {},
            ttl = null,
            forceRefresh = false,
            returnStale = true // 失败时返回过期缓存
        } = options;

        // 如果不强制刷新，先检查缓存
        if (!forceRefresh) {
            const cached = this.get(url, params);
            if (cached) {
                return cached;
            }
        }

        // 缓存未命中或强制刷新，发起请求
        try {
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            
            // 保存到缓存
            this.set(url, data, params, ttl);
            
            return data;

        } catch (error) {
            this.stats.errors++;
            console.error(`❌ API请求失败 [${url}]:`, error.message);

            // 如果允许返回过期缓存
            if (returnStale) {
                const key = this._generateKey(url, params);
                const stale = this.cache.get(key);
                
                if (stale) {
                    const age = ((Date.now() - stale.timestamp) / 1000).toFixed(1);
                    console.warn(`⚠️ 返回过期缓存 (${age}s前)`);
                    return stale.data;
                }
            }

            throw error;
        }
    }

    /**
     * 启动定期清理
     */
    startCleanup() {
        setInterval(() => {
            this.cleanup();
        }, this.cleanupInterval);
    }

    /**
     * 清理过期缓存
     */
    cleanup() {
        const now = Date.now();
        let cleaned = 0;

        for (const [key, cached] of this.cache.entries()) {
            if (now - cached.timestamp > cached.ttl * 2) {
                this.cache.delete(key);
                cleaned++;
            }
        }

        if (cleaned > 0) {
            console.log(`🧹 清理过期缓存: ${cleaned}条`);
        }
    }

    /**
     * 获取统计信息
     */
    getStats() {
        const hitRate = this.stats.hits + this.stats.misses > 0
            ? (this.stats.hits / (this.stats.hits + this.stats.misses) * 100).toFixed(1)
            : 0;

        return {
            ...this.stats,
            hitRate: hitRate + '%',
            cacheSize: this.cache.size,
            maxSize: this.maxSize
        };
    }

    /**
     * 打印统计信息
     */
    printStats() {
        const stats = this.getStats();
        console.log('📊 API缓存统计:');
        console.table(stats);
    }
}


// ═══════════════════════════════════════════════════════════════
// 全局实例（单例模式）
// ═══════════════════════════════════════════════════════════════

window.smartTimer = window.smartTimer || new SmartTimer();
window.apiCache = window.apiCache || new APICache({
    ttl: 60000,      // 1分钟缓存
    maxSize: 100,    // 最多100条
    cleanupInterval: 120000  // 2分钟清理一次
});

console.log('✅ 性能优化模块加载完成');

