import { resetAllStores } from '@/main'
import { native_api } from '@/utils'

// store统一设置
const beforeHandle = (key: string) => {
  if (!key) {
    console.error('storage key is required')
    return true
  }
  return false
}
export const setCache = (key: string, value: any) => {
  if (beforeHandle(key)) return
  const XKey = `X_${key?.toUpperCase()}`
  if (native_api?.setData) {
    return native_api.setData(XKey, value)
  }
  localStorage.setItem(XKey, value)
}
export const getCache = (key: string) => {
  if (beforeHandle(key)) return
  const XKey = `X_${key?.toUpperCase()}`
  if (native_api?.getData) {
    const res = JSON.parse(native_api.getData(XKey))
    if (res.code !== 200) return ''
    return res.data
  }
  return localStorage.getItem(XKey)
}
export const delCache = (key: string) => {
  if (beforeHandle(key)) return
  const XKey = `X_${key?.toUpperCase()}`
  if (native_api?.removeData) {
    return native_api.removeData(XKey)
  }
  localStorage.removeItem(XKey)
}
export const clearCache = () => {
  resetAllStores()
  localStorage.clear()
  if (native_api?.removeAllData) {
    return native_api.removeAllData()
  }
}
