import { sysMenu } from "../modules/login/api";
import staticMenu from "../constants/staticMenu";
// import localMenus from "../constants/menus-data";
import adminNavs from "../constants/adminNavs";

const state = {
  privilegeMap: {},
  privileges: [],
  validRoutes: [],
  menus: [],
};

const mutations = {
  setPrivilegeMap(state, privilegeMap) {
    state.privilegeMap = privilegeMap;
  },
  initStore() {
    state.privilegeMap = {};
    state.privileges = [];
    state.validRoutes = [];
    state.menus = [];
  },
};

function getPrivilegeMap(data) {
  const privilegeMap = {};
  const pageSetTypes = ["conditions", "buttons", "lists", "links"];
  data.forEach((item) => {
    privilegeMap[item.url] = [item.id];
    pageSetTypes.forEach((type) => {
      if (item[type] && item[type].length) {
        item[type].forEach((elem) => {
          privilegeMap[item.url].push(`${elem.type}_${elem.url}`.toLowerCase());
        });
      }
    });
  });

  return privilegeMap;
}

function transformMenu(list) {
  return list.map((item) => {
    return {
      id: item.id,
      parentId: item.parentId,
      name: item.name,
      type: item.type,
      url: item.url,
    };
  });
}

function getMenu(privileges) {
  const getChildren = (id) => {
    return privileges
      .filter((item) => item.parentId === id)
      .map((item) => {
        return { ...item };
      });
  };

  const menus = getChildren("-1");
  const validRoutes = [];
  const toTree = (menus) => {
    menus.forEach((menu) => {
      const children = getChildren(menu.id);
      if (children.length) {
        menu.children = children;
        toTree(menu.children);
      } else {
        validRoutes.push(menu.url);
      }
    });
  };
  toTree(menus);

  return { menus, validRoutes };
}

const actions = {
  async updatePrivilegeMap({ state }, isSuperAdmin) {
    const data = await sysMenu();
    // const data = { privileges: localMenus };
    // 超管进入学校页面不显示首页
    const privileges = isSuperAdmin
      ? data.privileges
      : [...staticMenu, ...data.privileges];
    state.privilegeMap = getPrivilegeMap(privileges);
    state.privileges = transformMenu(privileges);
    const { validRoutes, menus } = getMenu(state.privileges);
    state.menus = menus;
    state.validRoutes = [...validRoutes, "Home"];
  },
  updateAdminPrivilegeMap({ state }) {
    state.privileges = adminNavs;
    const { validRoutes, menus } = getMenu(state.privileges);
    state.menus = menus;
    state.validRoutes = [...validRoutes, "Admin"];
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
