/*
 * @Description: sessionStorage 封装
 */
import crypt from '@/lib/crypt'

class SessionStorage {
  constructor() {
    this.Data = sessionStorage
  }

  // 获取 key中的数据
  Get(key, flag = false) {
    let res = null
    try {
      if (flag) {
        res = crypt.Decrypt(this.Data[key])
      } else {
        res = this.Data[key]
      }
      return this.IsExist(key) ? res : null
    } catch (error) {
      console.error(`Error getting session data for key "${key}":`, error)
      return null
    }
  }

  // 更新或创建新数据
  Set(key, val, flag = false) {
    let res = null
    try {
      if (flag) {
        res = crypt.Encrypt(String(val))
      } else {
        res = String(val)
      }
      this.Data[key] = sessionStorage[key] = res
    } catch (error) {
      console.error(`Error setting session data for key "${key}":`, error)
    }
  }

  // 输出 key 数据
  Del(key) {
    this.Data[key] = null
    sessionStorage.removeItem(key)
  }

  // key数据是否存在
  IsExist(key) {
    return this.Data.getItem(key) ? true : false
  }

  // 清除所有session
  Clear() {
    this.Data = null
    sessionStorage.clear()
  }
}

export default new SessionStorage()
