import moment from 'moment'

const format = 'YYYY-MM-DD HH:mm:ss'

/**
 * 负责浏览器各种存储的API
 */
export default class StorageUtils {
  /**
   * 设置sessionStorage
   * @param key
   * @param data
   */
  static setSession(key, data) {
    let obj = {
      dataType: typeof data,
      body: data,
      time: moment().format(format)
    }
    window.sessionStorage.setItem(key, JSON.stringify(obj))
  }

  /**
   * 获取sessionStorage
   * @param key
   * @returns {{time, body: any}|{time: null, body: any}|{time: null, body: null}}
   */
  static getSession(key) {
    let obj = window.sessionStorage.getItem(key)
    try {
      obj = JSON.parse(obj)
    } catch (e) {
      return { body: null, time: null }
    }
    if (obj === null) {
      return { body: null, time: null }
    }
    if (!Object.prototype.hasOwnProperty.call(obj, 'dataType')) {
      return { body: obj, time: null }
    }
    switch (obj.dataType) {
      case 'number':
        obj.body = Number(obj.body)
        break
      case 'boolean':
        obj.body = eval(obj.body)
        break
      default:
        break
    }
    return { body: obj.body, time: obj.time }
  }

  /**
   * 删除session
   * @param key
   */
  static removeSession(key) {
    window.sessionStorage.removeItem(key)
  }

  /**
   * 设置localStorage
   * @param key
   * @param data
   */
  static setLocal(key, data) {
    let obj = {
      dataType: typeof data,
      body: data,
      time: moment().format(format)
    }
    window.localStorage.setItem(key, JSON.stringify(obj))
  }

  /**
   * 获取sessionStorage
   * @param key
   * @returns {{time, body: any}|{time: null, body: any}|{time: null, body: null}}
   */
  static getLocal(key) {
    let obj = window.localStorage.getItem(key)
    try {
      obj = JSON.parse(obj)
    } catch (e) {
      return { body: null, time: null }
    }
    if (obj === null) {
      return { body: null, time: null }
    }
    if (!Object.prototype.hasOwnProperty.call(obj, 'dataType')) {
      return { body: obj, time: null }
    }
    switch (obj.dataType) {
      case 'number':
        obj.body = Number(obj.body)
        break
      case 'boolean':
        obj.body = eval(obj.body)
        break
      default:
        break
    }
    return { body: obj.body, time: obj.time }
  }

  /**
   * 删除local
   * @param key
   */
  static removeLocal(key) {
    window.localStorage.removeItem(key)
  }

  static setWisLocal(key, data) {
    this.setLocal(`WIS_${key}`, data)
  }

  static getWisLocal(key) {
    return this.getLocal(`WIS_${key}`)
  }

  /**
   * 删除local
   * @param key
   */
  static removeWisLocal(key) {
    this.removeLocal(`WIS_${key}`)
  }
}
