import { to as tos } from 'await-to-js';
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import { isPathMatch } from '@/utils/validate';
import { useUserStore } from '@/store/modules/user';
import { ElMessage } from 'element-plus/es';
import { getCurrentSite, SITE_ROUTES } from '@/utils/siteConfig';
import { cartStore } from '@/store/modules/cart';

NProgress.configure({ showSpinner: false });
const whiteList = [
  '/login',
  '/register',
  '/social-callback',
  '/register*',
  '/register/*',
  '/index',
  '/',
  '/indexB',
  '/indexMro',
  '/indexFuli',
  '/reg',
  '/search',
  '/item',
  '/breg',
  '/greg',
  '/diy'
];

const isWhiteList = (path: string) => {
  return whiteList.some((pattern) => isPathMatch(pattern, path));
};

// 获取主站完整 URL（用于跨域跳转）
function getMainSiteUrl(path: string) {
  if (import.meta.env.PROD) {
    return `https://www.xiaoluwebsite.xyz${path}`;
  } else {
    // 本地开发：指向 www.xiaoluwebsite.xyz 加上当前运行的端口
    // 假设你启动 vite 后访问的是 http://www.xiaoluwebsite.xyz
    const devPort = window.location.port || import.meta.env.VITE_APP_PORT;
    return `https://www.xiaoluwebsite.xyz:${devPort}${path}`;
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const site = getCurrentSite();
  const allowedPaths = SITE_ROUTES[site];

  //不需要请求登录信息
  if (isWhiteList(to.path)) {
    next();
    NProgress.done();
  } else {
    const [err] = await tos(useUserStore().getInfo());
    // if (err) {
    if (false) {
      await useUserStore().logout();
      ElMessage.error(err);
      if (import.meta.env.VITE_DOMAIN_NAME == 'true') {
        window.location.href = getMainSiteUrl('/login');
      } else {
        next('/login');
      }
      NProgress.done();
    } else {
      cartStore().onCartCount();
      // 是否开启多域名
      if (import.meta.env.VITE_DOMAIN_NAME == 'true') {
        if (!allowedPaths.includes(to.path)) {
          console.warn(`[${site}] 禁止访问 ${to.path}`);
          window.location.href = getMainSiteUrl('/index');
          NProgress.done();
        } else {
          next();
          NProgress.done();
        }
      } else {
        next();
        NProgress.done();
      }
    }
  }
});

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