const win = window;

class init {
  constructor(type) {
    this.storage = type === 'session' ? win.sessionStorage : type === 'lacal' ? win.localStorage : null;
    this.val = null;
    this.key = null
  }

  getVal () {
    return this.val
  }

  getItem (key, cb) {
    this.val = this.storage.getItem(key);
    this.key = key;
    try {
      this.val = JSON.parse(this.val)
    } catch (err) {}
    if (cb && typeof(cb) === 'function') {
      this.val = cb(this.val)
    }
    return this
  }

  setItem (key, val, before) {
    if (typeof(key) === 'function') {
      before = key;
      key = null
    }
    if (typeof(val) === 'function') {
      before = val;
      val = null
    }
    if (key) { this.key = key }
    if (val) { this.val = val }
    if (before && typeof(before) === 'function') {
      this.val = before(this.val)
    }
    if (typeof(this.val) !== 'string') {
      this.val = JSON.stringify(this.val)
    }
    this.storage.setItem(this.key, this.val);
    return this
  }

  removeItem (key, before) {
    if (key) { this.key = key }
    if (before && typeof(before) === 'function') {
      this.val = before(this.val)
    }
    this.storage.removeItem(this.key);
    return this
  }
  //获取表单配置信息
  getFormConfigItem (key, cb) {
     return this.getItem(key,cb);
  }
  //设置表单配置信息
  setFormConfigItem (key, val, before) {
     return this.setItem(key,val,before);
  }

  //清空表单配置信息
  removeFormConfigItem (key, before) {
    return this.removeItem(key,before);
  }
}

export default function (type) {
  return new init(type)
}
