import { makeAutoObservable } from "mobx";
import { routes, navigate, operation, route } from "@/router";

class Permission {
  constructor() {
    makeAutoObservable(this);
  }

  allRoutes: Array<route | navigate | operation> = [];
  addRoutes: Array<Array<route>> = [];
  sidebarRouters: Array<route> = [];

  initAllRoutes = () => {
    this.allRoutes = routes;
    this.AddInsertRoutes(this.allRoutes);
  };

  setAddRoutes = (routes: Array<route>) => {
    this.addRoutes.push(routes);
  };

  restAddRoutes = () => {
    this.addRoutes = [];
  };

  setSidebarRouters = (path: string) => {
    for (let routeArray of this.addRoutes) {
      for (let route of routeArray) {
        if (route.type === "page" && route.path === path) {
          this.sidebarRouters = routeArray;
        }
      }
    }
  };

  AddInsertRoutes = (routes: Array<route | navigate | operation>) => {
    for (let route of routes) {
      if (route.type === "page" && route.children) {
        if (route.name === "Product") {
          for (let item of this.addRoutes) {
            route.children.push(...item.filter((a) => a.path.indexOf('product/') !== -1));
          }
        } else if (route.name === "Utility") {
          for (let item of this.addRoutes) {
            route.children.push(...item.filter((a) => a.path.indexOf('utility/') !== -1));
          }
        } else {
          this.AddInsertRoutes(route.children);
        }
      }
    }
  };
}

const permissionStore = new Permission();

export default permissionStore;
