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";
import { IProductOption } from "@/store/modules/productList";

const useMyRouter = () => {
  const { permissionStore, menuStore, productListStore } = 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) {
        let childrenRoutes: any = []
        for (let route of item.routes) {
          route.element = elements[route.element] || NotFound;
          route.path = `/product/${item.id}${route.path}`;
          if (Array.isArray(route.children)) {
            route.children.forEach((childrenItem: any, index: number) => {
              if (childrenItem.path) {
                childrenRoutes.push({
                  ...childrenItem,
                  element: elements[childrenItem.element] || NotFound,
                  path: `${route.path}${childrenItem.path}`,
                  show: false
                })
              }
            })
            route.children = route.children.filter((childrenItem: any) => !childrenItem.path)
          }
        }
        // permissionStore.setAddRoutes(item.routes);
        permissionStore.setAddRoutes([...childrenRoutes, ...item.routes]);
      }
      menuStore.initMenu(menuInfo.res.data);
      permissionStore.initAllRoutes();

      // /** 所有产品列表 */
      const newProductList:IProductOption[] =  [];
      for (let item of menuInfo.res.data) {
        if (item.type === "product") {
          newProductList.push({
            label: item.name,
            value: item.id,
          });
        }
      }
      productListStore.setProductList(newProductList)
    }

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

  return permissionStore.allRoutes;
};

export default useMyRouter;
