/**
 * 充电桩大盘 - 缓存模块
 */

import { state } from './state.js';

// 脏标记：只在数据实际变化时才写入 localStorage
let _cacheDirty = false;

/**
 * 从 localStorage 加载缓存
 */
export function loadCacheFromStorage() {
  try {
    const saved = localStorage.getItem('charger_cache');
    if (saved) {
      const data = JSON.parse(saved);
      // 只恢复 24 小时内的缓存
      const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
      if (data.freeCache) {
        state.freeCache = Object.fromEntries(
          Object.entries(data.freeCache).filter(([_, v]) => v > oneDayAgo)
        );
      }
      if (data.chargingCache) {
        state.chargingCache = Object.fromEntries(
          Object.entries(data.chargingCache).filter(([_, v]) => v > oneDayAgo)
        );
      }
      if (data.occupiedCache) {
        state.occupiedCache = Object.fromEntries(
          Object.entries(data.occupiedCache).filter(([_, v]) => v > oneDayAgo)
        );
      }
      console.log('[缓存] 从 localStorage 恢复', state.freeCache, state.chargingCache, state.occupiedCache);
    }
  } catch (e) {
    console.warn('[缓存] 加载失败', e);
  }
}

/**
 * 保存缓存到 localStorage（仅在脏标记为 true 时执行）
 */
export function saveCacheToStorage() {
  if (!_cacheDirty) return;
  try {
    localStorage.setItem('charger_cache', JSON.stringify({
      freeCache: state.freeCache,
      chargingCache: state.chargingCache,
      occupiedCache: state.occupiedCache,
      savedAt: Date.now()
    }));
    _cacheDirty = false;
  } catch (e) {
    console.warn('[缓存] 保存失败', e);
  }
}

/**
 * 更新状态缓存（空闲/充电/占位）
 */
export function updateStateCache(connectors) {
  const now = Date.now();
  connectors.forEach(c => {
    const key = c.connector_id || c.connector_name;
    // 空闲状态缓存
    if (c.state.type === 'free') {
      if (!state.freeCache[key]) { state.freeCache[key] = now; _cacheDirty = true; }
    } else {
      if (state.freeCache[key]) { delete state.freeCache[key]; _cacheDirty = true; }
    }
    // 充电状态缓存
    if (c.state.type === 'charging') {
      if (!state.chargingCache[key]) { state.chargingCache[key] = now; _cacheDirty = true; }
    } else {
      if (state.chargingCache[key]) { delete state.chargingCache[key]; _cacheDirty = true; }
    }
    // 占位状态缓存
    if (c.state.type === 'occupied') {
      if (!state.occupiedCache[key]) { state.occupiedCache[key] = now; _cacheDirty = true; }
    } else {
      if (state.occupiedCache[key]) { delete state.occupiedCache[key]; _cacheDirty = true; }
    }
  });
  // 持久化到 localStorage（仅在有变化时）
  saveCacheToStorage();
}

/**
 * 更新空闲/充电状态缓存（兼容旧调用）
 * @deprecated 请使用 updateStateCache
 */
export function updateFreeCache(connectors) {
  updateStateCache(connectors);
}
