import { useStores } from "@/store/index";
import { elements } from "@/router";
import { current } from "@/api/demo_api";

import localStorageKey from "@/utils/localStorageKey";
import NotFound from "@/views/404";
import useMyRequest from "@/hooks/useMyRequest";
import { useEffect } from "react";
import { menu } from "@/api/routes_api";

const useMyRouter = () => {
  const { permissionStore, menuStore } = useStores();
  const userInfo = useMyRequest(current);
  const menuInfo = useMyRequest(menu);

  useEffect(() => {
    userInfo.run();
    menuInfo.run();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (userInfo.res && menuInfo.res) {
      localStorage.setItem(
        localStorageKey.USER_INFO,
        JSON.stringify(userInfo.res)
      );

      permissionStore.restAddRoutes();
      for (let item of menuInfo.res.data) {
        for (let route of item.routes) {
          route.element = elements[route.element] || NotFound;
          route.path = `/product/${item.id}${route.path}`;
        }
        permissionStore.setAddRoutes(item.routes);
      }
      menuStore.initMenu(menuInfo.res.data);
      permissionStore.initAllRoutes();
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userInfo.data, menuInfo.data]);

  return permissionStore.allRoutes;
};

export default useMyRouter;
