import { PropsWithChildren } from "react";
import Taro, { useLaunch } from "@tarojs/taro";
import dayjs from "dayjs";
import { RouteGuard } from "@/utils";
import "dayjs/locale/zh-cn";
import "./app.css";
import "./iconfont.css";

dayjs.locale("zh-cn");

/**
 * 应用主组件
 * @param {PropsWithChildren<any>} props - 包含子组件的属性
 */
function App({ children }: PropsWithChildren<any>) {
  const processScreenshotNavigation = async (query: any, path?: string) => {
    if (!query) return;
    // 补充path信息到query中（如果需要）
    const enhancedQuery = { ...query };
    if (path && !enhancedQuery.path) {
      enhancedQuery.path = path;
    }

    const redirectResult =
      RouteGuard.shouldRedirectFromScreenshot(enhancedQuery);

    if (redirectResult.shouldRedirect) {
      console.log("路由守卫拦截:", redirectResult.reason);
      const redirected = await RouteGuard.executeRedirect(redirectResult);

      if (redirected) {
        // 可以在这里记录日志或上报统计
        await logRedirectEvent(redirectResult);
      }
    }
  };
  /**
   * 记录重定向事件（可选）
   */
  const logRedirectEvent = async (result: any) => {
    // 可以在这里集成数据统计或日志上报
    console.log("路由重定向事件:", {
      timestamp: Date.now(),
      reason: result.reason,
      redirectTo: result.redirectTo,
    });
  };

  // 应用启动时的初始化操作
  useLaunch(async () => {
    // 小程序环境下的应用更新
    if (process.env.TARO_ENV === "weapp") {
      updateApp();

      const launchOptions = Taro.getLaunchOptionsSync();
      await processScreenshotNavigation(
        launchOptions.query,
        launchOptions.path,
      );
    }

    // H5环境下的特殊处理
    if (process.env.TARO_ENV === "h5") {
      // 移除 class taro-tabbar__tabbar
      const { createRoot } = require("react-dom/client");
      const TabBar = require("@/components/biz/CustomTabBar").default;
      const domNode = document.querySelector(".taro-tabbar__tabbar");
      const root = createRoot(domNode);
      root.render(<TabBar />);

      // 初始化vConsole调试工具
      if (process.env.NODE_ENV === "development") {
        const VConsole = require("vconsole");
        new VConsole();
      }
    }
  });

  /**
   * 更新应用
   */
  const updateApp = () => {
    if (Taro.canIUse("getUpdateManager")) {
      const updateManager = Taro.getUpdateManager();
      // 监听应用更新检查
      updateManager.onCheckForUpdate(() => {
        console.log("checking app update .......");
      });
      // 监听应用更新准备就绪
      updateManager.onUpdateReady(() => {
        // noinspection JSIgnoredPromiseFromCall
        Taro.showModal({
          title: "更新提示",
          content: "新版本已经准备好，是否重启应用？",
          success: function (res) {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          },
        });
      });
      // 监听应用更新失败
      updateManager.onUpdateFailed(() => {
        // noinspection JSIgnoredPromiseFromCall
        Taro.showModal({
          title: "更新提示",
          content: "新版本下载失败，请检查你的微信",
          showCancel: false,
        });
      });
    } else {
      // noinspection JSIgnoredPromiseFromCall
      Taro.showModal({
        title: "微信升级",
        content: "当前微信版本过低，部分功能无法使用，请升级到最新版本",
        showCancel: false,
      });
    }
  };

  // 渲染组件
  return <>{children}</>;
}

export default App;
