import type { Router, RouteRecordRaw } from 'vue-router';
import { usePermissionStoreWithOut } from '/@/store/modules/permission';
import { PageEnum } from '/@/enums/pageEnum';
import { useUserStoreWithOut, useUserStore } from '/@/store/modules/user';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { RootRoute } from '/@/router/routes';
import { getMenuList } from '/@/api/sys/menu';
import { USER_INFO_KEY } from '/@/enums/cacheEnum';
import { getAuthCache } from '/@/utils/auth';

const LOGIN_PATH = PageEnum.BASE_LOGIN;
const DEVICE_LIST = PageEnum.DEVICE_LIST;
const ROOT_PATH = RootRoute.path;
const whitePathList: string[] = [LOGIN_PATH, DEVICE_LIST];

export async function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut();
  const userStore2 = useUserStore();
  const permissionStore = usePermissionStoreWithOut();
  if (location.href.indexOf('code') > -1) {
    let code = location.href.split('code=')
    console.log('有response_type后', code[1]);
    const userInfo = await userStore2.kidlogin({ code: code[1] })
    console.log('传参成功', userInfo);
  }
  router.beforeEach(async (to, from, next) => {
    const userInfo = await getAuthCache(USER_INFO_KEY);
    if (
      from.path === ROOT_PATH &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      next(userStore.getUserInfo.homePath);
      return;
    }

    const token = userStore.jwtToken;
    // Whitelist can be directly entered
    // 路由守卫拦截, 如果是已经登陆情况, 就不要回到登陆页面了;
    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && token) {
        const isSessionTimeout = userStore.getSessionTimeout;
        try {
          // await userStore.afterLoginAction();
          if (!isSessionTimeout) {
            next((to.query?.redirect as string) || '/');
            return;
          }
        } catch {}
      }
      next();
      return;
    }

    // token does not exist
    if (!token) {
      // You can access without permission. You need to set the routing meta.ignoreAuth to true
      if (to.meta.ignoreAuth) {
        next();
        return;
      }

      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      console.log('redirectData', redirectData);

      next(redirectData);
      return;
    }

    if (from.path === LOGIN_PATH && userInfo?.needSetPwd == false) {
      const getMenuListData = getAuthCache('MENU_LIST') || (await getMenuList());
      if (getMenuListData) {
        const getHomePage = getMenuListData.find((f) => {
          return f.path == '/dashboard/workbench';
        });
        if (getHomePage?.path == '/dashboard/workbench') {
          setTimeout(() => {
            console.log('路由:', getHomePage);
            router.push('/dashboard/workbench');
          }, 1);
        } else {
          const routeF = PageEnum.BASE_HOME_NAV; //PageEnum.BASE_HOME; //getMenuListData[0]?.children[0]?.path || getMenuListData[0]?.path;
          console.log('路由:', routeF);
          setTimeout(() => {
            router.push(routeF);
          }, 1);
        }
      }
    }

    if (from.path === LOGIN_PATH && userInfo?.needSetPwd == true) {
      setTimeout(() => {
        router.push('/system/changePassword');
      }, 1);
    }

    if (
      from.path === LOGIN_PATH &&
      to.name === PAGE_NOT_FOUND_ROUTE.name &&
      to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
    ) {
      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
      return;
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      next();
      return;
    }

    const routes = await permissionStore.buildRoutesAction();

    routes?.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw);
    });

    router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);

    permissionStore.setDynamicAddedRoute(true);
    console.log(to.query);

    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query });
    } else {
      const redirectPath = (from.query.redirect || to.path) as string;
      const redirect = decodeURIComponent(redirectPath);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      next(nextData);
    }
  });
}
