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); }
var _excluded = ["containerProps", "children"],
  _excluded2 = ["renderType", "open", "className"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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 React, { useMemo, useCallback, useState, useEffect } from 'react';
import classNames from 'classnames';
import { Popover } from 'antd';
import { useControllableValue } from 'ahooks';
import { Icon, Keyboard, PisellModal } from '@pisell/materials';
import { locales } from '@pisell/utils';
import VirtualInput from "../../../../../materials/src/components/virtualInput";
import useEngineContext from "../../../hooks/useEngineContext";
import localeTexts from "../locales";
import "./index.less";

// 生成简单的唯一 ID
var generateSimpleUUID = function generateSimpleUUID() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
};

/**
 * NumberKeyboardBase - 数字输入键盘基础组件
 * 支持整数模式和小数模式
 */
var NumberKeyboardBase = function NumberKeyboardBase(props) {
  var _context$engine;
  var _props$mode = props.mode,
    mode = _props$mode === void 0 ? 'integer' : _props$mode,
    _props$originalValue = props.originalValue,
    originalValue = _props$originalValue === void 0 ? '' : _props$originalValue,
    _props$placeholder = props.placeholder,
    placeholder = _props$placeholder === void 0 ? '' : _props$placeholder,
    max = props.max,
    min = props.min,
    maxLength = props.maxLength,
    _props$precision = props.precision,
    precision = _props$precision === void 0 ? 2 : _props$precision,
    _props$disabled = props.disabled,
    disabled = _props$disabled === void 0 ? false : _props$disabled,
    doneText = props.doneText,
    resetText = props.resetText,
    clearText = props.clearText,
    label = props.label,
    errorText = props.errorText,
    style = props.style,
    className = props.className,
    _props$keydown = props.keydown,
    keydown = _props$keydown === void 0 ? true : _props$keydown,
    inputStyle = props.inputStyle,
    inputWrapperStyle = props.inputWrapperStyle,
    onEnter = props.onEnter,
    onReset = props.onReset;
  var context = useEngineContext();
  locales.init(localeTexts, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en');

  // 受控/非受控值
  var _useControllableValue = useControllableValue(props, {
      defaultValue: ''
    }),
    _useControllableValue2 = _slicedToArray(_useControllableValue, 2),
    internalValue = _useControllableValue2[0],
    setInternalValue = _useControllableValue2[1];
  var uniqueKeyboardId = useMemo(function () {
    return "number-keyboard-".concat(generateSimpleUUID());
  }, []);

  // 是否是首次输入（用于选中状态）
  var _useState = useState(!!internalValue),
    _useState2 = _slicedToArray(_useState, 2),
    isSelected = _useState2[0],
    setIsSelected = _useState2[1];

  // 当从外部传入新的 value 时，重新标记为选中状态
  useEffect(function () {
    if (internalValue) {
      setIsSelected(true);
    }
  }, []);

  // 检查是否超出范围
  var isOutOfRange = useMemo(function () {
    if (!internalValue) return false;
    var numValue = parseFloat(internalValue);
    if (isNaN(numValue)) return false;
    if (max !== undefined && numValue > max) return true;
    if (min !== undefined && numValue < min) return true;
    return false;
  }, [internalValue, max, min]);

  // 获取错误提示文本
  var errorMessage = useMemo(function () {
    if (!isOutOfRange) return '';
    if (errorText) return errorText;
    var numValue = parseFloat(internalValue);
    if (max !== undefined && numValue > max) {
      return locales.getText('pisell2.keyboard.number-keybard.max')(max);
    }
    if (min !== undefined && numValue < min) {
      return locales.getText('pisell2.keyboard.number-keybard.min')(min);
    }
    return '';
  }, [isOutOfRange, errorText, internalValue, max, min]);

  // 处理数值变化
  var handleValueChange = useCallback(function (newValue) {
    // 如果当前是选中状态，替换整个值
    if (isSelected && newValue !== '') {
      setIsSelected(false);
    }
    setInternalValue(newValue);
  }, [isSelected, setInternalValue]);

  // 单个删除
  var handleDelete = useCallback(function () {
    if (isSelected) {
      setIsSelected(false);
    }
    if (internalValue.length > 0) {
      handleValueChange(internalValue.slice(0, -1));
    }
  }, [internalValue, isSelected, handleValueChange]);

  // 清空
  var handleClear = useCallback(function () {
    handleValueChange('');
    setIsSelected(false);
  }, [handleValueChange]);

  // 重置到原始值
  var handleReset = useCallback(function () {
    setInternalValue(String(originalValue));
    setIsSelected(true);
    onReset === null || onReset === void 0 || onReset();
  }, [originalValue, setInternalValue, onReset]);

  // 确认
  var handleDone = useCallback(function () {
    if (isOutOfRange) return;
    var submitValue = mode === 'decimal' ? internalValue.replace(/\.$/, '') : internalValue;
    onEnter === null || onEnter === void 0 || onEnter(submitValue);
  }, [internalValue, isOutOfRange, mode, onEnter]);

  // 处理数字输入
  var handleNumberInput = useCallback(function (num) {
    var newValue;
    if (isSelected) {
      // 选中状态，替换整个值
      newValue = mode === 'decimal' && num === '.' ? '0.' : num;
      setIsSelected(false);
    } else {
      newValue = internalValue + num;
    }

    // 检查最大长度
    if (maxLength && newValue.replace('.', '').length > maxLength) {
      return;
    }

    // 整数模式不允许小数点
    if (mode === 'integer' && newValue.includes('.')) {
      return;
    }

    // 小数模式检查小数位数
    if (mode === 'decimal' && newValue.includes('.')) {
      var parts = newValue.split('.');
      if (parts[1] && parts[1].length > precision) {
        return;
      }
    }

    // 防止多个小数点
    if (!isSelected && num === '.' && internalValue.includes('.')) {
      return;
    }

    // 防止以多个0开头
    if (newValue.length > 1 && newValue.startsWith('0') && !newValue.startsWith('0.')) {
      newValue = newValue.replace(/^0+/, '') || '0';
    }

    // 处理 "00" 输入
    if (num === '00') {
      if (internalValue === '' || internalValue === '0') {
        newValue = '0';
      }
    }
    handleValueChange(newValue);
  }, [internalValue, isSelected, maxLength, mode, precision, handleValueChange]);

  // 键盘按键处理
  var handleKeyboardChange = useCallback(function (key) {
    if (key === undefined) return;
    var keyStr = String(key);
    switch (keyStr) {
      case 'delete':
      case 'backspace':
        handleDelete();
        break;
      case 'clear':
        handleClear();
        break;
      case 'reset':
        handleReset();
        break;
      case 'done':
      case 'ok':
        handleDone();
        break;
      default:
        // 数字或小数点
        if (/^[0-9.]$/.test(keyStr) || keyStr === '00') {
          handleNumberInput(keyStr);
        }
        break;
    }
  }, [handleDelete, handleClear, handleReset, handleDone, handleNumberInput]);

  // 整数模式键盘配置 (3列布局)
  var integerKeyboardItems = useMemo(function () {
    return [{
      value: 1,
      label: '1',
      disabled: false,
      type: 'text'
    }, {
      value: 2,
      label: '2',
      disabled: false,
      type: 'text'
    }, {
      value: 3,
      label: '3',
      disabled: false,
      type: 'text'
    }, {
      value: 4,
      label: '4',
      disabled: false,
      type: 'text'
    }, {
      value: 5,
      label: '5',
      disabled: false,
      type: 'text'
    }, {
      value: 6,
      label: '6',
      disabled: false,
      type: 'text'
    }, {
      value: 7,
      label: '7',
      disabled: false,
      type: 'text'
    }, {
      value: 8,
      label: '8',
      disabled: false,
      type: 'text'
    }, {
      value: 9,
      label: '9',
      disabled: false,
      type: 'text'
    }, {
      value: 'reset',
      label: resetText || locales.getText('pisell2.keyboard.number-keybard.reset'),
      disabled: false,
      type: 'text',
      style: {
        color: '#F04438',
        fontSize: 18
      }
    }, {
      value: 0,
      label: '0',
      disabled: false,
      type: 'text'
    }, {
      value: 'done',
      label: doneText || locales.getText('pisell2.keyboard.number-keybard.ok'),
      disabled: isOutOfRange,
      type: 'primary',
      style: {
        fontSize: 18
      }
    }];
  }, [resetText, doneText, isOutOfRange]);

  // 小数模式键盘配置 (4列布局，带右侧按钮)
  var decimalKeyboardItems = useMemo(function () {
    return [{
      value: 1,
      label: '1',
      disabled: false,
      type: 'text'
    }, {
      value: 2,
      label: '2',
      disabled: false,
      type: 'text'
    }, {
      value: 3,
      label: '3',
      disabled: false,
      type: 'text'
    }, {
      value: 4,
      label: '4',
      disabled: false,
      type: 'text'
    }, {
      value: 5,
      label: '5',
      disabled: false,
      type: 'text'
    }, {
      value: 6,
      label: '6',
      disabled: false,
      type: 'text'
    }, {
      value: 7,
      label: '7',
      disabled: false,
      type: 'text'
    }, {
      value: 8,
      label: '8',
      disabled: false,
      type: 'text'
    }, {
      value: 9,
      label: '9',
      disabled: false,
      type: 'text'
    }, {
      value: 0,
      label: '0',
      disabled: false,
      type: 'text'
    }, {
      value: '00',
      label: '00',
      disabled: false,
      type: 'text'
    }, {
      value: '.',
      label: '.',
      disabled: false,
      type: 'text'
    }];
  }, []);

  // 小数模式右侧按钮
  var decimalRightItems = useMemo(function () {
    return [{
      value: 'clear',
      label: clearText || locales.getText('pisell2.keyboard.number-keybard.clear'),
      disabled: false,
      type: 'text',
      size: 1,
      style: {
        fontSize: 18
      }
    }, {
      value: 'reset',
      label: resetText || locales.getText('pisell2.keyboard.number-keybard.reset'),
      disabled: false,
      type: 'text',
      size: 1,
      style: {
        color: '#F04438',
        fontSize: 18
      }
    }, {
      value: 'done',
      label: doneText || locales.getText('pisell2.keyboard.number-keybard.ok'),
      disabled: isOutOfRange,
      type: 'primary',
      size: 2,
      style: {
        fontSize: 18
      }
    }];
  }, [clearText, resetText, doneText, isOutOfRange]);

  // 渲染输入框显示值
  var displayValue = useMemo(function () {
    return internalValue || '';
  }, [internalValue]);
  var renderBottomContent = useCallback(function () {
    if (isOutOfRange && errorMessage) {
      return /*#__PURE__*/React.createElement("div", {
        className: "pisell-number-keyboard-error-message"
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "pisell2-alert-circle",
        size: 16
      }), errorMessage);
    }
    return null;
  }, [errorMessage]);
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-number-keyboard', "pisell-number-keyboard--".concat(mode), {
      'pisell-number-keyboard--disabled': disabled
    }, className),
    style: style
  }, label && /*#__PURE__*/React.createElement("div", {
    className: "pisell-number-keyboard-label"
  }, label), /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-number-keyboard-input-wrapper')
  }, /*#__PURE__*/React.createElement(VirtualInput, {
    focused: !disabled,
    selected: isSelected && !!internalValue,
    value: displayValue,
    placeholder: placeholder,
    wrapperStyle: _objectSpread({
      flex: 1,
      padding: '19px 16px',
      borderRadius: '8px',
      backgroundColor: 'white',
      boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.06)',
      overflow: 'hidden'
    }, inputWrapperStyle),
    style: _objectSpread({
      fontSize: '48px',
      fontWeight: 'bold',
      border: 'none',
      background: 'transparent',
      width: '100%',
      color: isOutOfRange ? '#D92D20' : undefined
    }, inputStyle),
    preventBlurElements: ["#".concat(uniqueKeyboardId)],
    allowClear: true,
    onClear: handleDelete,
    textAlign: "center"
  }), renderBottomContent()), /*#__PURE__*/React.createElement(Keyboard, {
    id: uniqueKeyboardId,
    className: classNames('pisell-number-keyboard-keys', {
      'pisell-number-keyboard-keys--integer': mode === 'integer',
      'pisell-number-keyboard-keys--decimal': mode === 'decimal'
    }),
    items: mode === 'integer' ? integerKeyboardItems : decimalKeyboardItems,
    rightItems: mode === 'decimal' ? decimalRightItems : undefined,
    keydown: keydown,
    onChange: handleKeyboardChange
  }));
};

