var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/piPaymentResult/index.tsx
var piPaymentResult_exports = {};
__export(piPaymentResult_exports, {
  default: () => piPaymentResult_default,
  getPaymentResultFailReason: () => import_result.getPaymentResultFailReason,
  getPaymentResultStatus: () => import_result.getPaymentResultStatus
});
module.exports = __toCommonJS(piPaymentResult_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_usePrefix = __toESM(require("../../hooks/usePrefix"));
var import_locales = __toESM(require("./locales"));
var import_result = require("./result");
var import_serve = require("./serve");
var import_index = require("./index.less");
var PREFIX = "pisell-pi-payment-result";
var GLOBAL_QUERY_TIMEOUT = 60 * 1e3;
var REQUEST_TIMEOUT = 10 * 1e3;
var QUERY_INTERVAL = 2 * 1e3;
var NOT_FOUND_CODE = "4004";
var REQUEST_TIMEOUT_ERROR = "PaymentResultRequestTimeout";
var getResultCodeFromLocation = () => {
  if (typeof window === "undefined") {
    return void 0;
  }
  return new URLSearchParams(window.location.search || "").get("resultCode");
};
var getPaymentResultUrlParams = () => {
  if (typeof window === "undefined") {
    return {};
  }
  const searchParams = new URLSearchParams(window.location.search || "");
  return {
    // resultCode: 支付渠道返回的 resultCode
    resultCode: searchParams.get("resultCode"),
    // paymentNumber: 支付单号
    paymentNumber: searchParams.get("payment_number"),
    // shopId: 店铺 ID
    shopId: searchParams.get("shop_id")
  };
};
var getInitialResultState = (resultCode) => {
  const status = (0, import_result.getPaymentResultStatus)(resultCode);
  if (status === "failed") {
    return {
      status,
      failReason: (0, import_result.getPaymentResultFailReason)(resultCode) || "failed"
    };
  }
  return { status };
};
var getIconFileName = (status) => {
  if (status === "success") return "success.png";
  if (status === "failed") return "error.png";
  return "loading.png";
};
var getLocaleKey = (status, type, failReason) => {
  if (status === "failed" && failReason && failReason !== "failed") {
    return `pi-payment-result.failed.${failReason}.${type}`;
  }
  return `pi-payment-result.${status}.${type}`;
};
var isRequestTimeoutError = (error) => {
  return error instanceof Error && error.message === REQUEST_TIMEOUT_ERROR;
};
var getErrorCode = (error) => {
  if (typeof error === "object" && error !== null && "code" in error) {
    return `${error.code || ""}`;
  }
  return "";
};
var PiPaymentResultIcon = ({
  status
}) => {
  const prefix = (0, import_usePrefix.default)();
  const iconFileName = getIconFileName(status);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      "aria-label": import_utils.locales.getText(`pi-payment-result.${status}.title`),
      className: `${PREFIX}__icon ${PREFIX}__icon--${status}`,
      role: "img",
      style: { backgroundImage: `url(${prefix}/${iconFileName})` }
    }
  );
};
var PiPaymentResult = (0, import_react.memo)(({ className, style }) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  import_utils.locales.init(import_locales.default, ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en");
  const urlParams = (0, import_react.useMemo)(getPaymentResultUrlParams, []);
  const [resultState, setResultState] = (0, import_react.useState)(
    () => getInitialResultState(urlParams.resultCode || getResultCodeFromLocation())
  );
  const rootClassName = className ? `${PREFIX} ${className}` : PREFIX;
  const titleKey = getLocaleKey(
    resultState.status,
    "title",
    resultState.failReason
  );
  const descriptionKey = getLocaleKey(
    resultState.status,
    "description",
    resultState.failReason
  );
  (0, import_react.useEffect)(() => {
    if (resultState.status !== "querying") {
      return;
    }
    if (!urlParams.paymentNumber || !urlParams.shopId) {
      setResultState({ status: "failed", failReason: "invalidParams" });
      return;
    }
    let stopped = false;
    let queryIntervalTimer = null;
    let globalTimeoutTimer = null;
    let requestTimeoutTimer = null;
    const clearTimers = () => {
      if (queryIntervalTimer) {
        clearTimeout(queryIntervalTimer);
        queryIntervalTimer = null;
      }
      if (globalTimeoutTimer) {
        clearTimeout(globalTimeoutTimer);
        globalTimeoutTimer = null;
      }
      if (requestTimeoutTimer) {
        clearTimeout(requestTimeoutTimer);
        requestTimeoutTimer = null;
      }
    };
    const finish = (nextState) => {
      if (stopped) return;
      stopped = true;
      clearTimers();
      setResultState(nextState);
    };
    const poll = async () => {
      var _a2;
      if (stopped) return;
      try {
        const response = await Promise.race([
          (0, import_serve.getPaymentTransactionResult)({
            shop_id: urlParams.shopId,
            number: urlParams.paymentNumber
          }),
          new Promise((_, reject) => {
            requestTimeoutTimer = setTimeout(() => {
              reject(new Error(REQUEST_TIMEOUT_ERROR));
            }, REQUEST_TIMEOUT);
          })
        ]);
        if (requestTimeoutTimer) {
          clearTimeout(requestTimeoutTimer);
          requestTimeoutTimer = null;
        }
        if (stopped) return;
        if (`${(response == null ? void 0 : response.code) || ""}` === NOT_FOUND_CODE) {
          finish({ status: "failed", failReason: "notFound" });
          return;
        }
        const paymentStatus = (_a2 = response == null ? void 0 : response.data) == null ? void 0 : _a2.status;
        if (paymentStatus === "succeed") {
          finish({ status: "success" });
          return;
        }
        if (paymentStatus === "failed") {
          finish({ status: "failed", failReason: "failed" });
          return;
        }
        if (paymentStatus === "pending" || paymentStatus === "processing") {
          queryIntervalTimer = setTimeout(poll, QUERY_INTERVAL);
          return;
        }
        finish({ status: "failed", failReason: "failed" });
      } catch (error) {
        if (requestTimeoutTimer) {
          clearTimeout(requestTimeoutTimer);
          requestTimeoutTimer = null;
        }
        if (stopped) return;
        if (isRequestTimeoutError(error)) {
          finish({ status: "failed", failReason: "timeout" });
          return;
        }
        if (getErrorCode(error) === NOT_FOUND_CODE) {
          finish({ status: "failed", failReason: "notFound" });
          return;
        }
        finish({ status: "failed", failReason: "failed" });
      }
    };
    globalTimeoutTimer = setTimeout(() => {
      finish({ status: "failed", failReason: "timeout" });
    }, GLOBAL_QUERY_TIMEOUT);
    poll();
    return () => {
      stopped = true;
      clearTimers();
    };
  }, [resultState.status, urlParams.paymentNumber, urlParams.shopId]);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: rootClassName, style }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__card` }, /* @__PURE__ */ import_react.default.createElement(PiPaymentResultIcon, { status: resultState.status }), /* @__PURE__ */ import_react.default.createElement("h1", { className: `${PREFIX}__title` }, import_utils.locales.getText(titleKey)), /* @__PURE__ */ import_react.default.createElement("p", { className: `${PREFIX}__description` }, import_utils.locales.getText(descriptionKey))));
});
var piPaymentResult_default = PiPaymentResult;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getPaymentResultFailReason,
  getPaymentResultStatus
});
