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 { getAppEnvConfig } from '/@/utils/env';
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';
import SingleSignOn from '/@/utils/singleSignOn';
import eventBus from '/@/utils/eventBus';

const LOGIN_PATH = PageEnum.BASE_LOGIN;
const DEVICE_LIST = PageEnum.DEVICE_LIST;
const ROOT_PATH = RootRoute.path;
const whitePathList: string[] = [LOGIN_PATH, DEVICE_LIST];
let deveProType = false;
if (import.meta.env.MODE === 'development') {
  // 开发环境下的逻辑
  deveProType = false;
} else if (import.meta.env.MODE === 'production') {
  // 生产环境下的逻辑
  deveProType = true;
} else {
  // 其他环境下的逻辑
}
export async function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();
  if (location.href.indexOf('refreshToken') > -1) {
    var token = location.href.split('refreshToken=')[1].replace('#/', '').replace('home', '');
    // sessionStorage.setItem('refreshToken', token);home
    // sessionStorage.setItem('token', token);
    // userStore
    //   .LiGongLogin({
    //     username: 'admin',
    //     password: 'Cdut@123',
    //     breakCaptcha: '1',
    //   })
    //   .then((res) => {
    //     console.log('首次位置:', res);
    //   });
    //修改地址栏链接
    window.history.pushState('', '', location.href.split('?')[0]);
    userStore.setLigongTokenWay(token);
    await userStore.process({ refreshToken: token, token: token }, true);
  }

  const userStore2 = useUserStore();
  if (location.href.indexOf('code') > -1) {
    let code = location.href.split('code=')
    console.log('有response_type后', code[1]);
    var c = code[1].split('&');
    const userInfo = await userStore2.kidlogin({ code: c[0] })
    console.log('传参成功', userInfo);
  }





  router.beforeEach(async (to, from, next) => {
    console.log('to', to);
    console.log('from', from);
    // debugger
    // console.log('Refresh token', sessionStorage.getItem('refreshToken'));
    // console.log('token', sessionStorage.getItem('refreshToken'));
    let userInfo = await getAuthCache(USER_INFO_KEY);
    // if (!userInfo) {
    //   const obj = SingleSignOn();
    //   if (Object.keys(obj).length != 0) {
    //     userStore.singlesignon(obj);
    //   }
    // }
    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; // || JSON.parse(sessionStorage.getItem('refreshToken'));
    // 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 { }
      }
      if (to.path == '/login') sessionStorage.removeItem('refreshToken');
      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,
        };
      }
      if (redirectData.path == '/login') {
        const { VITE_GLOB_ADMIN_LOGIN, VITE_GLOB_IS_IDC } = getAppEnvConfig();
        if (VITE_GLOB_IS_IDC && VITE_GLOB_IS_IDC.length) {
          window.location.href = VITE_GLOB_IS_IDC;
          return;
        } else if (deveProType) {
          window.location.href = VITE_GLOB_ADMIN_LOGIN;
          return;
        }
      }
      next(redirectData);
      return;
    }

    if (from.path === LOGIN_PATH && userInfo?.needSetPwd == false) {
      const getMenuListData = getAuthCache('MENU_LIST') || (await getMenuList());
      const getHomePage = getMenuListData.find((f) => {
        return f.path == '/home';
      });
      if (getHomePage?.path == '/home') {
        setTimeout(() => {
          router.push('/home');
        }, 1);
      } else {
        const routeF = PageEnum.BASE_HOME; //getMenuListData[0]?.children[0]?.path || getMenuListData[0]?.path;
        setTimeout(() => {
          router.push(routeF); //sjl,注销默认跳转
        }, 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);
    }
  });
}
