import router from "./router";
import { resetRouter } from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import Layout from "@/layout";
const _import = require("./router/_import_" + process.env.NODE_ENV); // 获取组件的方法

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // get user info
          await store.dispatch("user/getInfo");

          // 请求获取路由表
          await store.dispatch("user/getRouter");
          if (store.getters.menus.length < 1) {
            global.antRouter = [];
            next();
          }

          // 设置路由
          var newRoutes = [];

          for (var route of store.getters.menus) {

            const item = buildRootRoute(route);
            newRoutes.push(item);
          }
          console.log(newRoutes,'8589');
          // newRoutes.shift();
          // 添加一项根目录重定向页面
          if (newRoutes[0].path != "/") {
            let path = newRoutes[0].path;
            if (newRoutes[0].children.length > 0) {
              path = `${path}/${newRoutes[0].children[0].path}`;
            }
            if (newRoutes[0].children[0].children.length > 0) {
              path = `${path}/${newRoutes[0].children[0].children[0].path}`;
            }
            newRoutes.unshift({
              path: "/",
              component: Layout,
              redirect: path,
            });
          } else {
            newRoutes[0].redirect = "/dashboard";
          }

          console.log(newRoutes);
          router.addRoutes(newRoutes); // 2.动态添加路由
          global.antRouter = newRoutes; // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作

          // const menus = filterAsyncRouter(store.getters.menus) // 1.过滤路由
          // console.log(menus);
          // router.addRoutes(menus) // 2.动态添加路由
          // global.antRouter = menus // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作
          next({
            ...to,
            replace: true,
          });
          // next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next('/login')
          // next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`);
      next('/login')
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});

// 遍历后台传来的路由字符串，转换为组件对象
// function filterAsyncRouter(asyncRouterMap) {
//   const accessedRouters = asyncRouterMap.filter((route) => {
//     console.log(route);
//     if (route.component) {
//       if (route.component === "Layout") {
//         route.component = Layout;
//       } else {
//         route.component = _import(route.component); // 导入组件
//       }
//     }
//     if (route.children && route.children.length) {
//       route.children = filterAsyncRouter(route.children);
//     }
//     return true;
//   });
//   return accessedRouters;
// }

function buildRootRoute(route) {
  const { url, icon, moduleName, moduleId, code, type,fullUrl  } = route;
  var item = {};
  item.path = url;
  item.component = Layout;
  item.name = code;
  item.meta = {
    title: moduleName,
    icon: icon,
  };
  if (code == "index") {
    item.path = "/";
    item.alwaysShow = false;
    let children = route.children;
    route.children = [];
    route.children.push({
      code: "dashboard",
      moduleName: "首页",
      type: 2,
      url: "/dashboard",
      children: children,
    });
  }
  if (code == "issue") {
    let children = route.children;
    route.children = [];
    route.children.push({
      code: "issue_index",
      moduleName: "文件下发",
      type: 2,
      url: "/index",
      children: children,
    });
    item.alwaysShow = false;
  }
  if (code == "notice") {
    let children = route.children;
    route.children = [];
    route.children.push({
      code: "notice_index",
      moduleName: "系统通知",
      type: 2,
      url: "/index",
      children: children,
    });
    item.alwaysShow = false;
  }
  item.children = [];
  if (
    (route.hasOwnProperty("children") && type === 1) ||
    code == "issue" ||
    code == "notice" ||
    code == "index"
  ) {

    for (var child of route.children) {
      item.children.push(buildRoute(child, fullUrl));
    }
  }
  return item;
}

function buildRoute(route, p_url) {
  const { url, moduleName, icon, moduleId, code, type, hidden,fullUrl } = route;
  var item = {};
  if (url.substr(0, 1) == "/") {
    item.path = url.substr(1);
  } else {
    item.path = url;
  }
  try {
    if (code == "dashboard") {
      // item.component = _import(`${url}/index`)
      item.component = (resolve) =>
        require(["@/views" + `${url}/index`], resolve);
    } else {

      if (fullUrl) {
        item.component = _import(`${fullUrl}`);
      }else{
        item.component = _import(`${p_url}${url}`);

      }

    }
  } catch (e) {
    console.log(e);
  }
  item.name = code;
  item.meta = {
    title: moduleName,
    icon: icon,
  };
  if (route.children && type == 2) {
    let roles = [];
    for (var role of route.children) {
      roles.push(role.code);
    }
    item.meta.roles = roles;
  }
  item.hidden = hidden;
  item.children = [];
  if (route.hasOwnProperty("children") && type === 1) {
    for (var child of route.children) {
      item.children.push(buildThirdRoute(child, `${p_url}${url}`));
    }
  }
  return item;
}

function buildThirdRoute(route, p_url) {

  const { url, moduleName, icon, moduleId, code, hidden, type ,fullUrl } = route;
  var item = {};
  if (url.substr(0, 1) == "/") {
    item.path = url.substr(1);
  } else {
    tem.path = url;
  }
  try {
    if (fullUrl) {
      item.component = _import(`${fullUrl}`);
    }else{
      item.component = _import(`${p_url}${url}`);
    }

  } catch (e) {
    console.log(e);
  }
  item.name = code;

  item.meta = {
    title: moduleName,
    icon: icon,
  };
  if (route.children && type == 2) {
    let roles = [];
    for (var role of route.children) {
      roles.push(role.code);
    }
    item.meta.roles = roles;
  }
  item.hidden = hidden;
  item.children = [];
  return item;
}
