// src/utils/routeGuard.ts
import Taro from "@tarojs/taro";
import {
  RedirectResult,
  SCREENSHOT_ALLOWED_ROUTES,
  TABBAR_ROUTES,
} from "@/config/routes";

export class RouteGuard {
  /**
   * 检查是否需要从截屏访问重定向
   */
  static shouldRedirectFromScreenshot(query: any): RedirectResult {
    if (!query || query.from !== "screenshot") {
      return { shouldRedirect: false };
    }

    // 获取当前页面路径
    const currentPath = this.getCurrentPath(query);

    // 如果没有指定路径或路径不在白名单中，需要重定向
    if (!currentPath || !SCREENSHOT_ALLOWED_ROUTES[currentPath]) {
      return {
        shouldRedirect: true,
        redirectTo: "/pages/main/index/index",
        reason: "页面不允许通过截屏直接访问",
      };
    }

    return { shouldRedirect: false };
  }

  /**
   * 获取当前页面路径
   */
  private static getCurrentPath(query: any): string {
    if (query.path) {
      // 从query中获取路径并格式化
      return query.path.replace(/^\//, "");
    }

    // 如果没有path参数，尝试获取当前页面实例
    try {
      const currentPages = Taro.getCurrentPages();
      if (currentPages.length > 0) {
        const currentPage = currentPages[currentPages.length - 1];
        return currentPage.route || "";
      }
    } catch (error) {
      console.warn("获取当前页面路径失败:", error);
    }

    return "";
  }

  /**
   * 执行重定向逻辑
   */
  static async executeRedirect(checkResult: RedirectResult): Promise<boolean> {
    if (!checkResult.shouldRedirect || !checkResult.redirectTo) {
      return false;
    }

    try {
      // 显示加载提示
      Taro.showLoading({
        title: "跳转中...",
        mask: true,
      });

      // 根据路径类型选择跳转方式
      if (TABBAR_ROUTES[checkResult.redirectTo]) {
        setTimeout(() => {
          Taro.switchTab({ url: "/pages/main/index/index" });
        }, 500);
      } else {
        setTimeout(() => {
          Taro.redirectTo({ url: checkResult.redirectTo! });
        }, 500);
      }

      return true;
    } catch (error) {
      console.error("重定向失败:", error);
      // 重定向失败时跳转到首页
      try {
        await Taro.switchTab({ url: "/pages/main/index/index" });
      } catch (fallbackError) {
        console.error("备用重定向也失败:", fallbackError);
      }
      return true;
    } finally {
      Taro.hideLoading();
    }
  }
}
