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"];
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 _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 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, useId, useCallback, useRef, useEffect, useState } from 'react';
import { useControllableValue } from 'ahooks';
import Decimal from 'decimal.js';
//@ts-ignore
import { merge } from 'lodash';
//@ts-ignore
import { locales } from '@pisell/utils';
import { Popover } from 'antd';
import { Keyboard, PisellText, VirtualInput, PisellModal } from '@pisell/materials';
import Shortcuts from "../shortcuts";
import useRightItems from "../../hooks/rightItems";
import useKeyActions from "../../hooks/keyActions";
import { setKeyboardTheme } from "../../utils";
import "./index.less";
var CashKeyboardBase = function CashKeyboardBase(props) {
  var _mergedDisplayField$c, _mergedDisplayField$b, _mergedDisplayField$c2;
  var amountSymbol = props.amountSymbol,
    titleArea = props.titleArea,
    _props$originalValue = props.originalValue,
    originalValue = _props$originalValue === void 0 ? '' : _props$originalValue,
    displayField = props.displayField,
    presets = props.presets,
    keyboardProps = props.keyboardProps,
    style = props.style,
    min = props.min,
    max = props.max,
    _props$selectType = props.selectType,
    selectType = _props$selectType === void 0 ? 'light' : _props$selectType,
    _props$placeholder = props.placeholder,
    placeholder = _props$placeholder === void 0 ? '' : _props$placeholder,
    doneText = props.doneText,
    resetText = props.resetText;
  var _useControllableValue = useControllableValue(props),
    _useControllableValue2 = _slicedToArray(_useControllableValue, 2),
    internalValue = _useControllableValue2[0],
    setInternalValue = _useControllableValue2[1];
  // 生成唯一的类名
  var uniqueId = useId();
  var uniqueKeyboardId = "virtual-keyboard-".concat(uniqueId.replace(/:/g, '-'));
  // shortcuts ref
  var shortcutsRef = useRef(null);
  // 首次收入标识
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    isFirstInput = _useState2[0],
    setIsFirstInput = _useState2[1];
  // 找零
  var changeDue = useMemo(function () {
    return Math.max(0, new Decimal(internalValue || 0).minus(new Decimal(originalValue || 0)).toNumber());
  }, [internalValue, originalValue]);
  // 设置主题
  useEffect(function () {
    setKeyboardTheme(selectType);
  }, [selectType]);
  var onReset = useCallback(function () {
    var _props$onReset;
    setInternalValue(String(originalValue));
    setIsFirstInput(true);
    props === null || props === void 0 || (_props$onReset = props.onReset) === null || _props$onReset === void 0 || _props$onReset.call(props);
  }, [props === null || props === void 0 ? void 0 : props.onReset, setInternalValue, originalValue]);
  var _handleValChange = useCallback(function (val) {
    setInternalValue(val);
    setIsFirstInput(false);
  }, []);
  var _useKeyActions = useKeyActions({
      onEnter: props.onEnter,
      onReset: onReset,
      onChange: _handleValChange,
      value: internalValue,
      min: min,
      max: max,
      scale: 2,
      mode: isFirstInput ? 'replace' : 'append'
    }),
    handleChange = _useKeyActions.handleChange;
  var rightItems = useRightItems({
    rightItemsStyle: {},
    doneText: doneText || locales.getText('cash-keyboard-pay'),
    resetText: resetText || locales.getText('cash-keyboard-reset')
  });

  // 变体1：最多展示4个，不足4个时用空白块补齐
  var getDefaultPresets = useCallback(function () {
    var userPresets = presets || [];

    // 取前4个预设
    var limitedPresets = userPresets.slice(0, 4);

    // 如果不足4个，用空白块补齐
    while (limitedPresets.length < 4) {
      limitedPresets.push({
        label: '',
        value: '',
        style: {
          visibility: 'hidden',
          pointerEvents: 'none'
        }
      });
    }
    return limitedPresets;
  }, [presets]);

  // 变体1：左右布局，左侧为Input区域
  var getDefaultDisplayField = useCallback(function () {
    return {
      cashReceived: {
        visible: true,
        label: locales.getText('cash-keyboard-cash-received')
      },
      balanceDue: {
        visible: true,
        label: locales.getText('cash-keyboard-balance-due')
      },
      changeDue: {
        visible: true,
        label: locales.getText('cash-keyboard-change-due')
      },
      gridRatio: [2, 1, 1] // Cash Received 占 2 份，其他各占 1 份
    };
  }, []);

  // 默认配置
  var defaultTitleArea = {
    title: {
      visible: true
    },
    subtitle: {
      visible: true
    },
    alignment: 'space-between',
    padding: '0px'
  };

  // 合并配置
  var mergedTitleArea = useMemo(function () {
    return merge({}, defaultTitleArea, titleArea);
  }, [titleArea]);
  var mergedDisplayField = useMemo(function () {
    return merge({}, getDefaultDisplayField(), displayField);
  }, [getDefaultDisplayField, displayField]);

  // 渲染标题区域
  var renderTitleArea = useCallback(function () {
    var _ref = mergedTitleArea || {},
      title = _ref.title,
      subtitle = _ref.subtitle;
    if (!(title !== null && title !== void 0 && title.visible) && !(subtitle !== null && subtitle !== void 0 && subtitle.visible)) {
      return null;
    }
    if (!(title !== null && title !== void 0 && title.text) && !(subtitle !== null && subtitle !== void 0 && subtitle.text)) {
      return null;
    }
    var titleStyle = {
      display: 'flex',
      justifyContent: mergedTitleArea.alignment,
      alignItems: 'center',
      padding: mergedTitleArea.padding
    };
    return /*#__PURE__*/React.createElement("div", {
      style: titleStyle,
      className: "pisell-cash-keyboard-title"
    }, (title === null || title === void 0 ? void 0 : title.visible) && /*#__PURE__*/React.createElement("div", {
      style: {
        fontSize: title.fontSize,
        color: title.color,
        fontWeight: title.fontWeight
      }
    }, title.text), (subtitle === null || subtitle === void 0 ? void 0 : subtitle.visible) && /*#__PURE__*/React.createElement("div", {
      className: "pisell-cash-keyboard-subtitle",
      style: {
        fontSize: subtitle.fontSize,
        color: subtitle.color,
        fontWeight: subtitle.fontWeight
      }
    }, mergedTitleArea.subtitle.text));
  }, [mergedTitleArea]);

  // 计算栅格样式
  var getGridStyle = useCallback(function (index) {
    if (!mergedDisplayField.gridRatio) {
      return {
        flex: 1
      };
    }
    var ratio = mergedDisplayField.gridRatio[index] || 1;
    return {
      flex: ratio
    };
  }, [mergedDisplayField]);
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-cash-keyboard pisell-cash-keyboard-simple",
    style: _objectSpread({}, style || {})
  }, renderTitleArea(), /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      gap: '8px'
    }
  }, ((_mergedDisplayField$c = mergedDisplayField.cashReceived) === null || _mergedDisplayField$c === void 0 ? void 0 : _mergedDisplayField$c.visible) && /*#__PURE__*/React.createElement(VirtualInput, {
    focused: true,
    wrapperStyle: _objectSpread(_objectSpread({
      padding: '12px 20px',
      borderRadius: '8px',
      backgroundColor: 'white',
      boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.06)'
    }, getGridStyle(0)), {}, {
      overflow: 'hidden'
    }),
    topContent: /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#667085',
        fontSize: '12px',
        fontWeight: 500,
        lineHeight: '18px'
      }
    }, mergedDisplayField.cashReceived.label),
    value: internalValue ? "".concat(amountSymbol || '').concat(internalValue) : '',
    placeholder: placeholder,
    style: {
      fontSize: '24px',
      fontWeight: 'bold',
      border: 'none',
      background: 'transparent',
      width: '100%'
    },
    preventBlurElements: ["#".concat(uniqueKeyboardId), shortcutsRef]
  }), /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      flexDirection: 'column',
      flex: 1,
      borderRadius: '8px',
      backgroundColor: '#ffffff',
      padding: 8,
      boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.06)',
      overflow: 'hidden'
    }
  }, ((_mergedDisplayField$b = mergedDisplayField.balanceDue) === null || _mergedDisplayField$b === void 0 ? void 0 : _mergedDisplayField$b.visible) && /*#__PURE__*/React.createElement("div", {
    style: _objectSpread({}, getGridStyle(1))
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      color: '#667085',
      fontSize: '12px',
      fontWeight: 500,
      lineHeight: '18px'
    }
  }, mergedDisplayField.balanceDue.label), /*#__PURE__*/React.createElement("div", {
    style: {
      color: '#475467',
      fontSize: '14px',
      fontWeight: 700,
      lineHeight: '20px'
    }
  }, /*#__PURE__*/React.createElement(PisellText.Amount, {
    value: originalValue,
    hideDecimalForWholeNumbers: false,
    precision: 2
  }))), ((_mergedDisplayField$c2 = mergedDisplayField.changeDue) === null || _mergedDisplayField$c2 === void 0 ? void 0 : _mergedDisplayField$c2.visible) && /*#__PURE__*/React.createElement("div", {
    style: _objectSpread({}, getGridStyle(2))
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      color: '#667085',
      fontSize: '12px',
      fontWeight: 500,
      lineHeight: '18px'
    }
  }, mergedDisplayField.changeDue.label), /*#__PURE__*/React.createElement("div", {
    style: {
      color: '#475467',
      fontSize: '14px',
      fontWeight: 700,
      lineHeight: '20px'
    }
  }, /*#__PURE__*/React.createElement(PisellText.Amount, {
    value: changeDue,
    hideDecimalForWholeNumbers: false,
    precision: 2
  }))))), /*#__PURE__*/React.createElement(Shortcuts, {
    ref: shortcutsRef,
    presets: getDefaultPresets(),
    onChange: function onChange(v) {
      setInternalValue(v);
    }
  }), /*#__PURE__*/React.createElement(Keyboard, _extends({}, keyboardProps, {
    rightItems: rightItems,
    onChange: handleChange,
    id: uniqueKeyboardId
  })));
};
var CashKeyboardSimple = function CashKeyboardSimple(props) {
  var containerProps = props.containerProps,
    children = props.children,
    keyboardProps = _objectWithoutProperties(props, _excluded);
  var _ref2 = containerProps || {},
    renderType = _ref2.renderType,
    open = _ref2.open,
    restProps = _objectWithoutProperties(_ref2, _excluded2);
  if (!containerProps) {
    return /*#__PURE__*/React.createElement(CashKeyboardBase, keyboardProps);
  }

  // 暂时只支持受控模式
  if (renderType === 'popover') {
    return /*#__PURE__*/React.createElement(Popover, _extends({
      key: "".concat(open),
      open: open,
      trigger: "click",
      className: "pisell-cash-keyboard-container pisell-cash-keyboard-popover"
    }, restProps, {
      content: /*#__PURE__*/React.createElement(CashKeyboardBase, keyboardProps)
    }), children);
  }
  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: "pisell-payment-keyboard-container pisell-payment-keyboard-modal",
      destroyOnHidden: true
    }, restProps), /*#__PURE__*/React.createElement(CashKeyboardBase, keyboardProps)) : null;
  }
  return /*#__PURE__*/React.createElement(CashKeyboardBase, keyboardProps);
};
export default CashKeyboardSimple;