import Vue from "vue";
import AcesAPI from "../api/base/sysm/AcesAPI";
import SysAPI from "../api/base/sysm/SysAPI";
import QueryDesignerAPI from "../api/base/sysm/QueryDesignerAPI";

export default {
  namespaced: true,
  state: {
    lang: Vue.config.lang,
    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 = [];
    },
    SET_LOGIN(state, sysLogin) {
      Object.assign(state.sysLogin, sysLogin);
    }
  },
  actions: {
    /**
     * 读取系统字典
     */
    loadSysCode({commit, dispatch, state}, codeType) {
      // 假设当前code已经加载过,就放弃本次处理
      if (state.sysCode[codeType] !== undefined) {
        return new Promise((resolve, reject) => {
          resolve({codeType: codeType, data: state.sysCode[codeType]});
        });
      }
      // 否则从本地存储读取,读取不到从服务器读取
      return (
        SysAPI.getAllCodes(codeType)
        // 成功设置到系统状态
          .then(data => {
            commit("SET_SYSCODE", {codeType, data});
            // 返回数据,交给下一承诺处理
            return {codeType, data};
          })
      );
    },
    /**
     * 刷新缓存sysCode
     */
    refreshSysCode({commit, state}, codeType) {
      return SysAPI.getAllCodes(codeType, true).then(data => {
        commit("SET_SYSCODE", {codeType, data});
        return data;
      });
    },
    /**
     * 登录超时
     */
    timeout({commit, dispatch}) {
      commit("SET_LOGIN", {timeout: true});
    },
    /**
     * 获取登录信息
     */
    async getLoginInfo({commit}) {
      let data = await AcesAPI.getLoginInfo();
      commit("updateState", {sysUser: data});
      commit("updateState", {sysMenus: data.menus});
      return data;
    },
    /**
     * 获取查询定义
     */
    getQueryDesign({commit}) {
      return QueryDesignerAPI.loadDesignMine().then(data => {
        commit("updateState", {queryDesign: data});
        return data;
      });
    },

    setPdfUuid({commit, dispatch, state}, uuid) {
      commit("updateState", {pdfUuid: uuid});
    }
  }
};
