import router from ".";
import store from "@/store";

const layout = () => import("@/layout/index.vue");

// 动态路由
export async function formatRoutes(aMenu: any, parentId?: string) {
  // console.log(aMenu);
  await aMenu.forEach((item: any) => {
    const haveChild: boolean = item.children?.length > 0;
    const route = {
      path: item.path,
      name: item.name,
      redirect: haveChild ? item.children[0].path : "",
      meta: {
        keepAlive: Number(item.keepAlive) === 1
      },
      component: haveChild ? layout : () => import(`@/views${item.path}/index.vue`)
    };
    if (parentId) {
      router.addRoute(parentId, route);
    } else {
      router.addRoute(route);
    }
    if (haveChild) {
      formatRoutes(item.children, item.name);
    }
  });
}

// 设置标题
export function setTitle(title: string) {
  const defaultTitle = "中央应急物资储备管理系统";
  title = title ? `${title}——${defaultTitle}` : defaultTitle;
  document.title = title;
}

// 移除当前tag，则打开最后一个tag
export function closeTagAndOpenLastTag() {
  store.commit("DEL_TAG", store.getters.tag);
  router.push({
    path: store.getters.tagList[store.getters.tagList.length - 1].value
  });
}