/**
 * NumberKeyboard - 数字输入键盘
 * 支持基础形式展示、popover 形态或 modal 形态
 */
var NumberKeyboard = function NumberKeyboard(props) {
  var containerProps = props.containerProps,
    children = props.children,
    keyboardProps = _objectWithoutProperties(props, _excluded);

  // 无 containerProps，直接渲染基础组件
  if (!containerProps) {
    return /*#__PURE__*/React.createElement(NumberKeyboardBase, keyboardProps);
  }
  var _ref = containerProps || {},
    renderType = _ref.renderType,
    open = _ref.open,
    className = _ref.className,
    restProps = _objectWithoutProperties(_ref, _excluded2);

  // Popover 模式（受控）
  if (renderType === 'popover') {
    return /*#__PURE__*/React.createElement(Popover, _extends({
      key: "".concat(open),
      open: open,
      trigger: ['click'],
      overlayClassName: classNames('pisell-number-keyboard-popover', className),
      destroyTooltipOnHide: true,
      overlayInnerStyle: {
        padding: 0
      },
      arrow: false
    }, restProps, {
      content: /*#__PURE__*/React.createElement(NumberKeyboardBase, keyboardProps)
    }), children);
  }

  // Modal 模式（受控）
  if (renderType === 'modal') {
    return open ? /*#__PURE__*/React.createElement(PisellModal, _extends({
      platform: 'pc',
      open: true,
      width: "unset",
      header: null,
      footer: false,
      mask: false,
      maskClosable: true,
      bodyStyle: {
        padding: '0px',
        backgroundColor: 'transparent'
      },
      closeIcon: null,
      className: classNames('pisell-number-keyboard-modal', className),
      destroyOnClose: true
    }, restProps), /*#__PURE__*/React.createElement(NumberKeyboardBase, keyboardProps)) : null;
  }

  // 默认渲染基础组件
  return /*#__PURE__*/React.createElement(NumberKeyboardBase, keyboardProps);
};
export default NumberKeyboard;
export { NumberKeyboardBase };