import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCacheStore = defineStore('cache', () => {
  // 缓存Map
  const cache = ref(new Map())
  const CACHE_DURATION = 30 * 60 * 1000 // 30分钟缓存时长

  // 生成缓存键
  const getCacheKey = (apiName, params = {}) => {
    const sortedParams = Object.keys(params)
      .sort()
      .reduce((result, key) => {
        result[key] = params[key]
        return result
      }, {})
    return `${apiName}_${JSON.stringify(sortedParams)}`
  }

  // 检查缓存是否有效
  const isValidCache = (cacheData) => {
    return cacheData && (Date.now() - cacheData.timestamp) < CACHE_DURATION
  }

  // 设置缓存
  const setCache = (key, data) => {
    cache.value.set(key, {
      data,
      timestamp: Date.now()
    })
  }

  // 获取缓存
  const getCache = (key) => {
    const cacheData = cache.value.get(key)
    if (isValidCache(cacheData)) {
      return cacheData.data
    }
    // 如果缓存过期，删除它
    if (cacheData) {
      cache.value.delete(key)
    }
    return null
  }

  // 缓存包装器函数
  const withCache = async (apiName, apiFunction, params = {}) => {
    const cacheKey = getCacheKey(apiName, params)
    const cachedData = getCache(cacheKey)
    
    if (cachedData) {
      console.log(`[缓存命中] ${apiName}:`, cachedData)
      return cachedData
    }
    
    console.log(`[API调用] ${apiName}`)
    const result = await apiFunction(params)
    setCache(cacheKey, result)
    return result
  }

  // 清除所有缓存
  const clearCache = () => {
    cache.value.clear()
    console.log('所有缓存已清除')
  }

  // 清除特定缓存
  const clearSpecificCache = (apiName, params = {}) => {
    const key = getCacheKey(apiName, params)
    cache.value.delete(key)
    console.log(`已清除缓存: ${key}`)
  }

  // 获取缓存信息并清理过期缓存
  const getCacheInfo = () => {
    const now = Date.now()
    const validCaches = []
    const expiredCaches = []
    
    for (const [key, data] of cache.value.entries()) {
      if (isValidCache(data)) {
        validCaches.push({
          key,
          timestamp: data.timestamp,
          age: Math.round((now - data.timestamp) / 1000) + 's'
        })
      } else {
        expiredCaches.push(key)
        cache.value.delete(key)
      }
    }
    
    return {
      validCount: validCaches.length,
      expiredCount: expiredCaches.length,
      validCaches,
      expiredCaches
    }
  }

  // 清除过期缓存
  const clearExpiredCache = () => {
    const info = getCacheInfo()
    console.log(`清理了 ${info.expiredCount} 个过期缓存`)
    return info
  }

  // 获取缓存统计信息
  const getCacheStats = () => {
    return {
      totalCount: cache.value.size,
      duration: CACHE_DURATION / (1000 * 60) + '分钟',
      ...getCacheInfo()
    }
  }

  return {
    // 状态
    cache,
    CACHE_DURATION,
    
    // 方法
    getCacheKey,
    isValidCache,
    setCache,
    getCache,
    withCache,
    clearCache,
    clearSpecificCache,
    getCacheInfo,
    clearExpiredCache,
    getCacheStats
  }
})