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/mx51/index.tsx
var mx51_exports = {};
__export(mx51_exports, {
  default: () => mx51_default
});
module.exports = __toCommonJS(mx51_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils2 = require("../../../utils");
var import_store = require("../store");
var import_const = require("../const");
var import_hooks = require("../hooks");
var import_aggregatePayment = require("../aggregatePayment");
var import_payLog = __toESM(require("../utils/payLog"));
var import_types = require("../aggregatePayment/types");
var import_utils3 = require("./utils");
var import_types2 = require("./types");
var import_Action = __toESM(require("./Action"));
var import_store2 = require("../store");
var import_hooks2 = require("../hooks");
var import_manufacturer = require("../manufacturer");
var import_helper = require("../helper");
var shouldPrintReceiptOnPos = (setting) => {
  if (typeof setting === "boolean") {
    return setting === false;
  }
  if (typeof setting === "number") {
    return setting === 0;
  }
  if (typeof setting === "string") {
    return setting === "0";
  }
  return false;
};
var AggregatePayment = ({ onChange }) => {
  const context = (0, import_useEngineContext.default)();
  const utils = context.appHelper.utils || {};
  import_utils2.request.setRequest(utils == null ? void 0 : utils.request);
  const {
    title,
    custom,
    status,
    eftpos,
    mode,
    name,
    symbol,
    amount,
    order_id
  } = (0, import_store.useContextData)();
  const {
    statusRef,
    numRef,
    netRef,
    modeRef,
    deviceRef,
    orderIdRef,
    amountRef,
    payRef
  } = (0, import_hooks.useStoreRef)();
  const dispatch = (0, import_store2.useDispatch)();
  const fail = (0, import_hooks2.useFail)(0);
  const failRef = (0, import_react.useRef)(fail);
  const [receiptModalShow, setReceiptModalShow] = (0, import_react.useState)(false);
  const [receiptModalData, setReceiptModalData] = (0, import_react.useState)(null);
  const [cancelDisabled, setCancelDisabled] = (0, import_react.useState)(false);
  const clickLockedRef = (0, import_react.useRef)(false);
  const clickUnlockTimerRef = (0, import_react.useRef)(null);
  const actionTimeoutRef = (0, import_react.useRef)(null);
  const clearRef = (0, import_react.useRef)(null);
  (0, import_react.useEffect)(() => {
    failRef.current = fail;
  }, [fail]);
  const initRef = (0, import_react.useRef)(false);
  const unloadRef = (0, import_react.useRef)(false);
  const updateToLoading = (title2) => {
    dispatch((0, import_store2.updateStatus)(import_const.StatusEnum.Loading));
    dispatch(
      (0, import_store2.updateState)({
        title: title2 || import_utils.locales.getText("page.eftpos-pay.text.loading")(modeRef.current)
      })
    );
  };
  const payment = (0, import_aggregatePayment.usePayment)({
    paymentCode: "EFTPOS_MX51",
    paymentNum: numRef.current || "",
    shouldContinue: () => !(unloadRef.current || !netRef.current),
    config: {
      hasQueryInterval: false,
      // 不开启轮询间隔
      globalQueryTimeout: 1e3 * 60 * 2,
      // 全局轮询超时时间2分钟
      requestDelaySeconds: 130
      // 接口兜底查询时间130秒
    },
    callback: (_instance, response) => {
      var _a, _b;
      console.log("callback  =>>>>>> ", response);
      const { status: status2, data } = response || {};
      const { transaction, action } = ((_a = data == null ? void 0 : data.data) == null ? void 0 : _a.external_unified_response) || {};
      const transformedData = (0, import_utils3.parseMX51Params)(transaction, status2, data);
      console.log("event_transformedData =>>>>>> ", transformedData);
      dispatch((0, import_store2.updateCustom)({ customAction: transformedData }));
      let needClearActionTimeout = true;
      if (status2 === import_types.EPaymentStatus.Processing) {
        if (action === "signature") {
          dispatch((0, import_store2.updateStatus)(import_const.StatusEnum.Question));
          dispatch((0, import_store2.updateState)({ title: (transformedData == null ? void 0 : transformedData.message) || "" }));
          _instance.stop();
          if ((_b = transformedData == null ? void 0 : transformedData.autoAction) == null ? void 0 : _b.includes("PRINT_MERCHANT_RECEIPT")) {
            const merchantReceipt = (transformedData == null ? void 0 : transformedData.merchantReceipt) || "";
            onChange("print", merchantReceipt ? [merchantReceipt] : []);
          }
        } else {
          needClearActionTimeout = false;
          updateToLoading();
        }
      } else if (status2 === import_types.EPaymentStatus.Success) {
        handleSuccess(data);
      } else if (status2 === import_types.EPaymentStatus.Failed) {
        if (transformedData) {
          dispatch((0, import_store2.updateStatus)("fail"));
          dispatch((0, import_store2.updateState)({ title: (transformedData == null ? void 0 : transformedData.message) || "" }));
        } else {
          handleFail(data);
        }
      }
      if (needClearActionTimeout) {
        if (actionTimeoutRef.current) {
          import_payLog.default.log("清除操作行为超时定时器");
          clearTimeout(actionTimeoutRef.current);
          actionTimeoutRef.current = null;
        }
      }
    }
  });
  (0, import_react.useEffect)(() => {
    console.log("mx51页面初始化", statusRef.current);
    if (statusRef.current === import_const.StatusEnum.Success || statusRef.current === import_const.StatusEnum.Fail || statusRef.current === import_const.StatusEnum.Question) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;
    if (numRef.current) {
      console.log("payment.query");
      payment.query();
      return;
    }
    payment.run();
  }, []);
  (0, import_react.useEffect)(() => {
    return () => {
      console.log("页面卸载");
      unloadRef.current = true;
      if (actionTimeoutRef.current) {
        clearTimeout(actionTimeoutRef.current);
        actionTimeoutRef.current = null;
      }
      if (clearRef.current) {
        clearTimeout(clearRef.current);
        clearRef.current = null;
      }
      if (clickUnlockTimerRef.current) {
        clearTimeout(clickUnlockTimerRef.current);
        clickUnlockTimerRef.current = null;
      }
    };
  }, []);
  const handleFail = (errorData) => {
    var _a, _b;
    const { message, response_code } = ((_a = errorData == null ? void 0 : errorData.data) == null ? void 0 : _a.external_unified_response) || {};
    const _code = `${response_code || ""}` || import_const.PayStatus.PaymentFailed;
    const _message = message || (errorData == null ? void 0 : errorData.message) || "";
    console.log("handleFail =>>>> ", errorData, _code, _message);
    (_b = failRef.current) == null ? void 0 : _b.call(failRef, { code: _code, message: _message }, true);
  };
  const handleSuccess = (res) => {
    var _a, _b;
    const receipt = [];
    const { transaction, external_service_fee } = ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.external_unified_response) || {};
    const { merchant_receipt, customer_receipt } = transaction || {};
    const card_reader_surcharge = external_service_fee || 0;
    const deviceSetting = (_b = deviceRef.current) == null ? void 0 : _b.setting;
    const shouldPrintMerchantReceiptOnPos = shouldPrintReceiptOnPos(
      deviceSetting == null ? void 0 : deviceSetting.print_merchant_receipt
    );
    const shouldPrintCustomerReceiptOnPos = shouldPrintReceiptOnPos(
      deviceSetting == null ? void 0 : deviceSetting.prompt_customer_receipt
    );
    if (shouldPrintMerchantReceiptOnPos && merchant_receipt) {
      receipt.push(merchant_receipt);
    }
    if (shouldPrintCustomerReceiptOnPos && customer_receipt) {
      receipt.push(customer_receipt);
    }
    dispatch((0, import_store.updateNextStep)());
    dispatch(
      (0, import_store2.updateCustom)({
        card_reader_surcharge,
        receipt
      })
    );
    dispatch(
      (0, import_store2.updateState)({
        status: "success",
        title: import_utils.locales.getText("page.eftpos-pay.text.successful")(
          modeRef.current
        )
      })
    );
    clearRef.current = setTimeout(() => {
      const params = (0, import_helper.getPayParams)(
        {
          mode: modeRef.current,
          amount: amountRef.current,
          order_id: orderIdRef.current,
          number: numRef.current,
          device: deviceRef.current,
          pay: payRef.current,
          custom: {
            card_reader_surcharge,
            receipt
          }
        },
        "success"
      );
      onChange("success", { ...params, receipt });
    }, 1e3);
  };
  const onCancel = (element) => {
    console.log("onCancel", element);
    setCancelDisabled(true);
    payment.action({ submit_url: element == null ? void 0 : element.submitUrl });
    actionTimeoutRef.current = setTimeout(() => {
      var _a, _b, _c;
      import_payLog.default.log("取消操作超时，前往标记支付");
      (_b = (_a = payment == null ? void 0 : payment._instance) == null ? void 0 : _a.stop) == null ? void 0 : _b.call(_a);
      (_c = failRef.current) == null ? void 0 : _c.call(failRef, { code: import_const.PayStatus.Timeout }, true);
    }, import_types2.CANCEL_ACTION_TIMEOUT);
  };
  const onDecline = (element) => {
    payment.action({ submit_url: element == null ? void 0 : element.submitUrl });
  };
  const onAccept = (element) => {
    payment.action({ submit_url: element == null ? void 0 : element.submitUrl });
  };
  const onPrintMerchantReceipt = (element) => {
    onChange("print", (element == null ? void 0 : element.receipt) ? [element == null ? void 0 : element.receipt] : []);
    setReceiptModalShow(true);
    setReceiptModalData(element == null ? void 0 : element.receipt);
  };
  const onPrintCustomerReceipt = (element) => {
    onChange("print", (element == null ? void 0 : element.receipt) ? [element == null ? void 0 : element.receipt] : []);
    setReceiptModalShow(true);
    setReceiptModalData(element == null ? void 0 : element.receipt);
  };
  const onRetry = (element) => {
    onChange("page", "pay");
    const { customAction, ...restCustom } = custom || {};
    const _params = {
      ...restCustom,
      // 自定义参数需要重新传递
      mode,
      name,
      symbol,
      amount,
      order_id,
      number: ""
    };
    dispatch((0, import_store2.updateState)((0, import_manufacturer.getInitState)(eftpos, _params)));
  };
  const onTransactionComplete = (element) => {
    var _a, _b, _c;
    const { paymentStatus, response, merchantReceipt, customerReceipt } = element._extra || {};
    if (paymentStatus === import_types.EPaymentStatus.Success) {
      const receipt = [];
      const card_reader_surcharge = ((_b = (_a = response == null ? void 0 : response.data) == null ? void 0 : _a.external_unified_response) == null ? void 0 : _b.external_service_fee) || 0;
      const deviceSetting = (_c = deviceRef.current) == null ? void 0 : _c.setting;
      const shouldPrintMerchantReceiptOnPos = shouldPrintReceiptOnPos(
        deviceSetting == null ? void 0 : deviceSetting.print_merchant_receipt
      );
      const shouldPrintCustomerReceiptOnPos = shouldPrintReceiptOnPos(
        deviceSetting == null ? void 0 : deviceSetting.prompt_customer_receipt
      );
      if (shouldPrintMerchantReceiptOnPos && merchantReceipt) {
        receipt.push(merchantReceipt);
      }
      if (shouldPrintCustomerReceiptOnPos && customerReceipt) {
        receipt.push(customerReceipt);
      }
      const params = (0, import_helper.getPayParams)(
        {
          mode: modeRef.current,
          amount: amountRef.current,
          order_id: orderIdRef.current,
          number: numRef.current,
          device: deviceRef.current,
          pay: payRef.current,
          custom: {
            card_reader_surcharge,
            receipt
          }
        },
        "success"
      );
      onChange("success", { ...params, receipt });
    } else {
      onChange("fail", {
        order_id: orderIdRef.current,
        number: numRef.current,
        uniquePaymentNumber: numRef.current,
        device: deviceRef.current
      });
    }
  };
  const onSubmitToAPI = (element, extra) => {
    const inputValues = (extra == null ? void 0 : extra.inputValues) || {};
    payment.action(
      { submit_url: element == null ? void 0 : element.submitUrl, payload: { ...inputValues } },
      { needResponse: true }
    );
  };
  const onNormalClick = (element, config) => {
    if (element == null ? void 0 : element.submitUrl) {
      console.log("onNormalClick_submit_url", element == null ? void 0 : element.submitUrl);
      payment.action({ submit_url: element == null ? void 0 : element.submitUrl }, config);
    } else {
      console.log("onNormalClick_no_submit_url", element);
    }
  };
  const shouldLockElementClick = (element) => {
    const lockKeys = [
      import_types2.EButtonKeyType.DeclineSignature,
      import_types2.EButtonKeyType.ApproveSignature,
      import_types2.EButtonKeyType.RetryTransaction,
      import_types2.EButtonKeyType.SubmitToAPI,
      import_types2.EButtonKeyType.CallTestFunction
    ];
    return lockKeys.includes(element.key);
  };
  const lockElementClick = () => {
    clickLockedRef.current = true;
    clickUnlockTimerRef.current = setTimeout(() => {
      clickLockedRef.current = false;
      clickUnlockTimerRef.current = null;
    }, 1e3);
  };
  const onElementClick = (element, extra) => {
    if (shouldLockElementClick(element)) {
      if (clickLockedRef.current) {
        import_payLog.default.log(`忽略重复点击${(element == null ? void 0 : element.key) || "未知"}按钮`);
        return;
      }
      lockElementClick();
      dispatch((0, import_store2.updateCustom)({ customAction: {} }));
      updateToLoading();
    }
    console.log("onElementClick", element, extra);
    import_payLog.default.log(`点击${(element == null ? void 0 : element.key) || "未知"}按钮`);
    switch (element.key) {
      case import_types2.EButtonKeyType.CancelTransaction:
        onCancel(element);
        break;
      case import_types2.EButtonKeyType.DeclineSignature:
        onDecline(element);
        break;
      case import_types2.EButtonKeyType.ApproveSignature:
        onAccept(element);
        break;
      case import_types2.EButtonKeyType.PrintMerchantReceipt:
        onPrintMerchantReceipt(element);
        break;
      case import_types2.EButtonKeyType.PrintCustomerReceipt:
        onPrintCustomerReceipt(element);
        break;
      case import_types2.EButtonKeyType.RetryTransaction:
        onRetry(element);
        break;
      case import_types2.EButtonKeyType.TransactionComplete:
        onTransactionComplete(element);
        break;
      case import_types2.EButtonKeyType.SubmitToAPI:
        onSubmitToAPI(element, extra);
        break;
      case import_types2.EButtonKeyType.CallTestFunction:
        (0, import_materials.PisellToast)({ content: "Test" });
        break;
      default:
        onNormalClick(element);
        break;
    }
  };
  const onCloseReceiptModal = () => {
    setReceiptModalShow(false);
    setReceiptModalData(null);
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, status === import_const.StatusEnum.Question ? /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__eft-pay-title",
      style: { textAlign: "center" }
    },
    title
  ) : null, status !== import_const.StatusEnum.Success ? /* @__PURE__ */ import_react.default.createElement(
    import_Action.default,
    {
      data: custom == null ? void 0 : custom.customAction,
      onClick: onElementClick,
      cancelDisabled,
      isLoading: status === import_const.StatusEnum.Loading
    }
  ) : null), receiptModalShow ? /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open: receiptModalShow,
      onCancel: onCloseReceiptModal,
      maskClosable: true,
      footer: null
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          padding: "16px",
          display: "flex",
          alignItems: "center",
          justifyContent: "center"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        "span",
        {
          style: {
            display: "inline-block",
            whiteSpace: "pre-wrap",
            fontFamily: "monospace",
            backgroundColor: "#fff"
          }
        },
        receiptModalData
      )
    )
  ) : null);
};
var mx51_default = AggregatePayment;
