// 缓存工具 - 提供sessionStorage和localStorage的封装

export default {
  // sessionStorage
  session: {
    // 设置sessionStorage
    set(key, value) {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      sessionStorage.setItem(key, value)
    },
    // 获取sessionStorage
    get(key) {
      const value = sessionStorage.getItem(key)
      try {
        return JSON.parse(value)
      } catch (e) {
        return value
      }
    },
    // 获取sessionStorage（JSON格式）
    getJSON(key) {
      const value = sessionStorage.getItem(key)
      try {
        return JSON.parse(value)
      } catch (e) {
        return null
      }
    },
    // 移除sessionStorage
    remove(key) {
      sessionStorage.removeItem(key)
    },
    // 清空sessionStorage
    clear() {
      sessionStorage.clear()
    }
  },
  
  // localStorage
  local: {
    // 设置localStorage
    set(key, value) {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      localStorage.setItem(key, value)
    },
    // 获取localStorage
    get(key) {
      const value = localStorage.getItem(key)
      try {
        return JSON.parse(value)
      } catch (e) {
        return value
      }
    },
    // 获取localStorage（JSON格式）
    getJSON(key) {
      const value = localStorage.getItem(key)
      try {
        return JSON.parse(value)
      } catch (e) {
        return null
      }
    },
    // 移除localStorage
    remove(key) {
      localStorage.removeItem(key)
    },
    // 清空localStorage
    clear() {
      localStorage.clear()
    }
  }
}