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_ahooks = require("ahooks");
var import_priceKeyboard = require("../../../../pro/priceKeyboard");
var import_index = require("./index.less");
function CashPaymentModule({
  amountSymbol,
  orderInfo,
  onPaymentComplete,
  customAmount,
  amountButtons = [],
  // 按钮列表，默认5个推荐金额
  disabled = false,
  // 禁用状态
  roundingFunction,
  balanceDueAmount = "0",
  // 当前阶段剩余支付金额（定金或普通支付）
  balanceDueTotalAmount = "0",
  // 完整订单剩余待付金额
  syncingLock = false,
  // 是否锁定
  shortcutsSize = "default"
  // 预设大小
}) {
  const [amount, setAmount] = (0, import_react.useState)(customAmount || "");
  const [roundingAmount, setRoundingAmount] = (0, import_react.useState)(0);
  const [roundingBaseInfo, setRoundingBaseInfo] = (0, import_react.useState)({
    orderBaseAmount: 0,
    roundedBaseAmount: 0,
    orderRoundingAmount: 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, _j;
    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 = (_j = (_i = import_locales.default) == null ? void 0 : _i[currentLang]) == null ? void 0 : _j[key];
    if (checkoutText) {
      return checkoutText;
    }
    return import_utils.locales.getText(key) || fallback;
  };
  const orderBaseAmount = (0, import_react.useMemo)(() => {
    const baseAmount = parseFloat(
      (orderInfo == null ? void 0 : orderInfo.isDeposit) ? balanceDueTotalAmount || "0" : balanceDueAmount || "0"
    );
    return Number.isFinite(baseAmount) ? baseAmount : 0;
  }, [orderInfo == null ? void 0 : orderInfo.isDeposit, balanceDueAmount, balanceDueTotalAmount]);
  const isAmountButtonsDisabled = disabled || orderBaseAmount <= 0;
  const isInputDisabled = disabled || orderBaseAmount <= 0;
  const shouldKeepOrderRounding = (inputAmount, baseInfo) => {
    const targetBaseInfo = baseInfo || roundingBaseInfo;
    if (Math.abs(targetBaseInfo.orderRoundingAmount) === 0) return false;
    return inputAmount >= targetBaseInfo.roundedBaseAmount - 1e-6;
  };
  const parseInputAmount = (value) => {
    const finalValue = String(value ?? "").trim();
    if (!finalValue) {
      return {
        isEmpty: true,
        isInvalid: false,
        amountValue: 0
      };
    }
    const cleanValue = finalValue.replace(/[$\s]/g, "");
    const amountValue = parseFloat(cleanValue);
    if (!Number.isFinite(amountValue)) {
      return {
        isEmpty: false,
        isInvalid: true,
        amountValue: 0
      };
    }
    return {
      isEmpty: false,
      isInvalid: false,
      amountValue
    };
  };
  const getDisplayedAmount = (inputAmount, baseInfo) => {
    const targetBaseInfo = baseInfo || roundingBaseInfo;
    const shouldUseRoundedValue = shouldKeepOrderRounding(inputAmount, targetBaseInfo) && Math.abs(inputAmount - targetBaseInfo.orderBaseAmount) < 0.01;
    return shouldUseRoundedValue ? targetBaseInfo.roundedBaseAmount : inputAmount;
  };
  const applyInputAmount = (value, options) => {
    const {
      showZeroToast = false,
      baseInfo,
      preserveDecimalInput = true
    } = options || {};
    const targetBaseInfo = baseInfo || roundingBaseInfo;
    const finalValue = String(value ?? "").trim();
    const cleanValue = finalValue.replace(/[$\s]/g, "");
    const shouldKeepInputDecimalInput = preserveDecimalInput && /^\d+\.\d{0,2}$/.test(cleanValue);
    const parsedAmount = parseInputAmount(value);
    if (parsedAmount.isEmpty) {
      setAmount("");
      setRoundingAmount(0);
      return;
    }
    if (parsedAmount.isInvalid) {
      setAmount("");
      setRoundingAmount(0);
      return;
    }
    if (showZeroToast && parsedAmount.amountValue === 0) {
      Toast.fail(
        getText("cash-payment-amount-cannot-be-zero", "The amount cannot be 0")
      );
      return;
    }
    const effectiveRoundingAmount = shouldKeepOrderRounding(
      parsedAmount.amountValue,
      targetBaseInfo
    ) ? targetBaseInfo.orderRoundingAmount : 0;
    const displayedAmount = getDisplayedAmount(parsedAmount.amountValue, targetBaseInfo);
    const nextAmount = shouldKeepInputDecimalInput ? cleanValue : displayedAmount.toString();
    setAmount(nextAmount);
    setRoundingAmount(effectiveRoundingAmount);
  };
  (0, import_react.useEffect)(() => {
    let isCancelled = false;
    const syncRoundingBaseInfo = async () => {
      let roundedBaseAmount = orderBaseAmount;
      let orderRoundingAmount = 0;
      if (roundingFunction && orderBaseAmount > 0) {
        try {
          const result = await roundingFunction(orderBaseAmount);
          roundedBaseAmount = (result == null ? void 0 : result.roundedAmount) ?? orderBaseAmount;
          orderRoundingAmount = (result == null ? void 0 : result.roundingDifference) ?? 0;
        } catch (error) {
          console.warn("Failed to calculate cash rounding amount:", error);
          roundedBaseAmount = orderBaseAmount;
          orderRoundingAmount = 0;
        }
      }
      const nextBaseInfo = {
        orderBaseAmount,
        roundedBaseAmount,
        orderRoundingAmount
      };
      if (isCancelled) return;
      setRoundingBaseInfo(nextBaseInfo);
      if (isInputDisabled) {
        setAmount("0.00");
        setRoundingAmount(0);
        return;
      }
      const nextInputAmount = Number(customAmount || 0) > 0 ? customAmount ?? "" : String(nextBaseInfo.roundedBaseAmount || nextBaseInfo.orderBaseAmount || "");
      applyInputAmount(nextInputAmount, {
        baseInfo: nextBaseInfo,
        preserveDecimalInput: false
      });
    };
    syncRoundingBaseInfo();
    return () => {
      isCancelled = true;
    };
  }, [
    customAmount,
    balanceDueAmount,
    balanceDueTotalAmount,
    orderInfo == null ? void 0 : orderInfo.isDeposit,
    roundingFunction,
    isInputDisabled,
    orderBaseAmount
  ]);
  const handleAmountClick = (clickedAmount) => {
    if (isAmountButtonsDisabled) return;
    const amountStr = clickedAmount.toString();
    setAmount(amountStr);
    setRoundingAmount(0);
  };
  const handleCashPayInternal = () => {
    if (isAmountButtonsDisabled) return;
    if (onPaymentComplete) {
      const finalAmount = typeof amount === "number" ? amount : Number(amount) || 0;
      const effectiveRoundingAmount = shouldKeepOrderRounding(finalAmount) ? roundingBaseInfo.orderRoundingAmount : 0;
      if (finalAmount === 0 && Math.abs(effectiveRoundingAmount) === 0) {
        Toast.fail(
          getText(
            "cash-payment-amount-cannot-be-zero",
            "The amount cannot be 0"
          )
        );
        return;
      }
      const effectiveBaseAmount = Number(roundingBaseInfo.orderBaseAmount) + Number(effectiveRoundingAmount);
      onPaymentComplete({
        type: "CASHMANUAL",
        amount: finalAmount,
        totalAmount: Number(customAmount) || 0,
        change: Number(finalAmount) - Number(effectiveBaseAmount),
        roundingAmount: effectiveRoundingAmount
      });
    }
  };
  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;
    }
    applyInputAmount(value, { showZeroToast: true });
  };
  const handleReset = async () => {
    if (isAmountButtonsDisabled) return;
    const displayedResetAmount = Math.abs(roundingBaseInfo.orderRoundingAmount) > 0 ? roundingBaseInfo.roundedBaseAmount : roundingBaseInfo.orderBaseAmount;
    setAmount(displayedResetAmount.toString());
    setRoundingAmount(roundingBaseInfo.orderRoundingAmount);
  };
  const currentInputAmount = Number(amount) || 0;
  const shouldUseRoundedBase = shouldKeepOrderRounding(currentInputAmount);
  const keyboardOriginalValue = shouldUseRoundedBase ? String(roundingBaseInfo.roundedBaseAmount) : customAmount;
  const normalizedAmountButtons = amountButtons.slice(0, 5).map((buttonAmount) => {
    const displayedAmount = getDisplayedAmount(buttonAmount);
    return {
      label: (0, import_utils.formatAmount)(displayedAmount, 2, amountSymbol),
      value: displayedAmount
    };
  });
  return /* @__PURE__ */ import_react.default.createElement(
    import_priceKeyboard.CashKeyboard,
    {
      variant: "intact",
      originalValue: keyboardOriginalValue,
      value: amount,
      disabled,
      onChange: (value) => {
        applyInputAmount(value);
      },
      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: normalizedAmountButtons,
      onReset: handleReset,
      onEnter: syncingLock ? void 0 : handleCashPay,
      shortcutsSize
    }
  );
}
var CashPaymentModule_default = CashPaymentModule;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CashPaymentModule
});
