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 React, { forwardRef, useCallback, useImperativeHandle, useMemo, useState } from 'react';
import { PisellModal, Iconfont, Tag, Button } from '@pisell/materials';
import NumericStepper from "../../../../pro/NumericStepper";
import { locales } from '@pisell/utils';
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { getDenominationId, normalizeAmount } from "../../utils";
import useEngineContext from "../../../../hooks/useEngineContext";
import { useResponsive } from "../../../../hooks/useResponsive";
import "./index.less";
var PREFIX = 'pisell-private-cash-counting-modal';
var formatAmount = function formatAmount(value, symbol, precision) {
  var formatter = new Intl.NumberFormat(undefined, {
    minimumFractionDigits: precision,
    maximumFractionDigits: precision
  });
  return "".concat(symbol).concat(formatter.format(value));
};
var CashCountingModal = /*#__PURE__*/forwardRef(function (props, ref) {
  var _context$appHelper;
  var currencyCode = props.currencyCode,
    currencyDenominations = props.currencyDenominations,
    decimalPlaces = props.decimalPlaces,
    symbol = props.symbol,
    modalWidth = props.modalWidth,
    onCancel = props.onCancel,
    onConfirm = props.onConfirm;
  var context = useEngineContext();
  var _ref = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    isTerminal = _ref.isTerminal;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = useState({}),
    _useState4 = _slicedToArray(_useState3, 2),
    draftQuantities = _useState4[0],
    setDraftQuantities = _useState4[1];
  var isIpad = useResponsive(1200);
  var isMobile = useResponsive(450);

  // 暴露 ref 方法
  useImperativeHandle(ref, function () {
    return {
      open: function open(_ref2) {
        var initialQuantities = _ref2.initialQuantities;
        setDraftQuantities(initialQuantities);
        setOpen(true);
      },
      close: function close() {
        return setOpen(false);
      }
    };
  });

  // 计算
  var groupedDenominations = useMemo(function () {
    return currencyDenominations.reduce(function (acc, item) {
      acc[item.denomination_type].push(item);
      return acc;
    }, {
      bill: [],
      coin: []
    });
  }, [currencyDenominations]);
  var calculatedDetails = useMemo(function () {
    return currencyDenominations.map(function (d) {
      var _draftQuantities$getD;
      var qty = (_draftQuantities$getD = draftQuantities[getDenominationId(d)]) !== null && _draftQuantities$getD !== void 0 ? _draftQuantities$getD : 0;
      return {
        denomination: d,
        quantity: qty,
        amount: normalizeAmount(d.denomination_value * qty, decimalPlaces)
      };
    });
  }, [currencyDenominations, draftQuantities, decimalPlaces, getDenominationId, normalizeAmount]);
  var billSubtotal = useMemo(function () {
    return calculatedDetails.filter(function (i) {
      return i.denomination.denomination_type === 'bill';
    }).reduce(function (s, i) {
      return s + i.amount;
    }, 0);
  }, [calculatedDetails]);
  var coinSubtotal = useMemo(function () {
    return calculatedDetails.filter(function (i) {
      return i.denomination.denomination_type === 'coin';
    }).reduce(function (s, i) {
      return s + i.amount;
    }, 0);
  }, [calculatedDetails]);
  var totalAmount = useMemo(function () {
    return billSubtotal + coinSubtotal;
  }, [billSubtotal, coinSubtotal]);

  // 操作
  var handleClose = function handleClose() {
    setOpen(false);
    if (typeof onCancel === 'function') {
      onCancel();
    }
  };
  var handleClear = function handleClear() {
    var reset = {};
    currencyDenominations.forEach(function (d) {
      return reset[getDenominationId(d)] = 0;
    });
    setDraftQuantities(reset);
  };
  var handleConfirm = function handleConfirm() {
    var payload = {
      amount: totalAmount,
      currencyCode: currencyCode,
      decimalPlaces: decimalPlaces,
      billSubtotal: billSubtotal,
      coinSubtotal: coinSubtotal,
      details: calculatedDetails,
      quantities: draftQuantities
    };
    if (typeof onConfirm === 'function') {
      onConfirm(payload);
    }
    setOpen(false);
  };
  var renderSection = function renderSection(type, title, subtotal) {
    var items = groupedDenominations[type];
    if (!items.length) return null;
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__section")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__section-header")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__section-title")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__dot ").concat(PREFIX, "__dot--").concat(type)
    }), /*#__PURE__*/React.createElement("span", null, title)), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__section-subtotal")
    }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell-cash-counting.subtotal')), /*#__PURE__*/React.createElement("strong", null, formatAmount(subtotal, symbol, decimalPlaces)))), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__denomination-list")
    }, items.map(function (item) {
      var _draftQuantities$id;
      var id = getDenominationId(item);
      var qty = (_draftQuantities$id = draftQuantities[id]) !== null && _draftQuantities$id !== void 0 ? _draftQuantities$id : 0;
      var amt = normalizeAmount(item.denomination_value * qty, decimalPlaces);
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "__denomination-row"),
        key: id
      }, /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "__denomination-left")
      }, /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "__denomination-label ").concat(PREFIX, "__denomination-label--").concat(type)
      }, item.denomination_label), /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "__stepper-wrap")
      }, /*#__PURE__*/React.createElement(NumericStepper, {
        className: "".concat(PREFIX, "__stepper"),
        min: 0,
        max: 9999,
        value: qty,
        plusOnlyAtZero: false,
        shape: "square",
        onChange: function onChange(val) {
          return setDraftQuantities(function (prev) {
            return _objectSpread(_objectSpread({}, prev), {}, _defineProperty({}, id, val));
          });
        }
      }))), /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "__row-amount")
      }, formatAmount(amt, symbol, decimalPlaces)));
    })));
  };
  var renderHeader = useCallback(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__modal-header")
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-cash",
      className: "".concat(PREFIX, "__modal-header-icon")
    }), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__modal-header-title")
    }, locales.getText('pisell-cash-counting.countCash')), /*#__PURE__*/React.createElement(Tag, {
      color: "blue",
      style: {
        border: 'none'
      }
    }, currencyCode));
  }, [currencyCode]);
  var renderFooter = useCallback(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__footer")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__summary")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__summary-row")
    }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell-cash-counting.billsSubtotal')), /*#__PURE__*/React.createElement("strong", null, formatAmount(billSubtotal, symbol, decimalPlaces))), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__summary-row")
    }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell-cash-counting.coinsSubtotal')), /*#__PURE__*/React.createElement("strong", null, formatAmount(coinSubtotal, symbol, decimalPlaces))), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__total-row")
    }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell-cash-counting.total')), /*#__PURE__*/React.createElement("strong", null, formatAmount(totalAmount, symbol, decimalPlaces)))), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__actions")
    }, /*#__PURE__*/React.createElement(Button, {
      type: "text",
      size: "large",
      onClick: handleClear
    }, locales.getText('pisell-cash-counting.clearAll')), /*#__PURE__*/React.createElement(Button, {
      size: "large",
      onClick: handleClose
    }, locales.getText('pisell-cash-counting.cancel')), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      size: "large",
      disabled: !currencyDenominations.length,
      onClick: handleConfirm
    }, locales.getText('pisell-cash-counting.confirm'))));
  }, [coinSubtotal, billSubtotal, totalAmount, currencyDenominations, handleClear, handleClose, handleConfirm]);
  return /*#__PURE__*/React.createElement(PisellModal, {
    destroyOnClose: true,
    maskClosable: false,
    footer: renderFooter(),
    open: open,
    title: renderHeader(),
    className: "".concat(PREFIX, "__modal-wrap"),
    bodyStyle: {
      padding: 0
    },
    width: modalWidth ? modalWidth : isTerminal !== null && isTerminal !== void 0 && isTerminal() ? '80%' : '880px',
    onCancel: handleClose
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__modal")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__modal-intro")
  }, /*#__PURE__*/React.createElement(ExclamationCircleOutlined, {
    style: {
      fontSize: 18,
      color: '#F2A63A'
    }
  }), locales.getText('pisell-cash-counting.subtitle')), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__scroll ").concat(isIpad || isMobile ? "".concat(PREFIX, "__scroll-column") : '', " ").concat(isMobile ? "".concat(PREFIX, "__scroll-mobile") : '')
  }, currencyDenominations.length === 0 ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__empty")
  }, locales.getText('pisell-cash-counting.empty')) : /*#__PURE__*/React.createElement(React.Fragment, null, renderSection('bill', locales.getText('pisell-cash-counting.bills'), billSubtotal), renderSection('coin', locales.getText('pisell-cash-counting.coins'), coinSubtotal)))));
});
export default CashCountingModal;