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/pro/priceKeyboard/components/paymentKeyboard/index.tsx
var paymentKeyboard_exports = {};
__export(paymentKeyboard_exports, {
  PaymentKeyboard: () => PaymentKeyboard,
  default: () => paymentKeyboard_default
});
module.exports = __toCommonJS(paymentKeyboard_exports);
var import_react = __toESM(require("react"));
var import_decimal = __toESM(require("decimal.js"));
var import_utils = require("@pisell/utils");
var import_lodash = require("lodash");
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_rightItems = __toESM(require("../../hooks/rightItems"));
var import_keyActions = __toESM(require("../../hooks/keyActions"));
var import_ahooks = require("ahooks");
var import_locales = __toESM(require("./locales"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_utils2 = require("../../utils");
var import_index = require("./index.less");
var KEYS = {
  PAYMENT: "payment",
  SURCHARGE: "surcharge",
  PERCENT: "percent",
  FIXED: "fixed"
};
var defaultConfig = {
  payment: {
    enable: true
  },
  surcharge: {
    enable: true
  }
};
var PaymentKeyboardBase = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const context = (0, import_useEngineContext.default)();
  const { getData } = context.appHelper.utils;
  const amountSymbol = props.amountSymbol || (getData == null ? void 0 : getData("shop_symbol")) || "$";
  import_utils.locales.init(
    import_locales.default,
    ((_e = (_d = (_c = (_b = (_a = context.appHelper.utils) == null ? void 0 : _a.getApp) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.locales) == null ? void 0 : _d.getLocale) == null ? void 0 : _e.call(_d)) || ((_g = (_f = context.appHelper.utils) == null ? void 0 : _f.storage) == null ? void 0 : _g.get("umi_locale")) || "en"
  );
  const {
    enableExceedMaxAmount = false,
    paymentOriginalValue,
    surchargeDefaultValue,
    doneText,
    resetText,
    onReset,
    onPay,
    selectType = "light"
  } = props;
  const uniqueId = (0, import_react.useId)();
  const uniqueKeyboardId = `virtual-keyboard-${uniqueId.replace(/:/g, "-")}`;
  (0, import_react.useEffect)(() => {
    (0, import_utils2.setKeyboardTheme)(selectType);
  }, [selectType]);
  const [activeKey, setActiveKey] = (0, import_react.useState)(() => {
    var _a2, _b2;
    if ((_a2 = props.payment) == null ? void 0 : _a2.enable) {
      return KEYS.PAYMENT;
    }
    if ((_b2 = props.surcharge) == null ? void 0 : _b2.enable) {
      return KEYS.SURCHARGE;
    }
    return KEYS.PAYMENT;
  });
  const [focusedInput, setFocusedInput] = (0, import_react.useState)(KEYS.PERCENT);
  const [internalPaymentValue, setInternalPaymentValue] = (0, import_ahooks.useControllableValue)(props, {
    defaultValuePropName: "paymentDefaultValue",
    valuePropName: "paymentValue"
  });
  const [internalSurchargeValue, setInternalSurchargeValue] = (0, import_ahooks.useControllableValue)(props, {
    defaultValue: surchargeDefaultValue || {
      percent: "",
      fixed: ""
    },
    valuePropName: "surchargeValue"
  });
  const [firstInputStatus, setFirstInputStatus] = (0, import_react.useState)({
    [KEYS.PAYMENT]: true,
    [KEYS.PERCENT]: true,
    [KEYS.FIXED]: true
  });
  const _onReset = (0, import_react.useCallback)(() => {
    if (activeKey === KEYS.PAYMENT) {
      setInternalPaymentValue(paymentOriginalValue || "");
      setFirstInputStatus((prev) => ({
        ...prev,
        [KEYS.PAYMENT]: true
      }));
    } else if (activeKey === KEYS.SURCHARGE) {
      if (focusedInput === KEYS.PERCENT) {
        setInternalSurchargeValue({
          ...internalSurchargeValue || {},
          percent: (surchargeDefaultValue == null ? void 0 : surchargeDefaultValue.percent) || ""
        });
        setFirstInputStatus((prev) => ({
          ...prev,
          [KEYS.PERCENT]: true
        }));
      } else {
        setInternalSurchargeValue({
          ...internalSurchargeValue || {},
          fixed: (surchargeDefaultValue == null ? void 0 : surchargeDefaultValue.fixed) || ""
        });
        setFirstInputStatus((prev) => ({
          ...prev,
          [KEYS.FIXED]: true
        }));
      }
    }
    onReset == null ? void 0 : onReset();
  }, [
    activeKey,
    onReset,
    focusedInput,
    paymentOriginalValue,
    surchargeDefaultValue
  ]);
  const currentValue = (0, import_react.useMemo)(() => {
    if (activeKey === KEYS.PAYMENT) {
      return internalPaymentValue;
    }
    if (activeKey === KEYS.SURCHARGE) {
      if (focusedInput === KEYS.FIXED) {
        return (internalSurchargeValue || {}).fixed || "";
      }
      return (internalSurchargeValue || {}).percent || "";
    }
    return "";
  }, [activeKey, focusedInput, internalPaymentValue, internalSurchargeValue]);
  const _max = (0, import_react.useMemo)(() => {
    if (activeKey === KEYS.SURCHARGE && focusedInput === KEYS.PERCENT) {
      return 100;
    }
    return void 0;
  }, [activeKey, focusedInput]);
  const _mode = (0, import_react.useMemo)(() => {
    if (activeKey === KEYS.PAYMENT) {
      return firstInputStatus.payment ? "replace" : "append";
    } else {
      return firstInputStatus[focusedInput] ? "replace" : "append";
    }
  }, [firstInputStatus, activeKey, focusedInput]);
  const { handleChange } = (0, import_keyActions.default)({
    onEnter: () => {
      if (!enableExceedMaxAmount && new import_decimal.default(internalPaymentValue).greaterThan(maxAmount)) {
        return;
      }
      onPay == null ? void 0 : onPay({
        surcharge: internalSurchargeValue,
        amount: internalPaymentValue
      });
    },
    onReset: _onReset,
    onChange: (v) => {
      if (activeKey === KEYS.PAYMENT) {
        setInternalPaymentValue(v);
        setFirstInputStatus((prev) => ({
          ...prev,
          [KEYS.PAYMENT]: false
        }));
      } else if (activeKey === KEYS.SURCHARGE) {
        if (focusedInput === KEYS.FIXED) {
          setInternalSurchargeValue({
            ...internalSurchargeValue || {},
            fixed: v
          });
          setFirstInputStatus((prev) => ({
            ...prev,
            [KEYS.FIXED]: false
          }));
        } else {
          setInternalSurchargeValue({
            ...internalSurchargeValue || {},
            percent: v
          });
          setFirstInputStatus((prev) => ({
            ...prev,
            [KEYS.PERCENT]: false
          }));
        }
      }
    },
    max: _max,
    value: currentValue,
    scale: 2,
    mode: _mode
  });
  const rightItems = (0, import_rightItems.default)({
    rightItemsStyle: {},
    doneText: doneText || import_utils.locales.getText("payment-keyboard-pay"),
    resetText: resetText || import_utils.locales.getText("payment-keyboard-reset")
  });
  const mergedConfig = (0, import_react.useMemo)(() => {
    return (0, import_lodash.merge)({}, defaultConfig, (0, import_lodash.pick)(props, ["payment", "surcharge"]));
  }, [props]);
  const options = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    const opts = [];
    if ((_a2 = mergedConfig.payment) == null ? void 0 : _a2.enable) {
      opts.push({
        label: import_utils.locales.getText("payment-keyboard-payment"),
        value: KEYS.PAYMENT
      });
    }
    if ((_b2 = mergedConfig.surcharge) == null ? void 0 : _b2.enable) {
      opts.push({
        label: import_utils.locales.getText("payment-keyboard-surcharge"),
        value: KEYS.SURCHARGE
      });
    }
    return opts;
  }, [mergedConfig]);
  const amountFormatter = (amount) => {
    if (amount === "" || amount === void 0) {
      return "";
    }
    return `${amountSymbol}${amount}`;
  };
  const maxAmount = props.paymentOriginalValue || 0;
  const surchargeFee = (0, import_react.useMemo)(() => {
    return new import_decimal.default(internalPaymentValue || 0).mul(new import_decimal.default((internalSurchargeValue == null ? void 0 : internalSurchargeValue.percent) || 0).div(100)).plus(new import_decimal.default((internalSurchargeValue == null ? void 0 : internalSurchargeValue.fixed) || 0)).toNumber();
  }, [internalPaymentValue, internalSurchargeValue]);
  const totalAmountDue = (0, import_react.useMemo)(() => {
    return new import_decimal.default(internalPaymentValue || 0).plus(new import_decimal.default(surchargeFee || 0)).toNumber();
  }, [internalPaymentValue, surchargeFee]);
  const remainingAmount = (0, import_react.useMemo)(() => {
    return new import_decimal.default(maxAmount || 0).minus(new import_decimal.default(internalPaymentValue || 0)).toNumber();
  }, [maxAmount, internalPaymentValue]);
  const renderBottomContent = () => {
    if (enableExceedMaxAmount) {
      if (new import_decimal.default(remainingAmount).lessThan(0)) {
        return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-input-tip ellipsis" }, import_utils.locales.getText("payment-keyboard-change-due"), ":", " ", /* @__PURE__ */ import_react.default.createElement(
          import_materials.PisellText.Amount,
          {
            hideDecimalForWholeNumbers: false,
            precision: 2,
            value: Math.abs(remainingAmount)
          }
        ));
      } else {
        return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-input-tip ellipsis" }, import_utils.locales.getText("payment-keyboard-remaining"), ":", " ", /* @__PURE__ */ import_react.default.createElement(
          import_materials.PisellText.Amount,
          {
            hideDecimalForWholeNumbers: false,
            precision: 2,
            value: remainingAmount
          }
        ));
      }
    } else {
      return (
        // 不允许输入金额超过最大金额
        /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-input-tip" }, /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            style: {
              color: remainingAmount < 0 ? "#F04438" : "#475467"
            }
          },
          import_utils.locales.getText("payment-keyboard-max"),
          ":",
          " ",
          /* @__PURE__ */ import_react.default.createElement(
            import_materials.PisellText.Amount,
            {
              hideDecimalForWholeNumbers: false,
              precision: 2,
              value: maxAmount
            }
          )
        ), " ", "( ", import_utils.locales.getText("payment-keyboard-remaining"), ":", " ", /* @__PURE__ */ import_react.default.createElement(
          import_materials.PisellText.Amount,
          {
            hideDecimalForWholeNumbers: false,
            precision: 2,
            value: Math.max(remainingAmount, 0)
          }
        ), " ", ")")
      );
    }
  };
  const renderPaymentDisplay = () => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_materials.VirtualInput,
      {
        focused: true,
        value: amountFormatter(internalPaymentValue),
        wrapperStyle: {
          width: "100%",
          backgroundColor: "#ffffff",
          borderRadius: 8,
          padding: 16
        },
        bottomContent: renderBottomContent(),
        preventBlurElements: [uniqueKeyboardId],
        selected: firstInputStatus.payment && !!internalPaymentValue
      }
    );
  };
  const renderSurchargeDisplay = () => {
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          display: "grid",
          gridTemplateColumns: "1fr auto 1fr",
          gap: 8,
          alignItems: "center"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.VirtualInput,
        {
          focused: focusedInput !== KEYS.FIXED,
          value: (internalSurchargeValue == null ? void 0 : internalSurchargeValue.percent) ? `${internalSurchargeValue == null ? void 0 : internalSurchargeValue.percent}%` : "",
          wrapperStyle: {
            backgroundColor: "#ffffff",
            borderRadius: 8,
            padding: 20
          },
          placeholder: import_utils.locales.getText("payment-keyboard-percent"),
          style: {
            justifyContent: "center"
          },
          onFocus: () => setFocusedInput(KEYS.PERCENT),
          preventBlurElements: [uniqueKeyboardId],
          selected: firstInputStatus.percent && !!(internalSurchargeValue == null ? void 0 : internalSurchargeValue.percent) && focusedInput !== KEYS.FIXED
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            color: "#667085",
            fontSize: 36,
            fontWeight: 600
          }
        },
        "+"
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.VirtualInput,
        {
          focused: focusedInput === KEYS.FIXED,
          value: amountFormatter((internalSurchargeValue == null ? void 0 : internalSurchargeValue.fixed) ?? ""),
          wrapperStyle: {
            backgroundColor: "#ffffff",
            borderRadius: 8,
            padding: 20
          },
          placeholder: import_utils.locales.getText("payment-keyboard-fixed"),
          style: {
            justifyContent: "center"
          },
          onFocus: () => setFocusedInput(KEYS.FIXED),
          preventBlurElements: [uniqueKeyboardId],
          selected: firstInputStatus.fixed && !!(internalSurchargeValue == null ? void 0 : internalSurchargeValue.fixed) && focusedInput === KEYS.FIXED
        }
      )
    );
  };
  const customDisplay = () => {
    if (activeKey === KEYS.PAYMENT) {
      return renderPaymentDisplay();
    }
    if (activeKey === KEYS.SURCHARGE) {
      return renderSurchargeDisplay();
    }
    return null;
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-payment-container" }, (options == null ? void 0 : options.length) > 1 ? /* @__PURE__ */ import_react.default.createElement(
    import_antd.Segmented,
    {
      size: "large",
      style: {
        padding: 6
      },
      block: true,
      options,
      value: activeKey,
      onChange: (value) => setActiveKey(value.toString())
    }
  ) : null, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-title ellipsis" }, import_utils.locales.getText("payment-keyboard-total-amount-due"), ":", " ", /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellText.Amount,
    {
      hideDecimalForWholeNumbers: false,
      precision: 2,
      value: totalAmountDue
    }
  )), ((_h = mergedConfig.surcharge) == null ? void 0 : _h.enable) ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-subtitle ellipsis" }, import_utils.locales.getText("payment-keyboard-inc-surcharge"), ":", " ", /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellText.Amount,
    {
      hideDecimalForWholeNumbers: false,
      precision: 2,
      value: surchargeFee
    }
  ), " ", "(", (internalSurchargeValue == null ? void 0 : internalSurchargeValue.percent) || "0", "% +", " ", /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellText.Amount,
    {
      hideDecimalForWholeNumbers: false,
      precision: 2,
      value: (internalSurchargeValue == null ? void 0 : internalSurchargeValue.fixed) || 0
    }
  ), ")") : null), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-payment" }, activeKey && customDisplay(), /* @__PURE__ */ import_react.default.createElement(
    import_materials.Keyboard,
    {
      rightItems,
      onChange: handleChange,
      id: uniqueKeyboardId
    }
  )));
};
var PaymentKeyboard = (props) => {
  const { containerProps, children, ...keyboardProps } = props;
  const { renderType, open, ...restProps } = containerProps || {};
  if (!containerProps) {
    return /* @__PURE__ */ import_react.default.createElement(PaymentKeyboardBase, { ...keyboardProps });
  }
  if (renderType === "popover") {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.Popover,
      {
        key: `${open}`,
        open,
        trigger: "click",
        className: "pisell-payment-keyboard-container pisell-payment-keyboard-popover",
        ...restProps,
        content: /* @__PURE__ */ import_react.default.createElement(PaymentKeyboardBase, { ...keyboardProps })
      },
      children
    );
  }
  if (renderType === "modal") {
    return open ? /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellModal,
      {
        platform: "pc",
        open: true,
        width: "unset",
        header: null,
        footer: false,
        mask: false,
        maskClosable: true,
        bodyStyle: { padding: "0px", backgroundColor: "transparent" },
        closeIcon: null,
        className: "pisell-payment-keyboard-container pisell-payment-keyboard-modal",
        destroyOnHidden: true,
        ...restProps
      },
      /* @__PURE__ */ import_react.default.createElement(PaymentKeyboardBase, { ...keyboardProps })
    ) : null;
  }
  return /* @__PURE__ */ import_react.default.createElement(PaymentKeyboardBase, { ...keyboardProps });
};
var paymentKeyboard_default = PaymentKeyboard;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PaymentKeyboard
});
