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/discountKeyboard/index.tsx
var discountKeyboard_exports = {};
__export(discountKeyboard_exports, {
  default: () => discountKeyboard_default
});
module.exports = __toCommonJS(discountKeyboard_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_decimal = __toESM(require("decimal.js"));
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_rightItems = __toESM(require("../../hooks/rightItems"));
var import_keyActions = __toESM(require("../../hooks/keyActions"));
var import_utils2 = require("../../utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var TIP_COLORS = {
  positive: "#CA8504",
  negative: "#1570EF",
  overflow: "#D92D20"
};
var DiscountKeyboardBase = (props) => {
  var _a, _b, _c, _d, _e, _f, _g;
  const {
    defaultValue,
    originalValue,
    selectType = "light",
    resetText,
    doneText,
    onEnter,
    onReset,
    enableExceedMaxAmount = false
  } = props;
  const context = (0, import_useEngineContext.default)();
  const [isFirstInput, setIsFirstInput] = (0, import_react.useState)(true);
  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 { getData } = context.appHelper.utils;
  const amountSymbol = props.amountSymbol || (getData == null ? void 0 : getData("shop_symbol")) || "$";
  const uniqueId = (0, import_react.useId)();
  const uniqueKeyboardId = `virtual-keyboard-${uniqueId.replace(/:/g, "-")}`;
  const [updateMode, setUpdateMode] = (0, import_react.useState)(
    "priceOverride"
  );
  const [discountMode, setDiscountMode] = (0, import_react.useState)(
    "amount"
  );
  const [internalValue, setInternalValue] = (0, import_react.useState)(
    defaultValue ? String(defaultValue) : ""
  );
  const [discountValue, setDiscountValue] = (0, import_react.useState)("");
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
  }, []);
  (0, import_react.useEffect)(() => {
    (0, import_utils2.setKeyboardTheme)(selectType);
  }, [selectType]);
  const _onReset = (0, import_react.useCallback)(() => {
    if (updateMode === "priceOverride") {
      setInternalValue(originalValue ? String(originalValue) : "");
      setIsFirstInput(true);
    } else {
      setDiscountValue("");
    }
    onReset == null ? void 0 : onReset();
  }, [originalValue, onReset, updateMode]);
  const _handleChange = (0, import_react.useCallback)(
    (val) => {
      if (updateMode === "priceOverride") {
        setIsFirstInput(false);
        setInternalValue(val);
      } else {
        setDiscountValue(val);
      }
    },
    [updateMode]
  );
  const discountAmount = (0, import_react.useMemo)(() => {
    const originalPrice = new import_decimal.default(originalValue || 0);
    let discountAmount2 = new import_decimal.default(0);
    if (updateMode === "priceOverride") {
      discountAmount2 = originalPrice.minus(new import_decimal.default(internalValue || 0));
    } else {
      if (discountMode === "amount") {
        discountAmount2 = new import_decimal.default(discountValue || 0);
      } else {
        const percentage = new import_decimal.default(discountValue || 0);
        discountAmount2 = originalPrice.times(percentage.dividedBy(100));
      }
    }
    return discountAmount2.toNumber();
  }, [updateMode, discountMode, internalValue, discountValue, originalValue]);
  const isDiscountOverflow = (0, import_react.useMemo)(() => {
    const _original = new import_decimal.default(originalValue || 0);
    if (updateMode === "priceOverride") {
      return new import_decimal.default(internalValue || 0).greaterThan(_original);
    }
    if (discountMode === "amount") {
      return new import_decimal.default(discountValue || 0).greaterThan(_original);
    }
    return false;
  }, [updateMode, discountMode, internalValue, discountValue, originalValue]);
  const payableAmount = (0, import_react.useMemo)(() => {
    return new import_decimal.default(originalValue || 0).minus(discountAmount).toNumber();
  }, [originalValue, discountAmount]);
  const handleEnter = () => {
    if (updateMode === "priceOverride" && enableExceedMaxAmount) {
      onEnter == null ? void 0 : onEnter(String(discountAmount));
      return;
    }
    if (isDiscountOverflow) {
      return;
    }
    onEnter == null ? void 0 : onEnter(String(discountAmount));
  };
  const _max = (0, import_react.useMemo)(() => {
    return updateMode === "discount" && discountMode === "percentage" ? 100 : void 0;
  }, [updateMode, discountMode]);
  const { handleChange } = (0, import_keyActions.default)({
    onEnter: handleEnter,
    onReset: _onReset,
    onChange: _handleChange,
    value: updateMode === "priceOverride" ? internalValue : discountValue,
    max: _max,
    mode: isFirstInput && updateMode === "priceOverride" ? "replace" : "append",
    scale: 2
  });
  const rightItems = (0, import_rightItems.default)({
    rightItemsStyle: {
      doneButtonStyle: {
        boxShadow: "0px 0px 1px #898A8D",
        cursor: updateMode !== "priceOverride" && isDiscountOverflow ? "not-allowed" : void 0,
        backgroundColor: updateMode !== "priceOverride" && isDiscountOverflow ? "#D0D5DD" : void 0
      }
    },
    doneText: doneText || import_utils.locales.getText("discount-keyboard-done"),
    resetText: resetText || import_utils.locales.getText("discount-keyboard-reset")
  });
  const formattedVal = (0, import_react.useMemo)(() => {
    if (updateMode === "priceOverride") {
      return internalValue ? `${amountSymbol}${internalValue}` : "";
    }
    if (discountMode === "amount") {
      return discountValue ? `${amountSymbol}${discountValue}` : "";
    } else {
      return discountValue ? `${discountValue}%` : "";
    }
  }, [updateMode, discountMode, internalValue, discountValue, amountSymbol]);
  const placeholder = (0, import_react.useMemo)(() => {
    if (updateMode === "priceOverride") {
      return `${amountSymbol}0`;
    } else {
      if (discountMode === "amount") {
        return "0";
      }
      return "%";
    }
  }, [amountSymbol, updateMode, discountMode]);
  const renderBottomContent = () => {
    if (new import_decimal.default(discountAmount).equals(0)) {
      return /* @__PURE__ */ import_react.default.createElement("div", null, " ");
    }
    if (updateMode === "priceOverride" || discountMode === "percentage") {
      let color;
      let sign = "";
      if (new import_decimal.default(discountAmount).greaterThan(0)) {
        color = TIP_COLORS.negative;
        sign = "-";
      } else {
        sign = "+";
        color = TIP_COLORS.positive;
      }
      const style = {
        color
      };
      return /* @__PURE__ */ import_react.default.createElement("div", { style, className: "ellipsis" }, /* @__PURE__ */ import_react.default.createElement("span", null, sign, /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellText.Amount,
        {
          hideDecimalForWholeNumbers: false,
          precision: 2,
          value: Math.abs(discountAmount)
        }
      )));
    }
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: { color: isDiscountOverflow ? TIP_COLORS.overflow : "" },
        className: "ellipsis"
      },
      import_utils.locales.getText("discount-keyboard-max-discount"),
      ":",
      " ",
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellText.Amount,
        {
          hideDecimalForWholeNumbers: false,
          precision: 2,
          value: originalValue
        }
      )
    );
  };
  const customDisplay = () => {
    const _color = updateMode === "discount" && discountMode === "amount" && isDiscountOverflow ? TIP_COLORS.overflow : void 0;
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          display: "flex",
          gap: 8
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.VirtualInput,
        {
          focused: true,
          value: formattedVal,
          wrapperStyle: {
            padding: "12px 20px",
            borderRadius: "8px",
            backgroundColor: "white",
            boxShadow: "0px 1px 2px rgba(16, 24, 40, 0.06)",
            flex: "2",
            overflow: "hidden"
          },
          style: {
            color: _color
          },
          placeholder,
          bottomContent: renderBottomContent()
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            flex: "1",
            display: "flex",
            flexDirection: "column",
            borderRadius: "8px",
            backgroundColor: "#ffffff",
            padding: 8,
            boxShadow: "0px 1px 2px rgba(16, 24, 40, 0.06)",
            overflow: "hidden"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              flex: 1
            }
          },
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              style: {
                color: "#667085",
                fontSize: 12,
                fontWeight: 500,
                wordWrap: "break-word"
              }
            },
            import_utils.locales.getText("discount-keyboard-total")
          ),
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              style: {
                color: "#475467",
                fontSize: 14,
                fontWeight: 700,
                wordWrap: "break-word"
              }
            },
            /* @__PURE__ */ import_react.default.createElement(import_materials.PisellText.Amount, { value: originalValue })
          )
        ),
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            style: {
              flex: 1
            }
          },
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              style: {
                color: "#667085",
                fontSize: 12,
                fontWeight: 500,
                wordWrap: "break-word"
              }
            },
            import_utils.locales.getText("discount-keyboard-payable")
          ),
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              style: {
                color: "#475467",
                fontSize: 14,
                fontWeight: 700,
                wordWrap: "break-word"
              }
            },
            /* @__PURE__ */ import_react.default.createElement(import_materials.PisellText.Amount, { value: payableAmount })
          )
        )
      )
    );
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-discount" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Segmented,
    {
      size: "large",
      style: {
        padding: 6
      },
      options: [
        {
          label: import_utils.locales.getText("discount-keyboard-price-override"),
          value: "priceOverride"
        },
        {
          label: import_utils.locales.getText("discount-keyboard-discount"),
          value: "discount"
        }
      ],
      value: updateMode,
      onChange: (val) => setUpdateMode(val),
      block: true
    }
  ), updateMode === "discount" && /* @__PURE__ */ import_react.default.createElement(
    import_antd.Segmented,
    {
      size: "large",
      style: {
        padding: 6
      },
      options: [
        {
          label: import_utils.locales.getText("discount-keyboard-amount") + ` (${amountSymbol})`,
          value: "amount"
        },
        {
          label: import_utils.locales.getText("discount-keyboard-percentage") + " (%)",
          value: "percentage"
        }
      ],
      value: discountMode,
      onChange: (val) => {
        setDiscountMode(val);
        setDiscountValue("");
      },
      block: true
    }
  ), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-pro-price-keyboard-content" }, customDisplay(), /* @__PURE__ */ import_react.default.createElement(
    import_materials.Keyboard,
    {
      rightItems,
      onChange: handleChange,
      id: uniqueKeyboardId
    }
  )));
};
var DiscountKeyboard = (props) => {
  const { containerProps, children, ...keyboardProps } = props;
  if (!containerProps) {
    return /* @__PURE__ */ import_react.default.createElement(DiscountKeyboardBase, { ...keyboardProps });
  }
  const { renderType, open, ...restProps } = containerProps || {};
  if (renderType === "popover") {
    return /* @__PURE__ */ import_react.default.createElement(
      import_antd.Popover,
      {
        key: `${open}`,
        open,
        trigger: "click",
        className: "pisell-discount-keyboard-popover",
        ...restProps,
        content: /* @__PURE__ */ import_react.default.createElement(DiscountKeyboardBase, { ...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-discount-keyboard-modal",
        destroyOnHidden: true,
        ...restProps
      },
      /* @__PURE__ */ import_react.default.createElement(DiscountKeyboardBase, { ...keyboardProps })
    ) : null;
  }
  return /* @__PURE__ */ import_react.default.createElement(DiscountKeyboardBase, { ...keyboardProps });
};
var DiscountKeyboardInputNumber = (props) => {
  var _a;
  const { originalValue, value, onChange, keyboardProps, ...rest } = props;
  const [internalValue, setInternalValue] = (0, import_ahooks.useControllableValue)(props);
  const [isOpen, setIsOpen] = (0, import_react.useState)(false);
  const renderType = ((_a = keyboardProps == null ? void 0 : keyboardProps.containerProps) == null ? void 0 : _a.renderType) || "popover";
  if (renderType === "modal") {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      import_antd.InputNumber,
      {
        value,
        readOnly: true,
        ...rest,
        onClick: () => setIsOpen(true)
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      DiscountKeyboard,
      {
        ...keyboardProps || {},
        containerProps: {
          ...keyboardProps == null ? void 0 : keyboardProps.containerProps,
          open: isOpen,
          onCancel: () => setIsOpen(false),
          renderType: "modal"
        },
        enableExceedMaxAmount: true,
        defaultValue: internalValue,
        onEnter: (val) => {
          setInternalValue(
            new import_decimal.default(originalValue).minus(Number(val)).toNumber()
          );
          setIsOpen(false);
        },
        originalValue
      }
    ));
  }
  return /* @__PURE__ */ import_react.default.createElement(
    DiscountKeyboard,
    {
      ...keyboardProps || {},
      containerProps: {
        ...keyboardProps == null ? void 0 : keyboardProps.containerProps,
        open: isOpen,
        onOpenChange: (val) => setIsOpen(val),
        renderType: "popover"
      },
      enableExceedMaxAmount: true,
      defaultValue: internalValue,
      onEnter: (val) => {
        setInternalValue(
          new import_decimal.default(originalValue).minus(Number(val)).toNumber()
        );
        setIsOpen(false);
      },
      originalValue
    },
    /* @__PURE__ */ import_react.default.createElement(import_antd.InputNumber, { value, readOnly: true, ...rest })
  );
};
DiscountKeyboard.InputNumber = DiscountKeyboardInputNumber;
var discountKeyboard_default = DiscountKeyboard;
