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/checkout/components/CashPaymentModule/index.tsx
var CashPaymentModule_exports = {};
__export(CashPaymentModule_exports, {
  CashPaymentModule: () => CashPaymentModule,
  default: () => CashPaymentModule_default
});
module.exports = __toCommonJS(CashPaymentModule_exports);
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_utils = require("@pisell/utils");
var import_locales = __toESM(require("../../locales"));
var import_useToast = __toESM(require("../../../../hooks/useToast"));
var import_priceKeyboard = require("../../../../pro/priceKeyboard");
var import_ahooks = require("ahooks");
var import_index = require("./index.less");
function CashPaymentModule({
  amountSymbol,
  orderInfo,
  onPaymentComplete,
  customAmount,
  amountButtons = [],
  // 按钮列表，默认5个推荐金额
  disabled = false,
  // 禁用状态
  roundingFunction,
  balanceDueAmount = "0",
  // 剩余支付金额
  syncingLock = false
  // 是否锁定
}) {
  const [amount, setAmount] = (0, import_react.useState)(customAmount || "");
  const [roundingAmount, setRoundingAmount] = (0, import_react.useState)(0);
  const context = (0, import_useEngineContext.default)();
  const Toast = (0, import_useToast.default)();
  const getText = (key, fallback) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i;
    const currentLang = ((_f = (_e = (_d = (_c = (_b = (_a = context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b)) == null ? void 0 : _d.locales) == null ? void 0 : _e.getLocale) == null ? void 0 : _f.call(_e)) || ((_h = (_g = context.appHelper.utils) == null ? void 0 : _g.storage) == null ? void 0 : _h.get("umi_locale")) || "en";
    const checkoutText = (_i = import_locales.default[currentLang]) == null ? void 0 : _i[key];
    if (checkoutText) {
      return checkoutText;
    }
    return import_utils.locales.getText(key) || fallback;
  };
  (0, import_react.useEffect)(() => {
    handleKeyboardConfirm(customAmount || "");
  }, [customAmount, balanceDueAmount]);
  const isAmountButtonsDisabled = disabled || Number(customAmount || 0) === 0;
  const isInputDisabled = disabled || Number(customAmount || 0) === 0;
  const handleCashPayInternal = () => {
    if (isAmountButtonsDisabled) return;
    if (onPaymentComplete) {
      if (Number(amount) === 0 && Math.abs(roundingAmount) === 0) {
        Toast.fail(
          getText(
            "cash-payment-amount-cannot-be-zero",
            "The amount cannot be 0"
          )
        );
        return;
      }
      const finalAmount = typeof amount === "number" ? amount : Number(amount) || 0;
      onPaymentComplete({
        type: "CASHMANUAL",
        amount: finalAmount,
        totalAmount: Number(customAmount) || 0,
        change: finalAmount - (Number(customAmount) || 0),
        roundingAmount
      });
    }
  };
  const { run: handleCashPay } = (0, import_ahooks.useDebounceFn)(handleCashPayInternal, {
    wait: 500,
    leading: true,
    trailing: false
  });
  const handleKeyboardConfirm = async (value) => {
    if (isInputDisabled) {
      setAmount("0.00");
      setRoundingAmount(0);
      return;
    }
    const finalValue = String(value);
    console.log("键盘确认:", finalValue);
    if (Number(finalValue) === 0) {
      Toast.fail(
        getText("cash-payment-amount-cannot-be-zero", "The amount cannot be 0")
      );
      return;
    }
    if (finalValue === "" || finalValue === null || finalValue === void 0) {
      setAmount("");
    } else {
      const cleanValue = finalValue.replace(/[$\s]/g, "");
      const numValue = parseFloat(cleanValue);
      const balanceDue = parseFloat(balanceDueAmount);
      const shouldApplyRounding = Math.abs(numValue - balanceDue) < 0.01;
      let finalAmount = numValue;
      let roundingDiff = 0;
      if (shouldApplyRounding && roundingFunction) {
        const result = await roundingFunction(numValue);
        const { roundedAmount = numValue, roundingDifference = 0 } = result || {};
        finalAmount = roundedAmount;
        roundingDiff = roundingDifference;
        console.log(
          "应用抹零：",
          numValue,
          "->",
          roundedAmount,
          "差额:",
          roundingDifference
        );
      } else {
        console.log(
          "不应用抹零，用户输入金额:",
          numValue,
          "剩余支付金额:",
          balanceDue
        );
      }
      setRoundingAmount(roundingDiff);
      if (isNaN(numValue)) {
        setAmount("");
      } else {
        setAmount(finalAmount.toString());
        console.log("设置金额为:", finalAmount);
      }
    }
  };
  const handleReset = async () => {
    if (isAmountButtonsDisabled) return;
    const resetAmount = balanceDueAmount || "0";
    const cleanValue = resetAmount.replace(/[$\s]/g, "");
    const numValue = parseFloat(cleanValue);
    const balanceDue = parseFloat(balanceDueAmount);
    const shouldApplyRounding = Math.abs(numValue - balanceDue) < 0.01;
    let finalAmount = numValue;
    let roundingDiff = 0;
    if (shouldApplyRounding && roundingFunction) {
      const result = await roundingFunction(finalAmount);
      const { roundedAmount = numValue, roundingDifference = 0 } = result || {};
      finalAmount = roundedAmount;
      roundingDiff = roundingDifference;
      console.log(
        "应用抹零：",
        numValue,
        "->",
        roundedAmount,
        "差额:",
        roundingDifference
      );
    } else {
      console.log(
        "不应用抹零，用户输入金额:",
        numValue,
        "剩余支付金额:",
        balanceDue
      );
    }
    setAmount(finalAmount.toString());
    setRoundingAmount(roundingDiff);
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_priceKeyboard.CashKeyboard,
    {
      variant: "intact",
      originalValue: customAmount,
      value: amount,
      disabled,
      hiddenChangeDue: roundingAmount > 0,
      onChange: (value) => {
        setAmount(value);
        setRoundingAmount(0);
      },
      titleArea: {
        visible: true,
        title: {
          text: getText("cash-payment-title", "Cash Payment")
        },
        subtitle: {
          visible: Math.abs(roundingAmount) > 0,
          text: `${getText(
            "cash-payment-rounding",
            "Rounding"
          )}: ${(0, import_utils.formatAmount)(roundingAmount, 2, amountSymbol)}`
        }
      },
      style: {
        width: "100%",
        backgroundColor: "transparent"
      },
      presets: amountButtons.slice(0, 5).map((buttonAmount) => {
        return {
          label: (0, import_utils.formatAmount)(buttonAmount, 2, amountSymbol),
          value: buttonAmount
        };
      }),
      onReset: handleReset,
      onEnter: syncingLock ? void 0 : handleCashPay
    }
  );
}
var CashPaymentModule_default = CashPaymentModule;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CashPaymentModule
});
