import { login } from "../api/login";
import { getAuthRouterFn } from "@/utils/getAuth";
import { resetRouter } from "@/router/index";

export default {
  namespaced: true, // 子模块一定要开启命名空间
  state: {
    userInfo: {},
  },
  getters: {},
  mutations: {
    SET_USERINFO(state, payload) {
      state.userInfo = payload;
    },
    RESET_USER_STATE(state) {
      state.userInfo = {};
      resetRouter();
    },
  },
  actions: {
    async goLogin({ commit, dispatch }, { loginForm, router }) {
      try {
        const result = await login(loginForm);
        commit("SET_USERINFO", result.data);
        dispatch("setAddRouter", {
          resultRouter: result.data.permission,
          router,
        });
      } catch (error) {
        console.error("Login error:", error);
      }
    },
    setAddRouter({ commit }, { resultRouter, router }) {
      // 获取home路由
      const homeRoute = router.options.routes.find(
        (route) => route.name === "home"
      );
      // 确保home路由存在
      if (homeRoute) {
        if (!homeRoute.children) {
          homeRoute.children = [];
        }
        // 过滤掉动态添加的路由，保留初始状态的路由
        const originalChildren = homeRoute.children.filter(
          (route) => route.meta && !route.meta.dynamic
        );
        // 清空原有的动态子路由
        homeRoute.children = originalChildren;
        const { authRouterList } = getAuthRouterFn(resultRouter);
        authRouterList.forEach((item) => {
          // 动态路由的父路径设置为home
          homeRoute.children.push(item);
        });
        // 重新添加home路由
        router.addRoute(homeRoute);
      }
      // 添加404页面路由
      router.addRoute({
        path: "/:pathMatch(.*)*",
        name: "NotFound",
        component: () => import("@/views/error/404.vue"),
        meta: { hidden: true },
      });
      // 确保导航到动态添加的路由
      router.push("/home");
    },
    logout({ commit }) {
      // 重置 Vuex 状态
      commit("RESET_USER_STATE");
      // 重置路由
      resetRouter();
    },
  },
};
