import Vue from 'vue';

/**
 * 本地存储
 * @param name：本地存储的键值
 * @param obj：本地存储的数据
 */
const STORAGE_KEY = Vue.prototype.$global.STORAGE_KEY;

Vue.prototype.$storage = {
  setLocal(key, value, module_name) {
    if (module_name) {
      const val = this.getLocal(module_name);
      val[key] = value;
      this.getLocal(module_name, val);
    } else {
      const val = this.getLocalStorage();
      val[key] = value;
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(val));
    }
  },
  getLocal(key, module_name) {
    if (module_name) {
      const val = this.getLocal(); // 返回一个Object
      if (val) {
        return val[key];
      }
    }
    return this.getLocalStorage()[key];
  },
  getLocalStorage() {
    return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}');
  },
  clearLocal(key, module_name) {
    const val = this.getLocalStorage();
    if (module_name) {
      delete val[module_name][key];
    } else {
      delete val[key];
    }
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(val));
  },
  clearLocalAll() {
    window.localStorage.removeItem(STORAGE_KEY);
  },
  // 存储值
  setSession(key, value, module_name) {
    if (module_name) {
      const val = this.getSession(module_name);
      val[key] = value;
      this.setSession(module_name, val);
    } else {
      const val = this.getSessionStorage();
      val[key] = value;
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
    }
  },
  // 获取某一模块下面的属性
  getSession(key, module_name) {
    if (module_name) {
      const val = this.getSession(); // 返回一个Object
      if (val) {
        return val[key];
      }
    }
    return this.getSessionStorage()[key];
  },
  getSessionStorage() {
    return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}');
  },
  clearSession(key, module_name) {
    const val = this.getSessionStorage();
    if (module_name) {
      delete val[module_name][key];
    } else {
      delete val[key];
    }
    window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
  },
  clearSessionAll() {
    window.sessionStorage.removeItem(STORAGE_KEY);
  }
};

/**
 * @param key 键
 * @param data 要存储的值
 */
Vue.prototype.$addStorageEvent = function (key, data) {
  const newStorageEvent = document.createEvent('StorageEvent');
  const storage = {
    setItem: function (k, val) {
      Vue.prototype.$storage.setSession(k, val);
      newStorageEvent.initStorageEvent(k, false, false, k, null, val, null, null);
      window.dispatchEvent(newStorageEvent);
    }
  };
  return storage.setItem(key, data);
};
