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/components/eftposPay/payo/payment.ts
var payment_exports = {};
__export(payment_exports, {
  ActionType: () => ActionType,
  usePayment: () => usePayment
});
module.exports = __toCommonJS(payment_exports);
var import_react = require("react");
var import_const = require("../const");
var import_payLog = __toESM(require("../utils/payLog"));
var QUERY_START_DELAY = 1e3 * 10;
var GLOBAL_TIMEOUT = 1e3 * 60 * 2;
var REQUEST_TIMEOUT = 1e3 * 10;
var QUERY_INTERVAL = 1e3 * 2;
var ActionType = /* @__PURE__ */ ((ActionType2) => {
  ActionType2["Pay"] = "pay";
  ActionType2["Refund"] = "refund";
  ActionType2["Query"] = "query";
  return ActionType2;
})(ActionType || {});
var isRequestFailed = (code) => {
  return code && `${code}` !== import_const.PayStatus.Timeout && `${code}` !== import_const.PayStatus.PayTimeout;
};
var usePayment = (options) => {
  const { payApi, refundApi, checkApi, shouldContinue = () => true } = options;
  const payControllerRef = (0, import_react.useRef)(null);
  const queryControllerRef = (0, import_react.useRef)(null);
  const queryStartTimerRef = (0, import_react.useRef)(null);
  const globalTimeoutTimerRef = (0, import_react.useRef)(
    null
  );
  const requestTimeoutTimerRef = (0, import_react.useRef)(
    null
  );
  const queryIntervalTimerRef = (0, import_react.useRef)(
    null
  );
  const isFinishedRef = (0, import_react.useRef)(false);
  const isQueryingRef = (0, import_react.useRef)(false);
  const callbacksRef = (0, import_react.useRef)(null);
  const isRequestTimeoutRef = (0, import_react.useRef)(false);
  const currentQueryIdRef = (0, import_react.useRef)(0);
  const currentRunIdRef = (0, import_react.useRef)(0);
  const clean = (params) => {
    const { clearCallbacks = true } = params || {};
    console.log("🧹 清理所有资源", { clearCallbacks });
    if (payControllerRef.current) {
      payControllerRef.current.abort();
      payControllerRef.current = null;
    }
    if (queryControllerRef.current) {
      queryControllerRef.current.abort();
      queryControllerRef.current = null;
    }
    if (queryStartTimerRef.current) {
      clearTimeout(queryStartTimerRef.current);
      queryStartTimerRef.current = null;
    }
    if (globalTimeoutTimerRef.current) {
      clearTimeout(globalTimeoutTimerRef.current);
      globalTimeoutTimerRef.current = null;
    }
    if (requestTimeoutTimerRef.current) {
      clearTimeout(requestTimeoutTimerRef.current);
      requestTimeoutTimerRef.current = null;
    }
    if (queryIntervalTimerRef.current) {
      clearTimeout(queryIntervalTimerRef.current);
      queryIntervalTimerRef.current = null;
    }
    isQueryingRef.current = false;
    isFinishedRef.current = false;
    isRequestTimeoutRef.current = false;
    if (clearCallbacks !== false) {
      callbacksRef.current = null;
    }
  };
  const finish = () => {
    if (!isFinishedRef.current) {
      clean();
      isFinishedRef.current = true;
    }
  };
  const handleFinalSuccess = (res, type) => {
    var _a, _b;
    if (isFinishedRef.current || !shouldContinue()) {
      import_payLog.default.log(`handleFinalSuccess: 已完成或不应继续处理，忽略${type}操作成功结果`);
      return;
    }
    import_payLog.default.log("接口最终结果：支付成功", { type, res });
    (_b = (_a = callbacksRef.current) == null ? void 0 : _a.onSuccess) == null ? void 0 : _b.call(_a, res);
    finish();
  };
  const handleFinalError = (error, type) => {
    var _a, _b;
    if (isFinishedRef.current || !shouldContinue()) {
      import_payLog.default.log(`handleFinalError: 已完成或不应继续处理，忽略${type}操作错误`);
      return;
    }
    import_payLog.default.log("接口最终结果：支付失败", { type, error });
    (_b = (_a = callbacksRef.current) == null ? void 0 : _a.onError) == null ? void 0 : _b.call(_a, error);
    finish();
  };
  const createTimeoutPromise = (timeoutMs) => {
    return new Promise((_, reject) => {
      requestTimeoutTimerRef.current = setTimeout(() => {
        import_payLog.default.log(`⏱️ 单次查询超时（${timeoutMs / 1e3}秒），强制终止`);
        isRequestTimeoutRef.current = true;
        if (queryControllerRef.current) {
          queryControllerRef.current.abort();
        }
        reject(new Error("REQUEST_TIMEOUT"));
      }, timeoutMs);
    });
  };
  const performQuery = async (paymentNum) => {
    if (isFinishedRef.current || !shouldContinue()) {
      import_payLog.default.log("支付轮询前置校验：已完成或不应继续，取消查询");
      return;
    }
    if (queryControllerRef.current) {
      queryControllerRef.current.abort();
      queryControllerRef.current = null;
    }
    if (requestTimeoutTimerRef.current) {
      clearTimeout(requestTimeoutTimerRef.current);
      requestTimeoutTimerRef.current = null;
    }
    const queryId = Date.now();
    currentQueryIdRef.current = queryId;
    isRequestTimeoutRef.current = false;
    queryControllerRef.current = new AbortController();
    const { signal } = queryControllerRef.current;
    try {
      import_payLog.default.log("支付轮询：开始单次查询");
      const res = await Promise.race([
        checkApi({ number: paymentNum }, { signal }),
        createTimeoutPromise(REQUEST_TIMEOUT)
      ]);
      if (requestTimeoutTimerRef.current) {
        clearTimeout(requestTimeoutTimerRef.current);
        requestTimeoutTimerRef.current = null;
      }
      if (queryId < currentQueryIdRef.current) {
        import_payLog.default.log("支付轮询结果：过期的查询响应，忽略");
        return;
      }
      if (isFinishedRef.current || !shouldContinue()) {
        import_payLog.default.log("支付轮询结果：已完成或不应继续处理");
        return;
      }
      if (res && `${res.code}` === "200") {
        import_payLog.default.log("支付轮询结果：支付成功");
        handleFinalSuccess(res, "query" /* Query */);
        return;
      }
      if (isRequestFailed(res == null ? void 0 : res.code)) {
        import_payLog.default.log("支付轮询结果：有明确错误code，停止轮询", { code: res == null ? void 0 : res.code });
        handleFinalError(res, "query" /* Query */);
      } else {
        import_payLog.default.log("支付轮询结果：无明确code，继续轮询", { code: res == null ? void 0 : res.code });
        scheduleNextQuery(paymentNum);
      }
    } catch (error) {
      if (requestTimeoutTimerRef.current) {
        clearTimeout(requestTimeoutTimerRef.current);
        requestTimeoutTimerRef.current = null;
      }
      if (queryId < currentQueryIdRef.current) {
        import_payLog.default.log("支付轮询结果：error-过期的查询异常，忽略");
        return;
      }
      if (isFinishedRef.current || !shouldContinue()) {
        return;
      }
      if (isRequestTimeoutRef.current || (error == null ? void 0 : error.name) === "AbortError" || (error == null ? void 0 : error.message) === "REQUEST_TIMEOUT") {
        import_payLog.default.log("支付轮询结果：error-请求被取消或超时，继续轮询");
        scheduleNextQuery(paymentNum);
        return;
      }
      if (isRequestFailed(error == null ? void 0 : error.code)) {
        import_payLog.default.log("支付轮询结果：error-有明确错误code，停止轮询", { code: error == null ? void 0 : error.code });
        handleFinalError(error, "query" /* Query */);
      } else {
        import_payLog.default.log("支付轮询结果：error-无明确code，继续轮询", { code: error == null ? void 0 : error.code });
        scheduleNextQuery(paymentNum);
      }
    }
  };
  const scheduleNextQuery = (paymentNum) => {
    if (isFinishedRef.current || !shouldContinue()) {
      return;
    }
    if (queryIntervalTimerRef.current) {
      clearTimeout(queryIntervalTimerRef.current);
    }
    queryIntervalTimerRef.current = setTimeout(() => {
      import_payLog.default.log("支付轮询：安排下一次查询");
      performQuery(paymentNum);
    }, QUERY_INTERVAL);
  };
  const startQuery = (paymentNum) => {
    if (isFinishedRef.current || !shouldContinue() || isQueryingRef.current) {
      return;
    }
    isQueryingRef.current = true;
    globalTimeoutTimerRef.current = setTimeout(() => {
      if (isFinishedRef.current) {
        return;
      }
      console.log("⏱️ 轮询全局超时（2分钟），终止所有请求");
      import_payLog.default.log("轮询全局超时（2分钟），终止所有请求");
      handleFinalError(
        { code: import_const.PayStatus.Timeout, message: "交易超时" },
        "query" /* Query */
      );
    }, GLOBAL_TIMEOUT);
    performQuery(paymentNum);
  };
  const run = async (options2) => {
    const {
      paymentType = "pay" /* Pay */,
      params,
      paymentNum,
      callbacks
    } = options2;
    const runId = Date.now();
    currentRunIdRef.current = runId;
    const { pay_param_base64, ...otherParams } = params || {};
    isFinishedRef.current = true;
    clean({ clearCallbacks: false });
    callbacksRef.current = callbacks;
    queryStartTimerRef.current = setTimeout(() => {
      import_payLog.default.log("支付后10秒开始轮询");
      startQuery(paymentNum);
    }, QUERY_START_DELAY);
    payControllerRef.current = new AbortController();
    const { signal } = payControllerRef.current;
    try {
      import_payLog.default.log("发起支付请求");
      const resultPromise = paymentType === "pay" /* Pay */ ? payApi : refundApi;
      if (!resultPromise) {
        throw new Error(
          `${paymentType === "pay" /* Pay */ ? "支付" : "退款"}接口不存在`
        );
      }
      const res = await (resultPromise == null ? void 0 : resultPromise(params, { signal }));
      if (runId < currentRunIdRef.current) {
        import_payLog.default.log("支付响应过期，忽略");
        return;
      }
      if (isFinishedRef.current || !shouldContinue()) {
        import_payLog.default.log("支付返回时已完成或不应继续处理");
        return;
      }
      if (res && `${res.code}` === "200") {
        import_payLog.default.log("支付接口成功");
        handleFinalSuccess(res, paymentType);
        return;
      }
      if (isRequestFailed(res == null ? void 0 : res.code)) {
        import_payLog.default.log("支付接口返回失败", { code: res == null ? void 0 : res.code });
        handleFinalError(res, "pay" /* Pay */);
      } else {
        import_payLog.default.log("支付超时或无明确错误，等待轮询结果", { code: res == null ? void 0 : res.code });
      }
    } catch (error) {
      if (runId < currentRunIdRef.current) {
        import_payLog.default.log("支付异常响应过期，忽略");
        return;
      }
      if (isFinishedRef.current || !shouldContinue()) {
        import_payLog.default.log("支付异常时已完成或不应继续处理");
        return;
      }
      if (isRequestFailed(error == null ? void 0 : error.code)) {
        import_payLog.default.log("支付接口异常", { code: error == null ? void 0 : error.code });
        handleFinalError(error, paymentType);
      } else {
        import_payLog.default.log("支付异常超时或无明确错误，等待轮询结果", { code: error == null ? void 0 : error.code });
      }
    }
  };
  const stop = () => {
    import_payLog.default.log("手动停止支付流程");
    clean();
    isFinishedRef.current = true;
  };
  return { run, stop, clean };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ActionType,
  usePayment
});
