import { InAppBrowser, DefaultWebViewOptions } from "@capacitor/inappbrowser";
import { Browser } from "@capacitor/browser";
import { openGaoDe } from "./appLauncher";

export const openDapp = async (url, params, open = false) => {
  // 将对象参数转换为 URL 查询字符串
  const queryString = new URLSearchParams(params).toString();
  const fullUrl = queryString?`${url}?${queryString}`:url;

  // 判断是web 还是 ios
  if (Capacitor.getPlatform() === "web") {
    window.open(fullUrl, "_blank");
    return;
  }

  if(open){
    await Browser.open({ url: fullUrl });
    return
  }

  // dappView
  await InAppBrowser.addListener(
    "browserPageNavigationCompleted",
    async (data) => {
      if (data.url.indexOf("go=gaode") > -1) {
        const params = new URLSearchParams(data.url);
        const lat = params.get("latitude");
        const lan = params.get("longitude");
        const address = params.get("address");
        await openGaoDe(lat, lan, address);
      }
    }
  );

  await InAppBrowser.addListener("browserClosed", async () => {
    InAppBrowser.removeAllListeners;
  });

  await InAppBrowser.addListener(
    "browserPageNavigationCompleted",
    async (data) => {
      if (data.url.indexOf("go=gaode") > -1) {
        const params = new URLSearchParams(data.url);
        const lat = params.get("latitude");
        const lan = params.get("longitude");
        const address = params.get("address");
        await openGaoDe(lat, lan, address);
      }
    }
  ); 
  await InAppBrowser.openInWebView({
    url: fullUrl,
    options: {
      ...DefaultWebViewOptions,
      showURL: false,
      showToolbar: false,
      androidMixedContentMode: "always_allow", // Android
      iosAllowsInsecureHTTPLoads: true, // iOS (部分版本支持)
      iosDisallowOverScroll: false
    },
  });
};
