import { filterAsyncRoutes, constantRouterMap, noMenuRouterMap } from '@/router';
import { leftMenus } from '@api/upms/api-user';
import { getStore, setStore } from '@utils/store';

const permission = {
  state: {
    constantRouters: constantRouterMap,
    routers: [],
    authBtnCodes: getStore('permissions') || [],
    multipleTag: getStore('multipleTag', true) || [],
    curTag: getStore('curTag', true) || '/home'
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.routers = routers;
    },
    SET_AUTH_BTN_CODES: (state, authBtnCodes) => {
      state.authBtnCodes = authBtnCodes;
      setStore('permissions', state.authBtnCodes);
    },
    SET_MULTIPLE_TAG: (state, multipleTag) => {
      state.multipleTag = multipleTag;
      setStore('multipleTag', state.multipleTag, true);
    },
    SET_CUR_TAG: (state, curTag) => {
      state.curTag = curTag;
      setStore('curTag', state.curTag, true);
    }
  },
  actions: {
    generateRoutes({ state, commit }) {
      return new Promise(resolve => {
        leftMenus().then(res => {
          let asyncMenu = filterAsyncRoutes(res.data, '');
          let accessedRouters = [...noMenuRouterMap, ...asyncMenu];
          let multipleTags = getStore('multipleTag', true);
          commit('SET_ROUTERS', accessedRouters);
          if (!multipleTags || multipleTags.length === 0) {
            commit('SET_MULTIPLE_TAG', [state.routers[0]]);
          } else {
            commit('SET_MULTIPLE_TAG', multipleTags);
          }
          resolve(accessedRouters);
        });
      });
    },
    removeRoutes({ commit }) {
      return new Promise(resolve => {
        commit('SET_ROUTERS', []);
        resolve();
      });
    },
    setMultipleTag({ commit }, multipleTag) {
      return new Promise(resolve => {
        commit('SET_MULTIPLE_TAG', multipleTag);
        resolve();
      });
    },
    setCurTag({ commit }, curTag) {
      return new Promise(resolve => {
        commit('SET_CUR_TAG', curTag);
        resolve();
      });
    }
  }
};

export default permission;
