interface CacheData<T> {
  expire: number | ''
  value: T
}

class Cache {
  private prefix: string = 'wd_admin_'
  private isSupported: boolean

  constructor() {
    this.isSupported = this.checkLocalStorageSupport()
  }

  /**
   * 检查 localStorage 是否可用
   */
  private checkLocalStorageSupport(): boolean {
    try {
      const testKey = '__test_local_storage_support__'
      window.localStorage.setItem(testKey, testKey)
      window.localStorage.removeItem(testKey)
      return true
    } catch (e) {
      return false
    }
  }

  /**
   * 获取当前时间戳（秒）
   */
  private getCurrentTime(): number {
    return Math.round(Date.now() / 1000)
  }

  /**
   * 生成带前缀的缓存键
   */
  private getFullKey(key: string): string {
    return `${this.prefix}${key}`
  }

  /**
   * 设置缓存
   * @param key 缓存键
   * @param value 缓存值
   * @param expire 过期时间（秒），0 表示永不过期
   */
  set<T>(key: string, value: T, expire: number = 0): boolean {
    if (!this.isSupported) {
      return false
    }

    try {
      const fullKey = this.getFullKey(key)
      const cacheData: CacheData<T> = {
        expire: expire > 0 ? this.getCurrentTime() + expire : '',
        value
      }

      window.localStorage.setItem(fullKey, JSON.stringify(cacheData))
      return true
    } catch (e) {
      return false
    }
  }

  /**
   * 获取缓存
   * @param key 缓存键
   * @param defaultValue 默认值
   */
  get<T>(key: string, defaultValue?: T): T | null {
    if (!this.isSupported) {
      return defaultValue || null
    }

    try {
      const fullKey = this.getFullKey(key)
      const data = window.localStorage.getItem(fullKey)

      if (!data) {
        return defaultValue || null
      }

      const cacheData: CacheData<T> = JSON.parse(data)

      // 检查是否过期
      if (cacheData.expire && cacheData.expire < this.getCurrentTime()) {
        this.remove(key)
        return defaultValue || null
      }

      return cacheData.value
    } catch (e) {
      return defaultValue || null
    }
  }

  /**
   * 移除指定缓存
   * @param key 缓存键
   */
  remove(key: string): boolean {
    if (!this.isSupported) {
      return false
    }

    try {
      const fullKey = this.getFullKey(key)
      window.localStorage.removeItem(fullKey)
      return true
    } catch (e) {
      return false
    }
  }

  /**
   * 清除所有本应用的缓存
   */
  clear(): boolean {
    if (!this.isSupported) {
      return false
    }

    try {
      const keysToRemove: string[] = []

      // 只清除带有本应用前缀的缓存
      for (let i = 0; i < window.localStorage.length; i++) {
        const key = window.localStorage.key(i)
        if (key && key.startsWith(this.prefix)) {
          keysToRemove.push(key)
        }
      }

      keysToRemove.forEach((key) => {
        window.localStorage.removeItem(key)
      })

      return true
    } catch (e) {
      return false
    }
  }

  /**
   * 获取所有缓存键
   */
  getKeys(): string[] {
    if (!this.isSupported) {
      return []
    }

    try {
      const keys: string[] = []

      for (let i = 0; i < window.localStorage.length; i++) {
        const key = window.localStorage.key(i)
        if (key && key.startsWith(this.prefix)) {
          // 返回不带前缀的键
          keys.push(key.replace(this.prefix, ''))
        }
      }

      return keys
    } catch (e) {
      return []
    }
  }

  /**
   * 检查缓存是否存在
   */
  has(key: string): boolean {
    return this.get(key) !== null
  }

  /**
   * 批量设置缓存
   */
  multiSet(items: Array<{ key: string; value: unknown; expire?: number }>): boolean {
    if (!this.isSupported) {
      return false
    }

    try {
      items.forEach((item) => {
        this.set(item.key, item.value as never, item.expire || 0)
      })
      return true
    } catch (e) {
      return false
    }
  }

  /**
   * 批量获取缓存
   */
  multiGet(keys: string[]): Record<string, unknown> {
    if (!this.isSupported) {
      return {}
    }

    const result: Record<string, unknown> = {}
    keys.forEach((key) => {
      result[key] = this.get(key)
    })

    return result
  }

  /**
   * 批量移除缓存
   */
  multiRemove(keys: string[]): boolean {
    if (!this.isSupported) {
      return false
    }

    try {
      keys.forEach((key) => {
        this.remove(key)
      })
      return true
    } catch (e) {
      return false
    }
  }
}

// 导出单例实例
const cache = new Cache()
export default cache
