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 = ["renderType", "containerProps", "children"],
  _excluded2 = ["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 } from 'react';
import classNames from 'classnames';
import { Popover } from 'antd';
import { useControllableValue } from 'ahooks';
import { Keyboard, PisellModal, VirtualInput } from '@pisell/materials';
import { locales } from '@pisell/utils';
import useEngineContext from "../../../hooks/useEngineContext";
import localeTexts from "../locales";
import { formatPhoneDisplay } from "./utils";
import "./index.less";

// 生成简单的唯一 ID
var generateSimpleUUID = function generateSimpleUUID() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
};
var normalizePhoneValue = function normalizePhoneValue(value) {
  return "".concat(value || '').replace(/\D/g, '');
};

/**
 * PhoneKeyboardBase - 手机号输入键盘基础组件
 * 按国家区号格式化展示，实际回传值保持纯数字。
 */
var PhoneKeyboardBase = function PhoneKeyboardBase(props) {
  var _context$engine;
  var _props$countryCalling = props.countryCallingCode,
    countryCallingCode = _props$countryCalling === void 0 ? '61' : _props$countryCalling,
    _props$placeholder = props.placeholder,
    placeholder = _props$placeholder === void 0 ? '' : _props$placeholder,
    maxLength = props.maxLength,
    _props$disabled = props.disabled,
    disabled = _props$disabled === void 0 ? false : _props$disabled,
    doneText = props.doneText,
    clearText = props.clearText,
    label = props.label,
    _props$formatSeparato = props.formatSeparator,
    formatSeparator = _props$formatSeparato === void 0 ? 'space' : _props$formatSeparato,
    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;
  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 "phone-keyboard-".concat(generateSimpleUUID());
  }, []);

  // 处理手机号变化
  var handleValueChange = useCallback(function (newValue) {
    var normalizedValue = normalizePhoneValue(newValue);
    setInternalValue(normalizedValue);
  }, [setInternalValue]);

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

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

  // 确认
  var handleDone = useCallback(function () {
    onEnter === null || onEnter === void 0 || onEnter(internalValue);
  }, [internalValue, onEnter]);

  // 处理数字输入
  var handleNumberInput = useCallback(function (num) {
    var newValue = internalValue + num;
    if (maxLength && newValue.length > maxLength) {
      return;
    }
    handleValueChange(newValue);
  }, [internalValue, maxLength, 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 'done':
      case 'ok':
        handleDone();
        break;
      default:
        if (/^[0-9]$/.test(keyStr)) {
          handleNumberInput(keyStr);
        }
        break;
    }
  }, [handleDelete, handleClear, handleDone, handleNumberInput]);

  // 手机号键盘配置 (3列布局)
  var phoneKeyboardItems = 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: 'clear',
      label: clearText || locales.getText('pisell2.keyboard.number-keybard.clear'),
      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.phone-keyboard.confirm'),
      disabled: false,
      type: 'primary',
      style: {
        fontSize: 18
      }
    }];
  }, [clearText, doneText]);

  // 渲染输入框显示值
  var displayValue = useMemo(function () {
    return formatPhoneDisplay(internalValue, countryCallingCode, formatSeparator);
  }, [internalValue, countryCallingCode, formatSeparator]);
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-phone-keyboard', {
      'pisell-phone-keyboard--disabled': disabled
    }, className),
    style: style
  }, label && /*#__PURE__*/React.createElement("div", {
    className: "pisell-phone-keyboard-label"
  }, label), /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-phone-keyboard-input-wrapper')
  }, /*#__PURE__*/React.createElement(VirtualInput, {
    focused: !disabled,
    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%'
    }, inputStyle),
    preventBlurElements: ["#".concat(uniqueKeyboardId)],
    textAlign: "center",
    allowClear: true,
    onClear: handleDelete
  })), /*#__PURE__*/React.createElement(Keyboard, {
    id: uniqueKeyboardId,
    className: "pisell-phone-keyboard-keys",
    items: phoneKeyboardItems,
    keydown: keydown,
    onChange: handleKeyboardChange
  }));
};

/**
 * PhoneKeyboard - 手机号输入键盘
 * 支持基础形式展示、popover 形态或 modal 形态
 */
var PhoneKeyboard = function PhoneKeyboard(props) {
  var renderType = props.renderType,
    containerProps = props.containerProps,
    children = props.children,
    keyboardProps = _objectWithoutProperties(props, _excluded);
  var _ref = containerProps || {},
    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-phone-keyboard-popover', className),
      destroyTooltipOnHide: true,
      overlayInnerStyle: {
        padding: 0
      },
      arrow: false
    }, restProps, {
      content: /*#__PURE__*/React.createElement(PhoneKeyboardBase, 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-phone-keyboard-modal', className),
      destroyOnClose: true
    }, restProps), /*#__PURE__*/React.createElement(PhoneKeyboardBase, keyboardProps)) : null;
  }

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