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 { useCallback, useMemo, useRef, useState } from 'react';
import { message } from 'antd';
import { locales } from '@pisell/utils';
import { buildEmptyQuantities, getEffectiveDenominationsForCurrency } from "./utils";
import useEngineContext from "../../hooks/useEngineContext";
export function usePisellCashCounting(_ref) {
  var _context$appHelper, _store$getState2, _currencyDenomination3;
  var value = _ref.value,
    _ref$defaultValue = _ref.defaultValue,
    defaultValue = _ref$defaultValue === void 0 ? '' : _ref$defaultValue,
    currencyCode = _ref.currencyCode,
    currencySymbol = _ref.currencySymbol,
    amountPrecision = _ref.amountPrecision,
    _ref$denominations = _ref.denominations,
    denominations = _ref$denominations === void 0 ? [] : _ref$denominations,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$countDisabled = _ref.countDisabled,
    countDisabled = _ref$countDisabled === void 0 ? false : _ref$countDisabled,
    onChange = _ref.onChange,
    onCountConfirm = _ref.onCountConfirm,
    onCountCancel = _ref.onCountCancel;
  var context = useEngineContext();
  var _ref2 = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    store = _ref2.store;
  var modalRef = useRef(null);
  var triggerRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    keyboardOpen = _useState2[0],
    setKeyboardOpen = _useState2[1];
  var _useState3 = useState(defaultValue),
    _useState4 = _slicedToArray(_useState3, 2),
    internalValue = _useState4[0],
    setInternalValue = _useState4[1];
  var _useState5 = useState({}),
    _useState6 = _slicedToArray(_useState5, 2),
    confirmedQuantities = _useState6[0],
    setConfirmedQuantities = _useState6[1];
  // 数钱结果
  var countedResultRef = useRef(null);
  // 手动输入金额
  var manualInputValueRef = useRef(null);
  // 手动输入金额与数钱总额不一致时弹窗
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    manualCountMismatchOpen = _useState8[0],
    setManualCountMismatchOpen = _useState8[1];
  var globalConfig = useMemo(function () {
    var _store$getState;
    var global = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 ? void 0 : _store$getState.global) || {};
    return {
      symbol: (global === null || global === void 0 ? void 0 : global.symbol) || '$',
      currency_code: (global === null || global === void 0 ? void 0 : global.currency_code) || 'AUD'
    };
  }, [store === null || store === void 0 || (_store$getState2 = store.getState) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.call(store)) === null || _store$getState2 === void 0 ? void 0 : _store$getState2.global]);
  var _currencyCode = useMemo(function () {
    return currencyCode || (globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.currency_code);
  }, [currencyCode, globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.currency_code]);
  var currencyDenominations = useMemo(function () {
    return getEffectiveDenominationsForCurrency(denominations, _currencyCode);
  }, [_currencyCode, denominations]);
  var decimalPlaces = useMemo(function () {
    var _currencyDenomination, _currencyDenomination2;
    if (typeof amountPrecision === 'number') {
      return amountPrecision;
    }
    return (_currencyDenomination = (_currencyDenomination2 = currencyDenominations[0]) === null || _currencyDenomination2 === void 0 ? void 0 : _currencyDenomination2.decimal_places) !== null && _currencyDenomination !== void 0 ? _currencyDenomination : 2;
  }, [amountPrecision, (_currencyDenomination3 = currencyDenominations[0]) === null || _currencyDenomination3 === void 0 ? void 0 : _currencyDenomination3.decimal_places]);
  var symbolValue = useMemo(function () {
    if (currencySymbol) {
      return currencySymbol;
    }
    return globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.symbol;
  }, [currencySymbol, globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.symbol]);
  var currentValue = useMemo(function () {
    return String(value !== null && value !== void 0 ? value : internalValue);
  }, [value, internalValue]);
  var updateAmount = useCallback(function (nextValue, source) {
    if (value === undefined) {
      setInternalValue(nextValue);
    }
    if (typeof onChange === 'function') {
      onChange(nextValue, {
        source: source
      });
    }
  }, [decimalPlaces, onChange, value]);

  /**
   * @description: 价格键盘输入
   * @return {*}
   */
  var handleAmountChange = useCallback(function (nextValue) {
    manualInputValueRef.current = nextValue;
    updateAmount(String(nextValue), 'manual');
  }, [updateAmount]);

  /**
   * @description: 价格键盘关闭
   * @return {*}
   */
  var handleKeyboardClose = useCallback(function () {
    var _countedResultRef$cur;
    setKeyboardOpen(false);
    // 手动输入金额与数钱总额不一致时弹窗
    if ((_countedResultRef$cur = countedResultRef.current) !== null && _countedResultRef$cur !== void 0 && _countedResultRef$cur.amount && Number(countedResultRef.current.amount) !== Number(manualInputValueRef.current)) {
      setManualCountMismatchOpen(true);
    }
  }, [setManualCountMismatchOpen]);

  /**
   * @description: 使用数钱金额
   * @param {*} useCallback
   * @return {*}
   */
  var confirmUseCountedTotal = useCallback(function () {
    var _countedResultRef$cur2, _countedResultRef$cur3;
    updateAmount((_countedResultRef$cur2 = (_countedResultRef$cur3 = countedResultRef.current) === null || _countedResultRef$cur3 === void 0 ? void 0 : _countedResultRef$cur3.amount) !== null && _countedResultRef$cur2 !== void 0 ? _countedResultRef$cur2 : '', 'count');
    setManualCountMismatchOpen(false);
  }, [updateAmount]);

  /**
   * @description: 保留手动金额
   * @param {*} useCallback
   * @return {*}
   */
  var confirmKeepManualAmount = useCallback(function () {
    var _manualInputValueRef$;
    // 保留手动金额时清空数钱结果与面额数量，避免再次打开数钱仍带回旧数据
    countedResultRef.current = null;
    setConfirmedQuantities({});
    updateAmount((_manualInputValueRef$ = manualInputValueRef.current) !== null && _manualInputValueRef$ !== void 0 ? _manualInputValueRef$ : '', 'manual');
    setManualCountMismatchOpen(false);
  }, [updateAmount]);
  var openCountModal = useCallback(function () {
    var _modalRef$current;
    if (disabled || countDisabled) {
      return;
    }
    if (currencyDenominations.length === 0) {
      message.warning(locales.getText('pisell-cash-counting.no-country-config'));
      return;
    }
    var initialQuantities = _objectSpread(_objectSpread({}, buildEmptyQuantities(currencyDenominations)), confirmedQuantities);
    setKeyboardOpen(false);
    (_modalRef$current = modalRef.current) === null || _modalRef$current === void 0 || _modalRef$current.open({
      initialQuantities: initialQuantities
    });
  }, [confirmedQuantities, countDisabled, currencyDenominations, disabled]);
  var handleCountCancel = useCallback(function () {
    onCountCancel === null || onCountCancel === void 0 || onCountCancel();
  }, [onCountCancel]);
  var handleCountConfirm = useCallback(function (payload) {
    countedResultRef.current = payload;
    setConfirmedQuantities(payload.quantities);
    updateAmount(payload.amount, 'count');
    if (typeof onCountConfirm === 'function') {
      onCountConfirm(payload);
    }
  }, [onCountConfirm, updateAmount]);
  return {
    modalRef: modalRef,
    triggerRef: triggerRef,
    keyboardOpen: keyboardOpen,
    setKeyboardOpen: setKeyboardOpen,
    currencyDenominations: currencyDenominations,
    decimalPlaces: decimalPlaces,
    symbol: symbolValue,
    currencyCode: _currencyCode,
    currentValue: currentValue,
    handleAmountChange: handleAmountChange,
    handleKeyboardClose: handleKeyboardClose,
    openCountModal: openCountModal,
    handleCountCancel: handleCountCancel,
    handleCountConfirm: handleCountConfirm,
    manualCountMismatchOpen: manualCountMismatchOpen,
    confirmUseCountedTotal: confirmUseCountedTotal,
    confirmKeepManualAmount: confirmKeepManualAmount
  };
}