import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";

import Home from "@/views/index.vue";
import Flow from "@/views/flow/index.vue";
import Login from "@/views/login.vue";

import { getAccessToken } from "@utils/auth";
import { socialLogin } from "@/api/user";
import * as authUtil from "@/utils/auth";
import {
  isRelogin,
  manualLogoutKey,
  reloginCancelKey,
} from "@/config/axios/service";

import { useUserStoreWithOut } from "@/stores/useUserStore";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: {
      title: "DeepOil 智慧经营平台 | 登录",
    },
  },

  {
    path: "/flow",
    name: "Flow",
    component: Flow,
    meta: {
      title: "DeepOil 智慧经营平台 | 流程门户",
    },
  },

  {
    path: "/todo-list",
    name: "TodoList",
    component: () => import("@/views/flow/todoList.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | 待办列表",
    },
  },

  {
    path: "/mobile-todo-list",
    name: "TodoListMobile",
    component: () => import("@/views/flow/todoListMobile.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | 待办列表",
    },
  },

  {
    path: "/oa-done-list",
    name: "OADoneList",
    component: () => import("@/views/flow/oaDoneList.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | 已办列表",
    },
  },

  {
    path: "/crm-todo-list",
    name: "CRMTodoList",
    component: () => import("@/views/flow/crmTodoList.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | CRM待办列表",
    },
  },

  {
    path: "/mobile-crm-todo-list",
    name: "MobileCRMTodoList",
    component: () => import("@/views/flow/crmTodoListMobile.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | CRM待办列表",
    },
  },

  {
    path: "/crm-done-list",
    name: "CRMDoneList",
    component: () => import("@/views/flow/crmDoneList.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | CRM已办列表",
    },
  },

  {
    path: "/srm-todo-list",
    name: "SRMTodoList",
    component: () => import("@/views/flow/srmTodo.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | SRM待办列表",
    },
  },

  {
    path: "/mobile-srm-todo-list",
    name: "MobileSRMTodoList",
    component: () => import("@/views/flow/srmTodoMoblie.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | SRM待办列表",
    },
  },

  {
    path: "/srm-done-list",
    name: "SRMDoneList",
    component: () => import("@/views/flow/srmDone.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | SRM已办列表",
    },
  },

  {
    path: "/drive",
    name: "Drive",
    component: () => import("@/views/drive/index.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | 驾驶舱",
    },
  },

  {
    path: "/news",
    name: "News",
    component: () => import("@/views/news/index.vue"),
    meta: {
      title: "DeepOil 智慧经营平台 | 新闻",
    },
  },

  {
    path: "/notice-redhead",
    name: "NoticeRedhead",
    component: () => import("@/views/notices/index.vue"),
    meta: {
      // 动态设置页面标题
      dynamicTitle: (route) => {
        const { paramsObject } = parseURL(route.fullPath);
        const { title } = paramsObject;
        return title || "新闻";
      },
    },
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savePosition) {
    // 始终滚动到顶部
    return { left: 0, top: 0 };
  },
});

export const resetRouter = (): void => {
  const resetWhiteNameList = ["Redirect", "Login", "NoFind", "Root"];
  router.getRoutes().forEach((route) => {
    const { name } = route;
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
};

const parseURL = (
  url: string | null | undefined,
): { basePath: string; paramsObject: { [key: string]: string } } => {
  // 如果输入为 null 或 undefined，返回空字符串和空对象
  if (url == null) {
    return { basePath: "", paramsObject: {} };
  }

  // 找到问号 (?) 的位置，它之前是基础路径，之后是查询参数
  const questionMarkIndex = url.indexOf("?");
  let basePath = url;
  const paramsObject: { [key: string]: string } = {};

  // 如果找到了问号，说明有查询参数
  if (questionMarkIndex !== -1) {
    // 获取 basePath
    basePath = url.substring(0, questionMarkIndex);

    // 从 URL 中获取查询字符串部分
    const queryString = url.substring(questionMarkIndex + 1);

    // 使用 URLSearchParams 遍历参数
    const searchParams = new URLSearchParams(queryString);
    searchParams.forEach((value, key) => {
      // 封装进 paramsObject 对象
      paramsObject[key] = value;
    });
  }

  // 返回 basePath 和 paramsObject
  return { basePath, paramsObject };
};

const whiteList = ["/", "/login", "/social-login", "/auth-redirect"];
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  const title = to.meta.title as string;
  if (title) {
    document.title = `${title}`;
  }
  if (getAccessToken()) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const userStore = useUserStoreWithOut();

      if (!userStore.getIsSetUser) {
        isRelogin.show = true;
        await userStore.setUserInfoAction();
        isRelogin.show = false;
        const redirectPath = from.query.redirect || to.path;
        // 修复跳转时不带参数的问题
        const redirect = decodeURIComponent(redirectPath as string);
        const { paramsObject: query } = parseURL(redirect);
        const nextData =
          to.path === redirect
            ? { ...to, replace: true }
            : { path: redirect, query };
        next(nextData);
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      const code = to.query.code;
      if (code) {
        const res = await socialLogin(
          "20",
          typeof code === "string" ? code : "",
          "22",
        );

        authUtil.setToken(res);
        sessionStorage.removeItem(manualLogoutKey);
        sessionStorage.removeItem(reloginCancelKey);
        next({ path: "/" });
      } else {
        next(); // 正常导航
      }
      // next();
    } else {
      next(`/login`);
    }
  }
});

export default router;
