import CacheStores from "./CacheStores";
import store from "@/store";
import {Notification} from "element-ui";
import Vue from "vue";
import SysAPI from "@/api/base/sysm/SysAPI";

function notify() {
  Notification.success({
    title: "成功",
    message: "系统字典已经更新."
  });
}

export default {
  // 监听字典改变
  async OBSERVER_TOPIC_CACHE_CODE(data) {
    let {codetype, version} = data.message;
    let codes = await SysAPI.getAllCodes(codetype);
    await CacheStores.codeListStore.setItem(codetype, codes);
    await CacheStores.codeTreeStore.setItem("VERSION", version);
    Vue.set(store.base.state.sysCode, codetype, codes);
    notify();
  },

  // 监听树改变
  async OBSERVER_TOPIC_CACHE_TREE(data) {
    let {treetype, version} = data.message;
    await CacheStores.codeTreeStore.iterate((value, key) => {
      if (key.startsWith(treetype)) {
        CacheStores.codeTreeStore.removeItem(key);
      }
    });
    await CacheStores.codeTreeStore.setItem("VERSION", version);
    notify();
  },

  /**
   * 修正缓存数据
   * @param {String } tocpic  要修正的主题
   * @param {String} version  检测版本号.
   */
  async repairWith(tocpic, version) {
    if (!version) {
      return;
    }
    if (!tocpic) {
      return;
    }
    // 树刷新
    if (tocpic === "OBSERVER_TOPIC_CACHE_TREE") {
      let data = await CacheStores.codeTreeStore.getItem("VERSION");
      if (data !== version) {
        await CacheStores.codeTreeStore.iterate((value, key, iterationNumber) => {
          CacheStores.codeTreeStore.removeItem(key);
        });
      }
      await CacheStores.codeTreeStore.setItem("VERSION", version);
    }
    // 字典项刷新
    if (tocpic === "OBSERVER_TOPIC_CACHE_CODE") {
      let data = await CacheStores.codeListStore.getItem("VERSION");
      if (data !== version) {
        await CacheStores.codeListStore.iterate((value, key, iterationNumber) => {
          CacheStores.codeListStore.removeItem(key);
        });
      }
      await CacheStores.codeListStore.setItem("VERSION", version);
    }
  }
};
