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/aggregatePayment/utils/payment.ts
var payment_exports = {};
__export(payment_exports, {
  default: () => payment_default
});
module.exports = __toCommonJS(payment_exports);
var import_utils = require("@pisell/utils");
var import_const = require("../../const");
var import_payLog = __toESM(require("../../utils/payLog"));
var import_service = require("../service");
var import_helper = require("../../helper");
var import_types = require("../types");
var sanitizePaymentLogContent = (content) => {
  var _a, _b;
  if (!content || typeof content !== "object") {
    return content;
  }
  if (!((_b = (_a = content.params) == null ? void 0 : _a.eftpos) == null ? void 0 : _b.pay_param_base64)) {
    return content;
  }
  const clonedContent = (0, import_helper.cloneDeep)(content);
  delete clonedContent.params.eftpos.pay_param_base64;
  return clonedContent;
};
var addPaymentLog = ({ title, content }) => {
  import_payLog.default.log(title, sanitizePaymentLogContent(content));
};
var paymentLog = {
  addLog: addPaymentLog
};
var PaymentMethod = class {
  /** 初始化参数 */
  initOptions;
  // 交易号
  paymentNum;
  // 订单ID
  orderId;
  // 统一回调函数
  callback;
  // 检查是否应该继续处理结果
  shouldContinue;
  // 配置
  config = {};
  // 主请求的 AbortController（支付/退款等）
  controller = null;
  // 查询请求的 AbortController
  queryController = null;
  // 开始轮询的定时器
  queryStartTimer = null;
  // 全局超时定时器
  globalTimeoutTimer = null;
  // 单次请求超时定时器
  requestTimeoutTimer = null;
  // 轮询间隔定时器
  queryIntervalTimer = null;
  // 是否已经完成（成功或失败）
  isFinished = false;
  // 是否正在轮询中
  isQuerying = false;
  // 当前操作类型
  currentActionType = null;
  // 当前查询的唯一ID（时间戳），用于防止过期响应被处理
  currentQueryId = "";
  // 当前执行的唯一ID（时间戳），用于防止旧的请求响应被处理
  currentRunId = "";
  // 当前查询API
  currentQueryApi = null;
  constructor(options) {
    this.initOptions = options;
    this.paymentNum = options.paymentNum;
    this.orderId = options.orderId;
    this.callback = options.callback;
    this.shouldContinue = options.shouldContinue || (() => true);
    this.config = options.config || {};
    import_payLog.default.setContext({
      transactionNumber: this.paymentNum,
      extra: { paymentCode: (options == null ? void 0 : options.paymentCode) || "" }
    });
    addPaymentLog({
      title: "聚合支付初始化",
      content: {
        paymentNum: this.paymentNum,
        paymentCode: (options == null ? void 0 : options.paymentCode) || ""
      }
    });
  }
  /**
   * 判断请求是否需要等待轮询结果
   * 1. 有明确错误code且不是超时和支付超时，则直接失败
   * @param code 错误码
   */
  isBusinessFailed(res) {
    var _a;
    const { external_unified_status, response_code } = ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.external_unified_response) || {};
    return `${res == null ? void 0 : res.code}` === "200" && external_unified_status === import_types.EPaymentStatus.Failed && response_code !== import_const.PayStatus.Timeout && response_code !== import_const.PayStatus.PayTimeout;
  }
  /**
   * 判断业务是否成功
   */
  isBusinessSuccess(res) {
    var _a;
    const { external_unified_status } = ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.external_unified_response) || {};
    return `${res == null ? void 0 : res.code}` === "200" && external_unified_status === import_types.EPaymentStatus.Success;
  }
  /**
   * 判断最外层code是否是超时错误
   */
  isOuterCodeTimeout(code) {
    return code && (`${code}` === import_const.PayStatus.Timeout || `${code}` === import_const.PayStatus.PayTimeout);
  }
  /**
   * 清理定时器和请求控制器
   */
  cleanupTimersAndControllers() {
    if (this.controller) {
      this.controller.abort();
      this.controller = null;
    }
    if (this.queryController) {
      this.queryController.abort();
      this.queryController = null;
    }
    if (this.queryStartTimer) {
      clearTimeout(this.queryStartTimer);
      this.queryStartTimer = null;
    }
    if (this.globalTimeoutTimer) {
      clearTimeout(this.globalTimeoutTimer);
      this.globalTimeoutTimer = null;
    }
    if (this.requestTimeoutTimer) {
      clearTimeout(this.requestTimeoutTimer);
      this.requestTimeoutTimer = null;
    }
    if (this.queryIntervalTimer) {
      clearTimeout(this.queryIntervalTimer);
      this.queryIntervalTimer = null;
    }
  }
  /**
   * 清理资源并重置状态
   * @param markAsFinished 是否标记为已完成（true: 操作完成; false: 准备新操作）
   */
  clean(markAsFinished = false) {
    console.log("🧹 清理资源", { markAsFinished });
    this.cleanupTimersAndControllers();
    this.isQuerying = false;
    this.isFinished = markAsFinished;
    this.currentQueryApi = null;
    this.currentActionType = null;
  }
  /**
   * 开始新的操作流程（统一的流程初始化）
   * @param actionType 操作类型
   * @returns 本次流程的唯一ID
   */
  startNewOperation(actionType) {
    const runId = (0, import_helper.getUuid)();
    this.currentRunId = runId;
    paymentLog.addLog({
      title: `触发新的操作：${actionType}`,
      content: { actionType, runId }
    });
    this.clean(false);
    this.currentActionType = actionType;
    return runId;
  }
  /**
   * 处理操作过程
   */
  handleOperationProcess(res) {
    if (!this.currentActionType) {
      return;
    }
    const actionType = this.currentActionType;
    try {
      this.callback(this, {
        status: import_types.EPaymentStatus.Processing,
        actionType,
        data: res
      });
    } catch (error) {
      console.error("⚠️ 回调执行出错:", error);
      paymentLog.addLog({ title: "回调执行出错", content: error });
    }
  }
  /**
   * 处理成功结果
   */
  handleOperationSuccess(res) {
    if (this.isFinished || !this.shouldContinue() || !this.currentActionType) {
      paymentLog.addLog({
        title: "操作结果：已完成或不应继续处理，忽略操作成功结果",
        content: { actionType: this.currentActionType, res }
      });
      return;
    }
    const actionType = this.currentActionType;
    paymentLog.addLog({
      title: "操作结果：成功",
      content: { actionType, res }
    });
    this.clean(true);
    try {
      this.callback(this, {
        status: import_types.EPaymentStatus.Success,
        actionType,
        data: res
      });
    } catch (error) {
      console.error("⚠️ 回调执行出错:", error);
      paymentLog.addLog({ title: "回调执行出错", content: error });
    }
  }
  /**
   * 处理错误（最终失败）
   * @param error 错误信息
   */
  handleOperationError(error) {
    if (this.isFinished || !this.shouldContinue() || !this.currentActionType) {
      console.log(`⚠️ 已完成或不应继续处理，忽略操作错误`);
      return;
    }
    const actionType = this.currentActionType;
    paymentLog.addLog({
      title: "操作结果：失败",
      content: { actionType, error }
    });
    this.clean(true);
    try {
      this.callback(this, {
        status: import_types.EPaymentStatus.Failed,
        actionType,
        data: error
      });
    } catch (err) {
      console.error("⚠️ 回调执行出错:", err);
      paymentLog.addLog({ title: "回调执行出错", content: err });
    }
  }
  /**
   * 处理接口响应
   */
  handleResponse(res) {
    var _a;
    if (!this.currentActionType) {
      return;
    }
    let needContinue = true;
    const { external_unified_status } = ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.external_unified_response) || {};
    switch (external_unified_status) {
      case import_types.EPaymentStatus.Success:
        this.handleOperationSuccess(res);
        needContinue = false;
        break;
      case import_types.EPaymentStatus.Failed:
        this.handleOperationError(res);
        needContinue = false;
        break;
      case import_types.EPaymentStatus.Processing:
      default:
        this.handleOperationProcess(res);
        needContinue = true;
        break;
    }
    return needContinue;
  }
  /**
   * 创建超时 Promise
   */
  createTimeoutPromise(timeoutMs) {
    return new Promise((_, reject) => {
      this.requestTimeoutTimer = setTimeout(() => {
        console.log(`⏱️ 单次查询超时（${timeoutMs / 1e3}秒），强制终止`);
        if (this.queryController) {
          this.queryController.abort();
        }
        reject(new Error("REQUEST_TIMEOUT"));
      }, timeoutMs);
    });
  }
  /**
   * 单次查询请求
   */
  async performQuery(actionType) {
    var _a, _b;
    if (this.isFinished || !this.shouldContinue()) {
      paymentLog.addLog({
        title: "查询前置校验：已完成或不应继续处理，取消查询"
      });
      return;
    }
    if (!this.currentQueryApi) {
      paymentLog.addLog({ title: "查询API未设置，取消查询" });
      return;
    }
    if (this.queryController) {
      this.queryController.abort();
      this.queryController = null;
    }
    if (this.requestTimeoutTimer) {
      clearTimeout(this.requestTimeoutTimer);
      this.requestTimeoutTimer = null;
    }
    const queryId = (0, import_helper.getUuid)();
    this.currentQueryId = queryId;
    this.queryController = new AbortController();
    const { signal } = this.queryController;
    paymentLog.addLog({ title: "查询轮询：开始单次查询" });
    try {
      const res = await Promise.race([
        this.currentQueryApi(
          {
            order_id: this.orderId,
            unique_payment_number: this.paymentNum,
            payment_code: (_a = this.initOptions) == null ? void 0 : _a.paymentCode,
            request_version: queryId,
            // TODO: MX51审核需要，后续需要删除
            is_force_request_api: 1
          },
          { signal }
        ),
        this.createTimeoutPromise(import_types.REQUEST_TIMEOUT)
      ]);
      paymentLog.addLog({
        title: "查询轮询：单次查询返回",
        content: { actionType, res }
      });
      if (this.requestTimeoutTimer) {
        clearTimeout(this.requestTimeoutTimer);
        this.requestTimeoutTimer = null;
      }
      if (((_b = res == null ? void 0 : res.data) == null ? void 0 : _b.request_version) !== this.currentQueryId) {
        paymentLog.addLog({ title: "查询轮询结果：过期的查询响应，忽略" });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        paymentLog.addLog({ title: "查询轮询结果：已完成或不应继续处理" });
        return;
      }
      if (`${res == null ? void 0 : res.code}` !== "200") {
        paymentLog.addLog({ title: "查询轮询结果：查询返回失败，code非200" });
        this.handleOperationError(res);
        return;
      }
      if (this.isBusinessSuccess(res)) {
        paymentLog.addLog({ title: "查询轮询结果：查询成功" });
        const needContinue = this.handleResponse(res);
        if (needContinue) {
          this.scheduleNextQuery(actionType);
        }
        return;
      }
      if (this.isBusinessFailed(res)) {
        paymentLog.addLog({
          title: "查询轮询结果：有明确错误code，停止轮询",
          content: res
        });
        this.handleOperationError(res);
      } else {
        paymentLog.addLog({
          title: "查询轮询结果：交易进行中，继续轮询",
          content: res
        });
        this.handleOperationProcess(res);
        this.scheduleNextQuery(actionType);
      }
    } catch (error) {
      if (this.requestTimeoutTimer) {
        clearTimeout(this.requestTimeoutTimer);
        this.requestTimeoutTimer = null;
      }
      if (queryId !== this.currentQueryId) {
        paymentLog.addLog({
          title: "查询轮询结果：error-过期的查询异常，忽略"
        });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        return;
      }
      if ((error == null ? void 0 : error.name) === "AbortError" || (error == null ? void 0 : error.message) === "REQUEST_TIMEOUT") {
        paymentLog.addLog({
          title: "查询轮询结果：error-请求被取消或超时，继续轮询"
        });
        this.scheduleNextQuery(actionType);
        return;
      }
      if (this.isOuterCodeTimeout(error == null ? void 0 : error.code)) {
        paymentLog.addLog({
          title: "查询轮询结果：error-code是超时错误，继续轮询",
          content: error
        });
        this.scheduleNextQuery(actionType);
        return;
      } else {
        paymentLog.addLog({
          title: "查询轮询结果：error-有明确错误code，停止轮询",
          content: error
        });
        this.handleOperationError(error);
      }
    }
  }
  /**
   * 安排下一次查询
   */
  scheduleNextQuery(actionType) {
    var _a;
    if (this.isFinished || !this.shouldContinue()) {
      return;
    }
    if (this.queryIntervalTimer) {
      clearTimeout(this.queryIntervalTimer);
    }
    if (((_a = this.config) == null ? void 0 : _a.hasQueryInterval) === false) {
      paymentLog.addLog({
        title: "查询轮询：立即安排下一次查询",
        content: { actionType }
      });
      this.performQuery(actionType);
    } else {
      this.queryIntervalTimer = setTimeout(() => {
        paymentLog.addLog({
          title: "查询轮询：安排下一次查询",
          content: { actionType }
        });
        this.performQuery(actionType);
      }, import_types.QUERY_INTERVAL);
    }
  }
  /**
   * 开始轮询
   */
  startQuery(actionType) {
    var _a;
    if (this.isFinished || !this.shouldContinue() || this.isQuerying) {
      return;
    }
    this.isQuerying = true;
    paymentLog.addLog({ title: "开始轮询", content: { actionType } });
    const _globalQueryTimeout = ((_a = this.config) == null ? void 0 : _a.globalQueryTimeout) || import_types.GLOBAL_TIMEOUT;
    this.globalTimeoutTimer = setTimeout(() => {
      var _a2;
      if (this.isFinished) {
        return;
      }
      paymentLog.addLog({
        title: `轮询全局超时（${_globalQueryTimeout / 1e3}秒），终止所有请求`,
        content: { actionType }
      });
      this.handleOperationError({
        code: "200",
        data: {
          external_unified_response: {
            external_unified_status: import_types.EPaymentStatus.Failed,
            response_code: import_const.PayStatus.Timeout,
            message: ((_a2 = import_utils.locales) == null ? void 0 : _a2.getText("page.eftpos-pay.text.transaction.fail.timeout")) || "Transaction timeout."
          }
        }
      });
    }, _globalQueryTimeout);
    this.performQuery(actionType);
  }
  /**
   * 获取操作API和查询API
   */
  getActionApi(actionType) {
    let actionApi = null;
    let queryApi = null;
    switch (actionType) {
      case import_types.ActionType.Pay:
        actionApi = import_service.AGPTPayApi;
        queryApi = import_service.AGPTQueryApi;
        break;
      case import_types.ActionType.PayAction:
        actionApi = import_service.AGPTActionApi;
        queryApi = import_service.AGPTQueryApi;
        break;
      case import_types.ActionType.PayQuery:
        queryApi = import_service.AGPTQueryApi;
        break;
      case import_types.ActionType.Refund:
        actionApi = import_service.AGPTRefundApi;
        queryApi = import_service.AGPTRefundQueryApi;
        break;
      case import_types.ActionType.RefundAction:
        actionApi = import_service.AGPTRefundActionApi;
        queryApi = import_service.AGPTRefundQueryApi;
        break;
      case import_types.ActionType.RefundQuery:
        queryApi = import_service.AGPTRefundQueryApi;
        break;
    }
    return { actionApi, queryApi };
  }
  /**
   * 执行纯查询操作（不需要先调用支付/退款接口）
   */
  async runQuery(options) {
    const { actionType } = options;
    this.startNewOperation(actionType);
    const { queryApi } = this.getActionApi(actionType);
    if (!queryApi) {
      const error = new Error(`${actionType}查询接口不存在`);
      this.handleOperationError(error);
      return;
    }
    this.currentQueryApi = queryApi;
    paymentLog.addLog({ title: `开始${actionType}查询轮询` });
    this.startQuery(actionType);
  }
  /**
   * 执行操作的核心方法
   */
  async run(runOptions) {
    var _a;
    const { actionType, params, config } = runOptions;
    const runId = this.startNewOperation(actionType);
    paymentLog.addLog({
      title: "请求参数",
      content: { params }
    });
    const { actionApi, queryApi } = this.getActionApi(actionType);
    if (!actionApi) {
      const error = new Error(`${actionType}接口不存在`);
      this.handleOperationError(error);
      return;
    }
    this.currentQueryApi = queryApi;
    if (queryApi !== null) {
      this.queryStartTimer = setTimeout(() => {
        paymentLog.addLog({
          title: "操作后10秒开始轮询",
          content: { actionType }
        });
        this.startQuery(actionType);
      }, import_types.QUERY_START_DELAY);
    }
    this.controller = new AbortController();
    const { signal } = this.controller;
    const _query = (_status, _title, _content) => {
      paymentLog.addLog({ title: _title, content: _content });
      if (this.queryStartTimer) {
        clearTimeout(this.queryStartTimer);
        this.queryStartTimer = null;
      }
      this.startQuery(actionType);
    };
    try {
      paymentLog.addLog({
        title: `发起${actionType}请求`,
        content: { actionType, params }
      });
      const res = await actionApi(
        { ...params, request_version: runId },
        { signal }
      );
      paymentLog.addLog({
        title: "请求返回",
        content: { params, actionType, res }
      });
      if (runId != ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.request_version)) {
        paymentLog.addLog({ title: "响应过期，忽略", content: { actionType } });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        paymentLog.addLog({
          title: "返回时已完成或不应继续处理",
          content: { actionType }
        });
        return;
      }
      if (`${res == null ? void 0 : res.code}` !== "200") {
        paymentLog.addLog({ title: `${actionType}接口返回失败，code非200` });
        this.handleOperationError(res);
        return;
      }
      if (this.isBusinessSuccess(res)) {
        paymentLog.addLog({
          title: `${actionType}接口成功`,
          content: { actionType, res }
        });
        const needContinue = this.handleResponse(res);
        if (needContinue) {
          _query("success", `${actionType}接口返回processing，开始轮询`);
        }
        return;
      }
      if (this.isBusinessFailed(res)) {
        paymentLog.addLog({
          title: `${actionType}接口返回失败`,
          content: { actionType, res }
        });
        this.handleOperationError(res);
      } else {
        this.handleOperationProcess(res);
        _query("failed", `${actionType}超时或无明确错误，开始轮询`, {
          actionType,
          res
        });
      }
    } catch (error) {
      if (runId !== this.currentRunId) {
        paymentLog.addLog({ title: "响应过期，忽略", content: { actionType } });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        paymentLog.addLog({
          title: "异常时已完成或不应继续处理",
          content: { actionType }
        });
        return;
      }
      _query("failed", `${actionType}接口异常，开始轮询`, {
        actionType,
        error
      });
    }
  }
  /**
   * 执行操作
   */
  async runAction(actionOptions) {
    var _a;
    const { actionType, params, config } = actionOptions;
    console.log("runAction_actionOptions", actionOptions);
    const runActionId = this.startNewOperation(actionType);
    paymentLog.addLog({
      title: `${actionType}操作请求参数`,
      content: { actionType, params }
    });
    const { actionApi, queryApi } = this.getActionApi(actionType);
    if (!actionApi) {
      const error = new Error(`${actionType}操作接口不存在`);
      this.handleOperationError(error);
      return;
    }
    this.currentQueryApi = queryApi;
    this.controller = new AbortController();
    const { signal } = this.controller;
    try {
      const res = await actionApi(
        {
          ...params || {},
          request_version: runActionId
        },
        { signal }
      );
      if (this.isFinished || !this.shouldContinue()) {
        paymentLog.addLog({
          title: "Action返回时已完成或不应继续处理，忽略",
          content: { actionType }
        });
        return;
      }
      if (runActionId !== ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.request_version)) {
        paymentLog.addLog({
          title: "Action响应过期，忽略",
          content: { actionType }
        });
        return;
      }
      if (config == null ? void 0 : config.needResponse) {
        this.handleResponse(res);
        return;
      }
      paymentLog.addLog({
        title: "Action请求返回，开始轮询",
        content: { actionType }
      });
      this.startQuery(actionType);
    } catch (error) {
      if (this.isFinished || !this.shouldContinue()) {
        paymentLog.addLog({
          title: "Action异常时已完成或不应继续处理，忽略",
          content: { actionType }
        });
        return;
      }
      if (runActionId !== this.currentRunId) {
        paymentLog.addLog({
          title: "Action响应过期，忽略",
          content: { actionType }
        });
        return;
      }
      paymentLog.addLog({
        title: "Action请求异常，开始轮询",
        content: { actionType, error }
      });
      this.startQuery(actionType);
    }
  }
  /**
   * 支付
   * @param params 支付参数
   */
  pay(params, config) {
    this.run({
      actionType: import_types.ActionType.Pay,
      params,
      config
    });
  }
  /**
   * 支付取消
   * @param params 取消参数
   */
  payAction(params, config) {
    this.runAction({
      actionType: import_types.ActionType.PayAction,
      params,
      config
    });
  }
  /**
   * 退款
   * @param params 退款参数
   */
  refund(params, config) {
    this.run({
      actionType: import_types.ActionType.Refund,
      params,
      config
    });
  }
  /**
   * 退款取消
   * @param params 取消参数
   */
  refundAction(params, config) {
    this.runAction({
      actionType: import_types.ActionType.RefundAction,
      params,
      config
    });
  }
  /**
   * 支付查询（直接查询，带2分钟超时和轮询机制）
   */
  payQuery() {
    this.runQuery({
      actionType: import_types.ActionType.PayQuery
    });
  }
  /**
   * 退款查询（直接查询，带2分钟超时和轮询机制）
   */
  refundQuery() {
    this.runQuery({
      actionType: import_types.ActionType.RefundQuery
    });
  }
  /**
   * 停止操作，后续依然可以重新发起操作
   */
  stop() {
    paymentLog.addLog({
      title: "停止操作",
      content: { actionType: this.currentActionType }
    });
    this.clean(true);
  }
  /**
   * 销毁实例（完全清理并上传日志）
   * 注意：销毁后实例不可再使用
   */
  destroy() {
    paymentLog.addLog({ title: "支付步骤结束，销毁实例" });
    this.clean(true);
  }
};
var payment_default = PaymentMethod;
