import { createApp } from "vue";
import Antd, { message } from "ant-design-vue";

import {
  createMemoryHistory,
  createRouter,
  createWebHistory,
} from "vue-router";

import routes from "./router";

import App from "./App.vue";

import AgGridVue from "EFX/AgGridVue";

import { Pane, Splitpanes } from "splitpanes";

import { init, IAxiosInitConfig, isXinPlatWorkspace } from "EIX/ei";
import { initInstrumentation } from "./instrumentation";
import { type PrepareContext } from "./prepare";
import {
  evictCachedOnLeave,
  cancelPendingEvict,
  refreshCached,
} from "./sharedTabCache";

export async function bootstrap(
  baseURL: string,
  preparePromise: Promise<PrepareContext>,
  appBase: string,
  routerHistory?: string,
) {
  // const { vueI18n } = await prepare();
  const { vueI18n } = await preparePromise;

  const app = createApp(App);

  const historyBase = import.meta.env.PROD
    ? `${baseURL}${appBase}/${import.meta.env.VITE_APP_NAME}/`
    : "";

  const history =
    routerHistory === "memory"
      ? createMemoryHistory(historyBase)
      : createWebHistory(historyBase);

  const router = createRouter({
    history,
    routes,
  });
  // if(import.meta.env.DEV) {
  router.beforeEach((to, from) => {
    console.debug(`[router] ${from.fullPath} -> ${to.fullPath}`);
  });
  // }
  app.use(router);

  app.use(vueI18n);

  app.use(Antd);

  app.component("ag-grid-vue", AgGridVue);

  app.component("v-splitter", Splitpanes);

  app.component("v-splitter-pane", Pane);

  const eiInitOptions: IAxiosInitConfig = {
    baseURL,
    powerByQianKun: window.__POWERED_BY_WUJIE__ ?? false,
    currentRouter: router,
    platType: import.meta.env.VITE_APP_PLAT_TYPE,
    messageService: message,
    jServerContext: import.meta.env.VITE_APP_SERVER_CONTEXT,
  };

  if (import.meta.env.DEV) {
    (eiInitOptions as any).useLocalServer =
      import.meta.env.VITE_APP_USE_LOCAL_SERVER === "true";
    (eiInitOptions as any).useGatewayProxy =
      import.meta.env.VITE_APP_USE_GATEWAY_PROXY === "true";
  }

  init(eiInitOptions);

  app.mount("#sub-app");

  // 单容器多 tab(实验):宿主切换同 dll 的 tab 时,经 wujie bus 驱动内部路由(沙箱常驻)
  if (window.__POWERED_BY_WUJIE__ && (window as any).$wujie?.bus) {
    const dllName = import.meta.env.VITE_APP_NAME;
    // 诊断探针
    (window as any).__XR_ROUTER__ = router;
    (window as any).$wujie.bus.$on(
      `xr-shared-route:${dllName}`,
      (path: string) => {
        console.info(`[xr-shared] 收到路由事件: ${path}`);
        // 路由重新落在该路径 = 画面被重新打开,取消之前关闭时挂起的延迟逐出
        cancelPendingEvict(path);
        const wujie = (window as any).$wujie;
        // 同步 wujie props.formName:xrEfForm 取画面名时 props.formName 优先级最高,
        // 而共享沙箱下 props 冻结在首个 tab——不更新则新挂载实例永远拿到旧参数。
        // 画面名有两种来源:参数画面在 query(baseFormName?formName=X),
        // 普通画面(FORM_CALL_MODE=0)就是路径最后一段(如 /EPESRG),两种都要覆盖,
        // 否则同模块第二个普通画面会沿用首个画面的名字(授权校验 checkdll 传错)
        try {
          const [pathname, search = ""] = path.split("?");
          const formName =
            new URLSearchParams(search).get("formName") ||
            pathname.split("/").filter(Boolean).pop();
          if (formName) {
            wujie.props = wujie.props ?? {};
            wujie.props.formName = formName;
          }
        } catch {
          /* path 异常时忽略 */
        }
        if (path && router.currentRoute.value.fullPath !== path) {
          router
            .push(path)
            .catch((e) => console.warn(`[xr-shared] 路由跳转失败: ${path}`, e));
        }
      },
    );
    // 宿主关闭 tab:按 fullPath 精确逐出该画面的 KeepAlive 缓存(同路由其他参数 tab 不受影响)
    // 被关画面是当前路由画面时,等路由真正离开后再逐出,避免 include 变化触发
    // router-view 重渲染、以新 key 重建缓存导致画面"复活"
    (window as any).$wujie.bus.$on(
      `xr-shared-close:${dllName}`,
      (path: string) => {
        if (path) evictCachedOnLeave(path, router);
      },
    );
    // 宿主刷新 tab:内层组件按刷新计数重建,状态归零,不影响同 dll 其他画面
    (window as any).$wujie.bus.$on(
      `xr-shared-refresh:${dllName}`,
      (path: string) => {
        if (path) refreshCached(path);
      },
    );
  }

  // 3. 初始化链路追踪
  try {
    if (isXinPlatWorkspace() && !window.__OTEL_PROVIDER__) {
      const provider = await initInstrumentation();

      if (provider) {
        window.__OTEL_PROVIDER__ = provider;
      }
    }
  } catch (err) {
    console.error("[OTel] init failed", err);
  }

  // await initDevAuth(router);

  return {
    app,

    router,

    history,
  };
}
