import router from "./router";
import useAuths from "@/hooks/useAuths";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import useUserStore from "@/stores/user";

NProgress.configure({ showSpinner: false });
const { getToken, logoutFun ,getRefreshToken} = useAuths();
const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const hasToken = getToken();
  const refreshToken = getRefreshToken();
  if (to.path === "/login" || to.path === "/index") {
    const urlParams = new URLSearchParams(window.location.search);
    const isPopup = window.opener && window.opener !== window;
    const clientId = urlParams.get('client_id');
    const redirectUri = urlParams.get('redirect_uri');
    // ➤ 如果是弹窗+LoginAgain，执行登出再跳转回 login 页面
    if (clientId === 'LoginAgain' && isPopup && hasToken) {
      await logoutFun()
      next({ path: '/login', query: { client_id: 'YiXinAi-Login', redirect_uri: redirectUri } });
      return;
    } else if (isPopup && clientId === 'YiXinAi-Login' && redirectUri) {
      if (hasToken) {
        // 发送消息给父窗口
        const targetOrigin = new URL(decodeURIComponent(redirectUri)).origin;
        window.opener.postMessage({
          type: 'SSO_LOGIN_SUCCESS',
          token: hasToken,
          refreshToken: refreshToken,
        }, targetOrigin);
        // 立即关闭窗口
        setTimeout(() => window.close(), 100);
        return;
      }
    }
  }

  if (hasToken) {
    if (to.path === "/login") {
      // 已经登陆跳转到首页
      next({path: "/"});
      NProgress.done();
    } else {
      if (useUserStore().roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        useUserStore()
            .getInfo()
            .then(() => {
              next({...to, replace: true});
            })
            .catch((err) => {
              logoutFun.then(() => {
                ElMessage.error(err);
                next({path: "/"});
              });
            });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next();
      useUserStore().resetInfo();
      // next(`/login?redirect=${to.path}&unTourist=true`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

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