import Vue from "vue";
import AcesAPI from "../api/base/sysm/AcesAPI";
import SysAPI from "../api/base/sysm/SysAPI";
import CacheStores from "@/service/module/CacheStores";

export default {
  namespaced: true,
  state: {
    queryDesign: [],
    sysMenus: [],
    sysUser: {},
    sysCode: {},
    loginTimeout: false,
    loginChangePwd: false
  },
  mutations: {
    updateState(state, tab) {
      Object.assign(state, tab);
    },
    SET_SYSCODE(state, code) {
      Vue.set(state.sysCode, code.codeType, code.data);
      state.sysCode[code.codeType] = code.data;
    },
    REMOVE_SYSCODE(state, codeType) {
      state.sysCode = [];
    }
  },
  actions: {
    /**
     * 读取系统字典
     */
    async loadSysCode({commit, dispatch, state}, codeType) {
      let data = state.sysCode[codeType];
      if (data) {
        return data;
      }

      data = await CacheStores.codeListStore.getItem(codeType);
      if (data) {
        commit("SET_SYSCODE", {codeType, data});
        return data;
      }

      data = await SysAPI.getAllCodes(codeType);
      await CacheStores.codeListStore.setItem(codeType, data);
      commit("SET_SYSCODE", {codeType, data});
      return data;
    },
    /**
     * 刷新缓存sysCode
     */
    async refreshSysCode({commit, state}, codeType) {
      let data = await SysAPI.getAllCodes(codeType);
      await CacheStores.codeListStore.setItem(codeType, data);
      commit("SET_SYSCODE", {codeType, data});
      return data;
    },
    /**
     * 登录超时
     */
    timeout({commit, dispatch}) {
      commit("updateState", {loginTimeout: true});
    },
    /**
     * 获取登录信息
     */
    async getLoginInfo({commit}) {
      let data = await AcesAPI.getLoginInfo();
      commit("updateState", {sysUser: data});
      commit("updateState", {sysMenus: data.menus});
      return data;
    }
  }
};
