import { getselfInfo } from "@/api/external";
import { Message } from "element-ui";
import { getcarid } from "@/api/jcy";
import router from "@/router";
let staticRouter = router.options.routes.filter((item) => item.isDiy == true)[0]
  .children;
const selfPermission = {
  state: {
    token: localStorage.getItem("MSSM-LIAONING__TOKEN"),
    permissionList: [],
    routerList: [],
    userData: {},
    inspectorId: "",
  },

  mutations: {
    SET_PERMISSIONLIST: (state, permissions) => {
      permissions.forEach((item) => {
        state.permissionList.push(item.menuPerms);
      });
    },
    SET_ROUTER: (state, router) => {
      state.routerList = router;
    },
    SET_USERDATA: (state, data) => {
      state.userData = data;
    },
    SET_INSPECTORID: (state, id) => {
      state.inspectorId = id;
    },
  },
  actions: {
    //获取远程接口（路由、菜单、按钮权限）
    GetPermission({ commit, state }) {
      return new Promise((resolve, reject) => {
        getselfInfo()
          .then((res) => {
            let infoData = res.result;

            let query = {
              id: infoData.userDto.cardId,
            };
            getcarid(query).then((res) => {
              commit(
                "SET_INSPECTORID",
                res.result.length > 0 ? res.result[0].id : null
              );
            });

            //存储用户信息
            commit("SET_USERDATA", infoData.userDto);
            //过滤出按钮权限字符
            let menuButton = infoData.menuButton.filter(
              (item) => item.appCode == "JCYGL"
            );
            commit("SET_PERMISSIONLIST", menuButton);
            //过滤菜单
            let menuTree = infoData.menuTree.filter(
              (item) => item.appCode == "JCYGL"
            );
            let fileTreeOut = filterTree(menuTree[0].childMenuList, []);
            commit("SET_ROUTER", fileTreeOut);

            resolve(fileTreeOut.length > 0 ? fileTreeOut[0].path : []);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

function filterTree(tree, result) {
  tree.forEach((item) => {
    staticRouter.forEach((router, index) => {
      if (item.menuUrl == router.path) {
        result.push(router);
      }
      if (item.childMenuList != null) {
        filterTree(tree[index].childMenuList, result[index].children);
      }
    });
  });
  return result;
}

export default selfPermission;
