var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/eftpos/SettlementModal/utils.ts
var utils_exports = {};
__export(utils_exports, {
  parseMX51Params: () => parseMX51Params,
  settlementQuery: () => settlementQuery
});
module.exports = __toCommonJS(utils_exports);
var import_types = require("./types");
var import_serve = require("./serve");
var import_utils = require("@pisell/utils");
var parseMX51Params = (params, settlementStatus, data) => {
  if (!params) {
    return null;
  }
  const result = {
    transactionId: (params == null ? void 0 : params.id) || "",
    status: (params == null ? void 0 : params.status) || "",
    version: (params == null ? void 0 : params.version) || 0,
    message: (params == null ? void 0 : params.message) || "",
    merchantReceipt: params == null ? void 0 : params.merchant_receipt,
    customerReceipt: params == null ? void 0 : params.customer_receipt,
    resultAmounts: params == null ? void 0 : params.result_amounts,
    resultFinancialStatus: params == null ? void 0 : params.result_financial_status,
    layouts: [],
    details: {},
    detailsText: "",
    autoAction: []
  };
  if (!(params == null ? void 0 : params.pos_instructions)) {
    return result;
  }
  const posInstructions = (params == null ? void 0 : params.pos_instructions) || {};
  result.autoAction = (posInstructions == null ? void 0 : posInstructions.auto_actions) || [];
  if (!(posInstructions == null ? void 0 : posInstructions.action_form)) {
    return result;
  }
  const actionForm = (posInstructions == null ? void 0 : posInstructions.action_form) || {};
  if (actionForm == null ? void 0 : actionForm.details) {
    result.details = { ...(actionForm == null ? void 0 : actionForm.details) || {} };
    const detailsTextArr = [];
    Object.keys((actionForm == null ? void 0 : actionForm.details) || {}).forEach((key) => {
      var _a;
      detailsTextArr.push(`${key}: ${((_a = actionForm == null ? void 0 : actionForm.details) == null ? void 0 : _a[key]) || ""}`);
    });
    result.detailsText = (detailsTextArr == null ? void 0 : detailsTextArr.join(", ")) || "";
  }
  if ((actionForm == null ? void 0 : actionForm.layout) && Array.isArray(actionForm == null ? void 0 : actionForm.layout)) {
    const layouts = [];
    actionForm.layout.forEach((layout) => {
      const elements = [];
      if ((layout == null ? void 0 : layout.elements) && Array.isArray(layout == null ? void 0 : layout.elements)) {
        layout.elements.forEach((element) => {
          var _a;
          const elementKey = (element == null ? void 0 : element.key) || "";
          const elementLabel = (element == null ? void 0 : element.label) || "";
          const property = ((_a = actionForm == null ? void 0 : actionForm.properties) == null ? void 0 : _a[elementKey]) || {};
          if (property) {
            const element2 = {
              _extra: {
                merchantReceipt: params == null ? void 0 : params.merchant_receipt,
                customerReceipt: params == null ? void 0 : params.customer_receipt,
                settlementStatus,
                response: data
              },
              key: elementKey,
              name: (property == null ? void 0 : property.name) || "",
              label: elementLabel,
              submitUrl: (property == null ? void 0 : property.submit_url) || "",
              action: property == null ? void 0 : property.action,
              type: (property == null ? void 0 : property.type) || "button",
              text: property == null ? void 0 : property.text,
              // 如果是打印收据按钮，需要关联对应的小票信息
              receipt: elementKey === import_types.EButtonKeyType.PrintMerchantReceipt ? result == null ? void 0 : result.merchantReceipt : elementKey === import_types.EButtonKeyType.PrintCustomerReceipt ? result == null ? void 0 : result.customerReceipt : null
            };
            if ((property == null ? void 0 : property.type) === "image") {
              element2.image = {
                name: (property == null ? void 0 : property.name) || "",
                data: (property == null ? void 0 : property.data) || "",
                encoding: (property == null ? void 0 : property.encoding) || ""
              };
            }
            elements.push(element2);
          }
        });
      }
      if (elements.length > 0) {
        layouts.push({
          layoutType: layout.type || "unknown",
          elements
        });
      }
    });
    result.layouts = layouts;
  }
  return result;
};
var SETTLEMENT_TOTAL_TIMEOUT = 2 * 60 * 1e3;
var SETTLEMENT_QUERY_TIMEOUT = 30 * 1e3;
var createFailedResponse = (message) => {
  return {
    code: -1,
    data: {
      status: "FAILED",
      message: message || import_utils.locales.getText("page.eftpos.text.settlement.failed"),
      // 构建一个按钮布局，按钮为 Done
      pos_instructions: {
        auto_actions: null,
        action_form: {
          layout: [
            {
              type: "horizontal_layout",
              elements: [
                {
                  label: import_utils.locales.getText(
                    "page.eftpos.text.settlement.button.done"
                  ),
                  key: "settlement_complete"
                }
              ]
            }
          ],
          properties: {
            settlement_complete: {
              type: "button",
              submit_url: null,
              action: "SETTLEMENT_COMPLETE"
            }
          },
          details: null
        }
      }
    }
  };
};
var pollSettlementQuery = async (params, callback) => {
  var _a, _b;
  let min_version = ((params == null ? void 0 : params.version) || 0) + 1;
  let isFinished = false;
  let currentRequestController = null;
  const totalTimer = setTimeout(() => {
    isFinished = true;
    if (currentRequestController) {
      currentRequestController.abort();
      currentRequestController = null;
    }
    callback(import_types.ESettlementStatus.Failed, createFailedResponse());
  }, SETTLEMENT_TOTAL_TIMEOUT);
  try {
    while (!isFinished) {
      if (currentRequestController) {
        currentRequestController.abort();
        currentRequestController = null;
      }
      currentRequestController = new AbortController();
      let requestTimeoutTimer = null;
      const requestPromise = () => {
        return new Promise((_, reject) => {
          requestTimeoutTimer = setTimeout(() => {
            if (currentRequestController) {
              currentRequestController.abort();
            }
            reject(createFailedResponse());
          }, SETTLEMENT_QUERY_TIMEOUT);
        });
      };
      try {
        const queryRes = await Promise.race([
          requestPromise(),
          (0, import_serve.settlementQueryApi)(
            params == null ? void 0 : params.id,
            { min_version, card_reader_id: params == null ? void 0 : params.card_reader_id },
            { signal: currentRequestController.signal }
          )
        ]);
        if (isFinished) break;
        if ((queryRes == null ? void 0 : queryRes.code) === 200 && ((_a = queryRes == null ? void 0 : queryRes.data) == null ? void 0 : _a.status) === "FINALISED") {
          isFinished = true;
          clearTimeout(totalTimer);
          callback(import_types.ESettlementStatus.Success, queryRes);
          break;
        }
        console.log("settlementQuery_queryRes", queryRes);
        callback(import_types.ESettlementStatus.Processing, queryRes);
        min_version = (((_b = queryRes == null ? void 0 : queryRes.data) == null ? void 0 : _b.version) || 0) + 1;
      } catch (error) {
        if (isFinished) break;
        console.log("settlementQuery_error", error);
      } finally {
        if (requestTimeoutTimer) {
          clearTimeout(requestTimeoutTimer);
        }
        requestTimeoutTimer = null;
      }
    }
  } finally {
    if (totalTimer) {
      clearTimeout(totalTimer);
    }
  }
};
var settlementQuery = async (params, callback) => {
  var _a, _b, _c;
  try {
    const initiateRes = await (0, import_serve.settlementApi)(params, {});
    if ((initiateRes == null ? void 0 : initiateRes.code) == 200 && ((_a = initiateRes == null ? void 0 : initiateRes.data) == null ? void 0 : _a.id)) {
      callback(import_types.ESettlementStatus.Processing, initiateRes);
    } else {
      callback(
        import_types.ESettlementStatus.Failed,
        createFailedResponse(initiateRes == null ? void 0 : initiateRes.message)
      );
      return;
    }
    pollSettlementQuery(
      {
        id: (_b = initiateRes == null ? void 0 : initiateRes.data) == null ? void 0 : _b.id,
        version: ((_c = initiateRes == null ? void 0 : initiateRes.data) == null ? void 0 : _c.version) || 0,
        card_reader_id: params == null ? void 0 : params.card_reader_id
      },
      callback
    );
  } catch (error) {
    callback(import_types.ESettlementStatus.Failed, createFailedResponse(error == null ? void 0 : error.message));
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  parseMX51Params,
  settlementQuery
});
