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, onPath } from '@/utils/siteConfig';
import { cartStore } from '@/store/modules/cart';
import { stationStore } from '@/store/modules/station';
import Cookies from 'js-cookie';

NProgress.configure({ showSpinner: false });

const whiteList = [
  '/login',
  '/register',
  '/social-callback',
  '/register*',
  '/register/*',
  '/index',
  '/',
  '/indexB',
  '/indexMro',
  '/indexFuli',
  '/reg',
  '/search',
  '/item',
  '/breg',
  '/greg',
  '/diy',
  '/theme'
];

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

function getMainSiteUrl(path: string) {
  if (import.meta.env.PROD) {
    return `https://index.xiaoluwebsite.xyz${path}`;
  } else {
    const devPort = window.location.port || import.meta.env.VITE_APP_PORT;
    return `https://index.xiaoluwebsite.xyz:${devPort}${path}`;
  }
}

// 根据 isDiy 字段决定首页路径
function getDomainHomePath(site: string, station: ReturnType<typeof stationStore>) {
  const allowedPaths = SITE_ROUTES[site] || [];
  const hasIndexData = allowedPaths.includes('/indexData');
  const hasDiy = allowedPaths.includes('/diy');
  const hasIndex = allowedPaths.includes('/index');

  if (station.stationData && Object.keys(station.stationData).length > 0) {
    // 兼容：stationData.data.isDiy 或 stationData.isDiy
    const data = station.stationData.data || station.stationData;
    const isDiy = data?.isDiy;

    if (isDiy === 0 || isDiy === '0') {
      if (hasIndexData) {
        return '/indexData';
      }
    } else if (isDiy !== undefined && isDiy !== null) {
      if (hasDiy) {
        return '/diy';
      }
    }
  }

  if (hasIndex) {
    return '/index';
  }

  return allowedPaths[0] || '/';
}

// 统一跳转处理
function doRedirect(path: string, next: any, isMultiDomain: boolean) {
  if (isMultiDomain) {
    onPath(path);
    next(false);
  } else {
    next(path);
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const site = getCurrentSite();
  const allowedPaths = SITE_ROUTES[site];
  const token = Cookies.get('Authorization');
  const isMultiDomain = import.meta.env.VITE_DOMAIN_NAME == 'true';
  const station = stationStore();
  const cart = cartStore();
  const userStore = useUserStore();

  // 需求一：判断是否需要调用 getInfo（有 token 或 不在白名单）
  const needGetInfo = token || !isWhiteList(to.path);

  if (needGetInfo) {
    const [err] = await tos(userStore.getInfo());

    // 需求五：getInfo 失败跳转/login
    if (err) {
      await userStore.logout();
      ElMessage.error(err);
      doRedirect('/login', next, isMultiDomain);
      NProgress.done();
      return;
    }

    // 修复：有 token 时才请求购物车和站点数据
    if (token) {
      try {
        // 获取购物车数量
        cart.onCartCount();
        // 获取站点数据
        await station.onstation();
      } catch (error) {
        console.error('获取站点数据失败:', error);
      }
    }
  }

  // 需求四：多域名下检查路径权限
  if (isMultiDomain) {
    const homePaths = ['/', '/index', '/indexData', '/diy'];
    if (homePaths.includes(to.path)) {
      const homePath = getDomainHomePath(site, station);
      if (to.path !== homePath) {
        doRedirect(homePath, next, isMultiDomain);
        NProgress.done();
        return;
      }
    }

    if (!allowedPaths.includes(to.path)) {
      console.warn(`[${site}] 禁止访问 ${to.path}`);
      const homePath = getDomainHomePath(site, station);
      doRedirect(homePath, next, isMultiDomain);
      NProgress.done();
      return;
    }
  } else {
    // 单域名下首页处理
    const homePaths = ['/', '/index', '/indexData', '/diy'];
    if (homePaths.includes(to.path)) {
      const homePath = getDomainHomePath(site, station);
      if (to.path !== homePath) {
        doRedirect(homePath, next, isMultiDomain);
        NProgress.done();
        return;
      }
    }
  }

  // 需求三 & 需求六：正常放行
  next();
  NProgress.done();
});

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