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_const = require("../../const");
var import_logs = __toESM(require("./logs"));
var import_service = require("../service");
var import_helper = require("../../helper");
var import_types = require("../types");
var PaymentMethod = class {
  /** 初始化参数 */
  initOptions;
  // 交易号
  paymentNum;
  // 订单ID
  orderId;
  // 设备ID
  deviceId;
  // 统一回调函数
  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.deviceId = options.deviceId;
    this.callback = options.callback;
    this.shouldContinue = options.shouldContinue || (() => true);
    this.config = options.config || {};
    import_logs.default.init(this.paymentNum, {
      orderId: this.orderId,
      deviceId: this.deviceId,
      paymentCode: (options == null ? void 0 : options.paymentCode) || ""
    });
  }
  /**
   * 判断请求是否需要等待轮询结果
   * 1. 有明确错误code且不是超时和支付超时，则直接失败
   * @param code 错误码
   */
  isRequestFailed(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;
    import_logs.default.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);
      import_logs.default.addLog({ title: "回调执行出错", content: error });
    }
  }
  /**
   * 处理成功结果
   */
  handleOperationSuccess(res) {
    if (this.isFinished || !this.shouldContinue() || !this.currentActionType) {
      import_logs.default.addLog({
        title: "操作结果：已完成或不应继续处理，忽略操作成功结果",
        content: { actionType: this.currentActionType, res }
      });
      return;
    }
    const actionType = this.currentActionType;
    import_logs.default.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);
      import_logs.default.addLog({ title: "回调执行出错", content: error });
    }
  }
  /**
   * 处理错误（最终失败）
   * @param error 错误信息
   */
  handleOperationError(error) {
    if (this.isFinished || !this.shouldContinue() || !this.currentActionType) {
      console.log(`⚠️ 已完成或不应继续处理，忽略操作错误`);
      return;
    }
    const actionType = this.currentActionType;
    import_logs.default.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);
      import_logs.default.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()) {
      import_logs.default.addLog({
        title: "查询前置校验：已完成或不应继续处理，取消查询"
      });
      return;
    }
    if (!this.currentQueryApi) {
      import_logs.default.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;
    import_logs.default.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,
            is_outer_response_info: 1
          },
          { signal }
        ),
        this.createTimeoutPromise(import_types.REQUEST_TIMEOUT)
      ]);
      import_logs.default.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) {
        import_logs.default.addLog({ title: "查询轮询结果：过期的查询响应，忽略" });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        import_logs.default.addLog({ title: "查询轮询结果：已完成或不应继续处理" });
        return;
      }
      if (res && `${res.code}` === "200") {
        import_logs.default.addLog({ title: "查询轮询结果：查询成功" });
        const needContinue = this.handleResponse(res);
        if (needContinue) {
          this.scheduleNextQuery(actionType);
        }
        return;
      }
      if (this.isRequestFailed(res == null ? void 0 : res.code)) {
        import_logs.default.addLog({
          title: "查询轮询结果：有明确错误code，停止轮询",
          content: res
        });
        this.handleOperationError(res);
      } else {
        import_logs.default.addLog({
          title: "查询轮询结果：查询返回失败但没有明确code或超时code，继续轮询",
          content: res
        });
        this.scheduleNextQuery(actionType);
      }
    } catch (error) {
      if (this.requestTimeoutTimer) {
        clearTimeout(this.requestTimeoutTimer);
        this.requestTimeoutTimer = null;
      }
      if (queryId !== this.currentQueryId) {
        import_logs.default.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") {
        import_logs.default.addLog({
          title: "查询轮询结果：error-请求被取消或超时，继续轮询"
        });
        this.scheduleNextQuery(actionType);
        return;
      }
      if (this.isRequestFailed(error == null ? void 0 : error.code)) {
        import_logs.default.addLog({
          title: "查询轮询结果：error-有明确错误code，停止轮询",
          content: error
        });
        this.handleOperationError(error);
      } else {
        import_logs.default.addLog({
          title: "查询轮询结果：error-无明确code或者code不是超时，继续轮询",
          content: error
        });
        this.scheduleNextQuery(actionType);
      }
    }
  }
  /**
   * 安排下一次查询
   */
  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) {
      import_logs.default.addLog({
        title: "查询轮询：立即安排下一次查询",
        content: { actionType }
      });
      this.performQuery(actionType);
    } else {
      this.queryIntervalTimer = setTimeout(() => {
        import_logs.default.addLog({
          title: "查询轮询：安排下一次查询",
          content: { actionType }
        });
        this.performQuery(actionType);
      }, import_types.QUERY_INTERVAL);
    }
  }
  /**
   * 开始轮询
   */
  startQuery(actionType) {
    if (this.isFinished || !this.shouldContinue() || this.isQuerying) {
      return;
    }
    this.isQuerying = true;
    import_logs.default.addLog({ title: "开始轮询", content: { actionType } });
    this.globalTimeoutTimer = setTimeout(() => {
      if (this.isFinished) {
        return;
      }
      import_logs.default.addLog({
        title: "轮询全局超时（2分钟），终止所有请求",
        content: { actionType }
      });
      this.handleOperationError({
        code: import_const.PayStatus.Timeout,
        message: "交易超时"
      });
    }, import_types.GLOBAL_TIMEOUT);
    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;
    import_logs.default.addLog({ title: `开始${actionType}查询轮询` });
    this.startQuery(actionType);
  }
  /**
   * 执行操作的核心方法
   */
  async run(runOptions) {
    var _a;
    const { actionType, params } = runOptions;
    const runId = this.startNewOperation(actionType);
    const { pay_param_base64, ...otherParams } = params || {};
    if (Object.keys(otherParams).length > 0) {
      import_logs.default.addLog({
        title: "请求参数",
        content: { params: otherParams }
      });
    }
    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(() => {
        import_logs.default.addLog({
          title: "操作后10秒开始轮询",
          content: { actionType }
        });
        this.startQuery(actionType);
      }, import_types.QUERY_START_DELAY);
    }
    this.controller = new AbortController();
    const { signal } = this.controller;
    try {
      import_logs.default.addLog({
        title: `发起${actionType}请求`,
        content: { actionType, params }
      });
      const res = await actionApi(
        { ...params, request_version: runId, is_outer_response_info: 1 },
        { signal }
      );
      import_logs.default.addLog({
        title: "请求返回",
        content: { params, actionType, res }
      });
      if (runId != ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.request_version)) {
        import_logs.default.addLog({ title: "响应过期，忽略", content: { actionType } });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        import_logs.default.addLog({
          title: "返回时已完成或不应继续处理",
          content: { actionType }
        });
        return;
      }
      if (res && `${res.code}` === "200") {
        import_logs.default.addLog({
          title: `${actionType}接口成功`,
          content: { actionType, res }
        });
        const needContinue = this.handleResponse(res);
        if (needContinue) {
          import_logs.default.addLog({
            title: `${actionType}接口返回processing，开始轮询`
          });
          if (this.queryStartTimer) {
            clearTimeout(this.queryStartTimer);
            this.queryStartTimer = null;
          }
          this.startQuery(actionType);
        }
        return;
      }
      if (this.isRequestFailed(res == null ? void 0 : res.code)) {
        import_logs.default.addLog({
          title: `${actionType}接口返回失败`,
          content: { actionType, res }
        });
        this.handleOperationError(res);
      } else {
        import_logs.default.addLog({
          title: `${actionType}超时或无明确错误，等待轮询结果`,
          content: { actionType, res }
        });
        if (this.queryStartTimer) {
          clearTimeout(this.queryStartTimer);
          this.queryStartTimer = null;
        }
        this.startQuery(actionType);
      }
    } catch (error) {
      if (runId !== this.currentRunId) {
        import_logs.default.addLog({ title: "响应过期，忽略", content: { actionType } });
        return;
      }
      if (this.isFinished || !this.shouldContinue()) {
        import_logs.default.addLog({
          title: "异常时已完成或不应继续处理",
          content: { actionType }
        });
        return;
      }
      if (this.isRequestFailed(error == null ? void 0 : error.code)) {
        import_logs.default.addLog({
          title: `${actionType}接口异常`,
          content: { actionType, error }
        });
        this.handleOperationError(error);
      } else {
        import_logs.default.addLog({
          title: `${actionType}超时或无明确错误，等待轮询结果`,
          content: { actionType, error }
        });
      }
    }
  }
  /**
   * 执行操作
   */
  async runAction(actionOptions) {
    var _a;
    const { actionType, params } = actionOptions;
    const runActionId = this.startNewOperation(actionType);
    const { pay_param_base64, ...otherParams } = params || {};
    if (Object.keys(otherParams).length > 0) {
      import_logs.default.addLog({
        title: "请求参数",
        content: { params: otherParams }
      });
    }
    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,
          is_outer_response_info: 1
        },
        { signal }
      );
      if (this.isFinished || !this.shouldContinue()) {
        import_logs.default.addLog({
          title: "Action返回时已完成或不应继续处理，忽略",
          content: { actionType }
        });
        return;
      }
      if (runActionId !== ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.request_version)) {
        import_logs.default.addLog({
          title: "Action响应过期，忽略",
          content: { actionType }
        });
        return;
      }
      import_logs.default.addLog({
        title: "Action请求返回，开始轮询",
        content: { actionType }
      });
      this.startQuery(actionType);
    } catch (error) {
      if (this.isFinished || !this.shouldContinue()) {
        import_logs.default.addLog({
          title: "Action异常时已完成或不应继续处理，忽略",
          content: { actionType }
        });
        return;
      }
      if (runActionId !== this.currentRunId) {
        import_logs.default.addLog({
          title: "Action响应过期，忽略",
          content: { actionType }
        });
        return;
      }
      import_logs.default.addLog({
        title: "Action请求异常，开始轮询",
        content: { actionType, error }
      });
      this.startQuery(actionType);
    }
  }
  /**
   * 支付
   * @param params 支付参数
   */
  pay(params) {
    this.run({
      actionType: import_types.ActionType.Pay,
      params
    });
  }
  /**
   * 支付取消
   * @param params 取消参数
   */
  payAction(params) {
    this.runAction({
      actionType: import_types.ActionType.PayAction,
      params
    });
  }
  /**
   * 退款
   * @param params 退款参数
   */
  refund(params) {
    this.run({
      actionType: import_types.ActionType.Refund,
      params
    });
  }
  /**
   * 退款取消
   * @param params 取消参数
   */
  refundAction(params) {
    this.runAction({
      actionType: import_types.ActionType.RefundAction,
      params
    });
  }
  /**
   * 支付查询（直接查询，带2分钟超时和轮询机制）
   */
  payQuery() {
    this.runQuery({
      actionType: import_types.ActionType.PayQuery
    });
  }
  /**
   * 退款查询（直接查询，带2分钟超时和轮询机制）
   */
  refundQuery() {
    this.runQuery({
      actionType: import_types.ActionType.RefundQuery
    });
  }
  /**
   * 停止操作，后续依然可以重新发起操作
   */
  stop() {
    import_logs.default.addLog({
      title: "停止操作",
      content: { actionType: this.currentActionType }
    });
    this.clean(true);
  }
  /**
   * 销毁实例（完全清理并上传日志）
   * 注意：销毁后实例不可再使用
   */
  destroy() {
    import_logs.default.addLog({ title: "销毁实例，完成所有流程" });
    this.clean(true);
    import_logs.default.clearLogs();
  }
};
var payment_default = PaymentMethod;
