function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import * as React from 'react';
import { useMemo, useState, useCallback, useEffect } from 'react';
import classNames from 'classnames';
import { isMobile } from '@pisell/utils';
import { NumberKeyboard } from "../keyboards";
import useThemeTokens from "../../hooks/useThemeTokens";
import "./index.less";

/**
 * 样式变体类型
 * - separated: 分离式，按钮独立显示（默认）
 * - capsule: 胶囊式，按钮和数字在一个圆角容器内
 */

var NumericStepper = function NumericStepper(_ref) {
  var value = _ref.value,
    _ref$defaultValue = _ref.defaultValue,
    defaultValue = _ref$defaultValue === void 0 ? 0 : _ref$defaultValue,
    _ref$min = _ref.min,
    min = _ref$min === void 0 ? 0 : _ref$min,
    _ref$max = _ref.max,
    max = _ref$max === void 0 ? Infinity : _ref$max,
    _ref$step = _ref.step,
    step = _ref$step === void 0 ? 1 : _ref$step,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    onChange = _ref.onChange,
    className = _ref.className,
    styles = _ref.styles,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? 'middle' : _ref$size,
    _ref$shape = _ref.shape,
    shape = _ref$shape === void 0 ? 'round' : _ref$shape,
    minusIcon = _ref.minusIcon,
    plusIcon = _ref.plusIcon,
    _ref$horizontalPaddin = _ref.horizontalPadding,
    horizontalPadding = _ref$horizontalPaddin === void 0 ? 0 : _ref$horizontalPaddin,
    _ref$variant = _ref.variant,
    variant = _ref$variant === void 0 ? 'separated' : _ref$variant,
    _ref$enableInput = _ref.enableInput,
    enableInput = _ref$enableInput === void 0 ? true : _ref$enableInput,
    displayMaxWidth = _ref.displayMaxWidth,
    theme = _ref.theme,
    _ref$plusOnlyAtZero = _ref.plusOnlyAtZero,
    plusOnlyAtZero = _ref$plusOnlyAtZero === void 0 ? true : _ref$plusOnlyAtZero;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = useState(value !== undefined ? value : defaultValue),
    _useState4 = _slicedToArray(_useState3, 2),
    internalValue = _useState4[0],
    setInternalValue = _useState4[1];
  var _isMobile = useMemo(function () {
    return isMobile();
  }, [isMobile]);
  var _useThemeTokens = useThemeTokens(theme),
    colorPrimary = _useThemeTokens.colorPrimary;
  var _useState5 = useState(''),
    _useState6 = _slicedToArray(_useState5, 2),
    tempValue = _useState6[0],
    setTempValue = _useState6[1];
  var currentValue = value !== undefined ? value : internalValue;

  // 同步外部value变化
  useEffect(function () {
    if (value !== undefined) {
      setInternalValue(value);
    }
  }, [value]);

  // 处理值变化
  var handleValueChange = useCallback(function (newValue) {
    // 确保值在有效范围内
    var clampedValue = Math.max(min, Math.min(max, newValue));
    if (value === undefined) {
      setInternalValue(clampedValue);
    }
    onChange === null || onChange === void 0 || onChange(clampedValue);
  }, [min, max, value, onChange]);

  // 减少数值
  var handleDecrease = useCallback(function () {
    if (disabled) return;
    var newValue = currentValue - step;
    if (newValue >= min) {
      handleValueChange(newValue);
    }
  }, [currentValue, step, min, disabled, handleValueChange]);

  // 增加数值
  var handleIncrease = useCallback(function () {
    if (disabled) return;

    // 如果当前值小于 min，直接增加到 min
    if (currentValue < min) {
      handleValueChange(min);
      return;
    }
    var newValue = currentValue + step;
    if (newValue <= max) {
      handleValueChange(newValue);
    }
  }, [currentValue, step, min, max, disabled, handleValueChange]);
  var handleChange = function handleChange(e) {
    if (!e) {
      setTempValue(min.toString());
      return;
    }
    if (e === 'delete') {
      // 删除最后一位数字
      var newTempValue = tempValue.slice(0, -1);
      setTempValue(newTempValue || '0');
      return;
    } else if (e === 'verify') {
      // 确认时提交暂存的值
      var newValue = parseInt(tempValue) || 0;
      var clampedValue = Math.max(min, Math.min(max, newValue));
      onChange === null || onChange === void 0 || onChange(clampedValue);
      setOpen(false); // 手动关闭弹窗
      return;
    } else {
      // 更新暂存值，不直接触发onChange
      setTempValue(e);
    }
  };

  // 点击数字的处理
  var handleNumberClick = function handleNumberClick() {
    // 禁用或关闭输入功能时不响应点击
    if (disabled || !enableInput) return;
    // Popover 会自动处理打开，我们只需要设置初始值
    setTempValue(currentValue.toString()); // 设置临时值为当前值
    if (_isMobile) {
      setOpen(true);
    }
  };

  // 处理弹窗开关时的值同步
  var handleOpenChange = function handleOpenChange(visible) {
    setOpen(visible);
    if (visible) {
      // 打开时设置临时值为当前值
      setTempValue(currentValue.toString());
    } else {
      // 关闭时检查是否需要提交值
      var tempNumber = parseInt(tempValue) || 0;
      var clampedValue = Math.max(min, Math.min(max, tempNumber));
      if (clampedValue !== value) {
        onChange === null || onChange === void 0 || onChange(clampedValue);
      }
      // 重置临时值为当前值，确保下次打开时显示正确的值
      setTempValue(currentValue.toString());
    }
  };

  // 判断按钮是否应该禁用
  var isDecreaseDisabled = disabled || currentValue <= min;
  var isIncreaseDisabled = disabled || currentValue >= max;
  // 胶囊模式下不应用 isPlusOnly 逻辑，始终显示完整的 减号-数字-加号
  var isPlusOnly = variant === 'capsule' ? false : Boolean(plusOnlyAtZero && (currentValue === 0 || currentValue === undefined));
  var outOfRange = currentValue < min || currentValue > max;
  var stepperClasses = classNames('numeric-stepper', "numeric-stepper-".concat(size), "numeric-stepper-".concat(variant), _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, "numeric-stepper-".concat(shape), variant === 'separated'), 'numeric-stepper-disabled', disabled), 'numeric-stepper-simple', currentValue === 0 || currentValue === undefined), 'numeric-stepper-out-of-range', outOfRange), 'numeric-stepper-plus-only', isPlusOnly), 'numeric-stepper-input-disabled', !enableInput), className);
  var _minus = !isPlusOnly && /*#__PURE__*/React.createElement("div", {
    className: "numeric-stepper-button-wrapper numeric-stepper-minus-button-wrapper",
    onClick: handleDecrease,
    style: {
      paddingLeft: horizontalPadding
    }
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: classNames('numeric-stepper-button', 'numeric-stepper-minus', {
      'numeric-stepper-button-disabled': isDecreaseDisabled
    }),
    disabled: isDecreaseDisabled
  }, minusIcon || /*#__PURE__*/React.createElement("svg", {
    width: "16",
    height: "16",
    viewBox: "0 0 16 16",
    fill: "none"
  }, /*#__PURE__*/React.createElement("path", {
    d: "M3 8h10",
    stroke: "currentColor",
    strokeWidth: "1.5",
    strokeLinecap: "round"
  }))));
  var _display = useMemo(function () {
    if (isPlusOnly) {
      return null;
    }

    // 展示区域样式（胶囊模式下支持 displayMaxWidth）
    var displayWrapperStyle = variant === 'capsule' && displayMaxWidth ? {
      maxWidth: typeof displayMaxWidth === 'number' ? "".concat(displayMaxWidth, "px") : displayMaxWidth
    } : {};

    // 纯展示模式（enableInput 为 false）
    var displayElement = /*#__PURE__*/React.createElement("span", {
      className: "numeric-stepper-display-wrapper",
      onClick: handleNumberClick,
      style: displayWrapperStyle
    }, /*#__PURE__*/React.createElement("span", {
      className: classNames('numeric-stepper-display')
    }, currentValue));

    // 关闭输入功能时，只展示数字，不包装键盘
    if (!enableInput) {
      return displayElement;
    }
    if (_isMobile) {
      return displayElement;
    }
    return /*#__PURE__*/React.createElement(NumberKeyboard, {
      max: max,
      min: min,
      originalValue: currentValue.toString(),
      defaultValue: currentValue.toString(),
      onEnter: function onEnter(newValue) {
        handleValueChange === null || handleValueChange === void 0 || handleValueChange(Number(newValue));
        setOpen(false);
      },
      containerProps: {
        className: 'numeric-stepper-keyboard-popover',
        renderType: 'popover',
        open: open,
        onOpenChange: handleOpenChange,
        content: /*#__PURE__*/React.createElement(NumberKeyboard, {
          max: max,
          min: min,
          originalValue: currentValue.toString(),
          defaultValue: currentValue.toString(),
          onEnter: function onEnter(newValue) {
            handleValueChange === null || handleValueChange === void 0 || handleValueChange(Number(newValue));
            setOpen(false);
          }
        })
      }
    }, displayElement);
  }, [_isMobile, open, isPlusOnly, currentValue, handleNumberClick, handleOpenChange, handleChange, max, min, onChange, tempValue, enableInput, variant, displayMaxWidth]);
  var _plus = /*#__PURE__*/React.createElement("div", {
    className: "numeric-stepper-button-wrapper numeric-stepper-plus-button-wrapper",
    onClick: handleIncrease,
    style: {
      paddingLeft: isPlusOnly ? horizontalPadding : 0,
      paddingRight: horizontalPadding
    }
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: classNames('numeric-stepper-button', 'numeric-stepper-plus', {
      'numeric-stepper-button-disabled': isIncreaseDisabled
    }),
    disabled: isIncreaseDisabled
  }, plusIcon || /*#__PURE__*/React.createElement("svg", {
    width: "16",
    height: "16",
    viewBox: "0 0 16 16",
    fill: "none"
  }, /*#__PURE__*/React.createElement("path", {
    d: "M8 3v10M3 8h10",
    stroke: "currentColor",
    strokeWidth: "1.5",
    strokeLinecap: "round"
  }))));
  return /*#__PURE__*/React.createElement("div", {
    className: stepperClasses,
    style: _objectSpread(_objectSpread({}, (styles === null || styles === void 0 ? void 0 : styles.container) || {}), {}, _defineProperty({}, '--color-primary', colorPrimary)),
    onClick: function onClick(e) {
      return e.stopPropagation();
    }
  }, _minus, _display, _plus, _isMobile && /*#__PURE__*/React.createElement(NumberKeyboard, {
    containerProps: {
      className: 'numeric-stepper-keyboard-modal',
      renderType: 'modal',
      open: open,
      onCancel: function onCancel() {
        setOpen(false);
      }
    },
    max: max,
    min: min,
    defaultValue: currentValue.toString(),
    originalValue: currentValue.toString(),
    onEnter: function onEnter(newValue) {
      handleValueChange === null || handleValueChange === void 0 || handleValueChange(Number(newValue));
      setOpen(false);
    }
  }));
};
export default NumericStepper;