import router from '@/router'
import { name as appName } from '../../../package.json'

let name = `${appName}-${import.meta.env.VITE_NODE_ENV}`

const sessionCache = {
  set(key, value) {
    if (!sessionStorage) {
      return
    }
    if (key != null && value != null) {
      let storageStr = sessionStorage.getItem(name)
      let storage = storageStr ? JSON.parse(storageStr) : {}
      Reflect.set(storage, key, value)
      sessionStorage.setItem(name, JSON.stringify(storage))
    }
  },
  get(key) {
    if (!sessionStorage) {
      return null
    }
    if (key == null) {
      return null
    }
    let storageStr = sessionStorage.getItem(name)
    let storage = storageStr ? JSON.parse(storageStr) : {}
    return storage[key]
  },
  remove(key) {
    if (!sessionStorage) {
      return null
    }
    if (key == null) {
      return null
    }
    let storageStr = sessionStorage.getItem(name)
    let storage = storageStr ? JSON.parse(storageStr) : {}
    delete storage[key]
    sessionStorage.setItem(name, JSON.stringify(storage))
  }
}
const localCache = {
  set(key, value) {
    if (!localStorage) {
      return
    }
    if (key != null && value != null) {
      let storageStr = localStorage.getItem(name)
      let storage = storageStr ? JSON.parse(storageStr) : {}
      Reflect.set(storage, key, value)
      localStorage.setItem(name, JSON.stringify(storage))
    }
  },
  get(key) {
    if (!localStorage) {
      return null
    }
    if (key == null) {
      return null
    }
    let storageStr = localStorage.getItem(name)
    let storage = storageStr ? JSON.parse(storageStr) : {}
    return storage[key]
  },
  remove(key) {
    if (!localStorage) {
      return null
    }
    if (key == null) {
      return null
    }
    let storageStr = localStorage.getItem(name)
    let storage = storageStr ? JSON.parse(storageStr) : {}
    delete storage[key]
    localStorage.setItem(name, JSON.stringify(storage))
  }
}

function setParams(params) {
  sessionCache.set(`${router.currentRoute.value.name}-search`, params)
}

function getParams() {
  return sessionCache.get(`${router.currentRoute.value.name}-search`)
}

export default {
  /**
   * 会话级缓存
   */
  session: sessionCache,
  /**
   * 本地缓存
   */
  local: localCache,
  setParams,
  getParams
}
