(function () {
  const NETWORK_EVENT = "__PDD_30D_REFUND_NETWORK__";
  const QUERY_EVENT = "__PDD_30D_REFUND_QUERY__";
  const QUERY_RESULT_EVENT = "__PDD_30D_REFUND_QUERY_RESULT__";
  const FETCH_MARKER = "__PDD_30D_REFUND_FETCH_PATCHED__";
  const XHR_MARKER = "__PDD_30D_REFUND_XHR_PATCHED__";

  function headersToObject(headersLike) {
    const output = {};
    if (!headersLike) {
      return output;
    }

    if (headersLike instanceof Headers) {
      headersLike.forEach((value, key) => {
        output[String(key).toLowerCase()] = value;
      });
      return output;
    }

    if (Array.isArray(headersLike)) {
      headersLike.forEach((entry) => {
        if (Array.isArray(entry) && entry.length >= 2) {
          output[String(entry[0]).toLowerCase()] = String(entry[1]);
        }
      });
      return output;
    }

    if (typeof headersLike === "object") {
      Object.entries(headersLike).forEach(([key, value]) => {
        output[String(key).toLowerCase()] = String(value);
      });
    }
    return output;
  }

  function dispatch(name, detail) {
    try {
      window.dispatchEvent(new CustomEvent(name, { detail }));
    } catch (error) {
      console.warn("[PDD30日退款率] 事件派发失败", error);
    }
  }

  function shouldReadResponse(response) {
    const contentType = response.headers.get("content-type") || "";
    return contentType.includes("json") || contentType.includes("text") || !contentType;
  }

  function installFetchPatch() {
    if (typeof window.fetch !== "function" || window.fetch[FETCH_MARKER]) {
      return;
    }

    const originalFetch = window.fetch;
    const patchedFetch = async function patchedFetch(input, init) {
      const request = input instanceof Request ? input : null;
      const url = request ? request.url : String(input);
      const method = String(
        (init && init.method) || (request && request.method) || "GET"
      ).toUpperCase();

      let requestBody = "";
      try {
        if (init && typeof init.body === "string") {
          requestBody = init.body;
        } else if (request) {
          requestBody = await request.clone().text();
        }
      } catch (error) {
        requestBody = "";
      }

      const requestHeaders = headersToObject(
        (init && init.headers) || (request && request.headers)
      );

      const response = await originalFetch.apply(this, arguments);

      try {
        const clone = response.clone();
        if (shouldReadResponse(clone)) {
          const responseText = await clone.text();
          dispatch(NETWORK_EVENT, {
            transport: "fetch",
            url,
            method,
            status: response.status,
            requestBody,
            requestHeaders,
            responseText
          });
        }
      } catch (error) {
        console.warn("[PDD30日退款率] 读取 fetch 响应失败", error);
      }

      return response;
    };

    patchedFetch[FETCH_MARKER] = true;
    patchedFetch.__pddOriginalFetch = originalFetch;
    window.fetch = patchedFetch;
  }

  function installXhrPatch() {
    if (XMLHttpRequest.prototype.send[XHR_MARKER]) {
      return;
    }

    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;
    const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

    XMLHttpRequest.prototype.open = function patchedOpen(method, url) {
      this.__pdd30dRefundMeta = {
        method: String(method || "GET").toUpperCase(),
        url: String(url || ""),
        requestHeaders: {}
      };
      return originalOpen.apply(this, arguments);
    };

    XMLHttpRequest.prototype.setRequestHeader = function patchedSetRequestHeader(key, value) {
      if (this.__pdd30dRefundMeta) {
        this.__pdd30dRefundMeta.requestHeaders[String(key).toLowerCase()] = String(value);
      }
      return originalSetRequestHeader.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function patchedSend(body) {
      if (this.__pdd30dRefundMeta) {
        this.__pdd30dRefundMeta.requestBody = typeof body === "string" ? body : "";
      }

      this.addEventListener("load", function onLoad() {
        try {
          const responseType = this.responseType || "";
          if (responseType && responseType !== "text") {
            return;
          }

          dispatch(NETWORK_EVENT, {
            transport: "xhr",
            url: this.responseURL || (this.__pdd30dRefundMeta || {}).url || "",
            method: (this.__pdd30dRefundMeta || {}).method || "GET",
            status: this.status,
            requestBody: (this.__pdd30dRefundMeta || {}).requestBody || "",
            requestHeaders: (this.__pdd30dRefundMeta || {}).requestHeaders || {},
            responseText: typeof this.responseText === "string" ? this.responseText : ""
          });
        } catch (error) {
          console.warn("[PDD30日退款率] 读取 XHR 响应失败", error);
        }
      });

      return originalSend.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send[XHR_MARKER] = true;
  }

  async function queryGoodsAfterSales(requestId, goodsId) {
    try {
      const response = await window.fetch("/sydney/api/mallCoreData/queryGoodsAfterSales", {
        method: "POST",
        credentials: "include",
        headers: {
          accept: "application/json, text/plain, */*",
          "content-type": "application/json"
        },
        body: JSON.stringify({ goodsId: Number(goodsId) || String(goodsId) })
      });

      const responseText = await response.text();
      dispatch(QUERY_RESULT_EVENT, {
        requestId,
        goodsId: String(goodsId),
        ok: response.ok,
        status: response.status,
        responseText
      });
    } catch (error) {
      dispatch(QUERY_RESULT_EVENT, {
        requestId,
        goodsId: String(goodsId),
        ok: false,
        status: 0,
        error: error && error.message ? error.message : String(error)
      });
    }
  }

  window.addEventListener(QUERY_EVENT, (event) => {
    const detail = event && event.detail;
    if (!detail || !detail.requestId || !detail.goodsId) {
      return;
    }
    queryGoodsAfterSales(detail.requestId, detail.goodsId);
  });

  installFetchPatch();
  installXhrPatch();

  let reinstallCount = 0;
  const reinstallTimer = window.setInterval(() => {
    reinstallCount += 1;
    installFetchPatch();
    installXhrPatch();
    if (reinstallCount >= 80) {
      window.clearInterval(reinstallTimer);
    }
  }, 250);
})();
