(function () {
  // 从url里面读取参数 type
  const urlParams = new URLSearchParams(window.location.search);
  const type = urlParams.get("type");
  // 如果type为空，则警告lert("请输入type参数")
  if (!type) {
    alert("请输入type参数");
    return;
  }

  let urlMap = {
    tri: ["http://192.168.3.36:9002/", "https://tri.tianyunperfect.cn/"],
  };

  const urls = urlMap[type];

  function checkUrl(url) {
    return new Promise((resolve) => {
      const startTime = performance.now();
      const img = new Image();
      let isResolved = false;

      img.onload = function () {
        if (!isResolved) {
          isResolved = true;
          resolve({
            url: url,
            accessible: true,
            responseTime: performance.now() - startTime,
          });
        }
      };

      img.onerror = function () {
        if (!isResolved) {
          isResolved = true;
          resolve({
            url: url,
            accessible: true,
            responseTime: performance.now() - startTime,
          });
        }
      };

      setTimeout(() => {
        if (!isResolved) {
          isResolved = true;
          resolve({
            url: url,
            accessible: false,
            responseTime: 99999,
          });
        }
      }, 5000);

      const timestamp = new Date().getTime();
      img.src = url + `favicon.ico?t=${timestamp}`;
    });
  }

  function showStatus(message, isError = false) {
    let statusDiv = document.getElementById("url-checker-status");
    if (!statusDiv) {
      statusDiv = document.createElement("div");
      statusDiv.id = "url-checker-status";
      statusDiv.style.cssText = `
                position: fixed;
                top: 10px;
                right: 10px;
                padding: 10px;
                background: ${
                  isError ? "rgba(255, 0, 0, 0.8)" : "rgba(0, 0, 0, 0.8)"
                };
                color: white;
                border-radius: 5px;
                z-index: 999999;
                font-family: Arial, sans-serif;
                font-size: 14px;
                max-width: 300px;
                word-break: break-word;
            `;
      document.body.appendChild(statusDiv);
    }
    statusDiv.textContent = message;
    return statusDiv;
  }

  async function checkAllUrls() {
    const statusDiv = showStatus("正在检测网络连接...");

    try {
      const results = await Promise.all(urls.map((url) => checkUrl(url)));
      const accessibleUrls = results.filter((result) => result.accessible);
      console.log("检测结果:", results);

      if (accessibleUrls.length === 0) {
        showStatus("所有地址均无法访问！", true);
        setTimeout(() => statusDiv.remove(), 3000);
        return;
      }

      const fastestUrl = accessibleUrls.reduce((prev, current) =>
        prev.responseTime < current.responseTime ? prev : current
      );

      showStatus(
        `正在跳转到最快地址: ${fastestUrl.url}\n响应时间: ${Math.round(
          fastestUrl.responseTime
        )}ms`
      );

      setTimeout(() => {
        window.location.href = fastestUrl.url;
        statusDiv.remove();
      }, 1500);
    } catch (error) {
      console.error("检测过程出错:", error);
      showStatus("检测过程出错，请稍后重试", true);
      setTimeout(() => statusDiv.remove(), 3000);
    }
  }

  checkAllUrls();
})();
