import router from "./router";
import store from "./store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { setTenantId, setToken } from "@/utils/auth";
import { Message, MessageBox } from "element-ui";
import { getPath } from "@/utils/ruoyi";
import { getItem, removeItem } from "@/utils/cookie";
import { isRelogin } from "@/utils/request";

NProgress.configure({ showSpinner: false });

// 增加三方登陆 update by 芋艿
const whiteList = [
  "/login",
  "/social-login",
  "/auth-redirect",
  "/bind",
  "/register",
  "/oauthLogin/gitee",
];

function routerAction(to, from, next) {
  // 解决多级路由无法缓存
  if (to.matched && to.matched.length > 2) {
    to.matched.splice(1, to.matched.length - 2);
  }
  to.meta.title && store.dispatch("settings/setTitle", to.meta.title);
  /* has token*/
  if (to.path === "/login") {
    next({ path: "/" });
    NProgress.done();
  } else {
    if (store.getters.roles.length === 0) {
      isRelogin.show = true;
      // 获取字典数据 add by 芋艿
      store.dispatch("dict/loadDictDatas");
      // 判断当前用户是否已拉取完user_info信息
      store
        .dispatch("GetInfo")
        .then(() => {
          isRelogin.show = false;
          store.dispatch("GenerateRoutes").then((accessRoutes) => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes); // 动态添加可访问路由表
            next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
          });
        })
        .catch((err) => {
          store.dispatch("LogOut").then(() => {
            Message.error(err);
            next({ path: "/" });
          });
        });
    } else {
      if (!!to.meta.queryManageId) {
        const { queryManageId, ...metaWithoutQueryId } = to.meta;
        // 构建查询参数，包含id和name
        const queryParams = {
          id: queryManageId,
          name: to.meta.title, // 使用原路由的标题作为name参数
        };
        const targetPath = `/querymanage/queryFormNew`;

        // 防止死循环：如果当前路径已经是目标路径，就不再跳转
        if (to.path === targetPath) {
          next();
          return;
        }

        // 在重定向前结束当前的NProgress
        NProgress.done();
        next({
          path: targetPath,
          query: queryParams,
          meta: metaWithoutQueryId,
          replace: true, // 使用 replace 避免历史栈堆积
        });
        return; // 必须 return，防止继续执行后面的 next()
      } else {
        next();
      }
    }
  }
}

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getItem("accessToken") && getItem("refreshToken")) {
    setToken({
      accessToken: getItem("accessToken"),
      refreshToken: getItem("refreshToken"),
    });
    setTenantId(getItem("tenantId"));
    routerAction(to, from, next);
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (
        window.location.hostname === "113.105.183.190" &&
        process.env.VUE_APP_TITLE === "麦禾田WMS管理系统"
      ) {
        window.location.href =
          "http://113.105.183.190:8263/login?redirect=%2Findex";
      }
      if (
        window.location.hostname === "113.105.183.190" &&
        process.env.VUE_APP_TITLE === "东苏发WMS管理系统"
      ) {
        window.location.href =
          "http://113.105.183.190:8263/login?redirect=%2Findex";
      }
      if (
        window.location.hostname === "113.105.183.190" &&
        process.env.VUE_APP_TITLE === "东旭达WMS管理系统"
      ) {
        window.location.href =
          "http://113.105.183.190:8267/login?redirect=%2Findex";
      }
      switch (window.location.hostname) {
        case "192.168.1.163":
          window.location.href =
            "http://192.168.1.163:8282/login?redirect=%2Findex";
          break;
        // case '218.2.10.30':
        default:
          // location.href = "http://localhost:81/login?redirect=%2Findex";
          MessageBox.confirm(
            "登录状态已过期，您可以继续留在该页面，或者重新登录",
            "系统提示",
            {
              confirmButtonText: "重新登录",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            // 清除localStorage存储
            localStorage.clear();
            // 清除cookie，防止接口卡死
            removeItem("tenantId");
            removeItem("accessToken");
            removeItem("refreshToken");
            next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
            // store.dispatch('LogOut').then(() => {
            //   // 源代码
            //   location.href = getPath('/login');
            // })
          });
          break;
      }
      // next(`/login?redirect=${encodeURIComponent(to.fullPath)}`); // 否则全部重定向到登录页 encodeURIComponent对fullpath做转码处理，解决缺少参数
      // NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
