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();
      if (window.location.host === "localhost:8088") {
        menuInfo.res.data.forEach((item: any) => {
          if (item.id === 'cadd') {
            item.routes.push({
              element: 'Demo',
              id: "demo",
              name: "demo",
              order: 1000,
              path: "/demo",
              show: true,
              type: "page",
            })
          }
        });
      }
     
      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;
