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); }
import React, { useMemo, useCallback } from 'react';
import classNames from 'classnames';
import { PisellHierarchicalSummaryList } from '@pisell/materials';
import { locales, formatAmountWithOptions } from '@pisell/utils';
import { buildSummaryItems } from "./utils";
import { Collapse } from "./components/Collapse";
import "./PisellFinancialSummary.less";
var PREFIX_CLS = 'pisell-financial-summary';

/** 与 PisellHierarchicalSummaryList levelConfig 结构兼容，避免从 @pisell/materials 导入类型时的 TS2709 */

/**
 * 层级约定：首行「应付余额」为主标题（level 1），「费用合计 / 付款历史 / 退款」为二级标题（level 2），其下为明细（level 3+）。
 * 付款历史、退款展开后内置使用 Collapse 展示每条记录。
 */
var FIGMA_GAPS = {
  row: 8,
  rowLeft: 8,
  meta: 4,
  rowRight: 6
};
var DEFAULT_LEVEL_CONFIG = {
  1: {
    labelTextStyle: {
      fontSize: 16,
      fontWeight: 700,
      color: '#1B1B1B',
      lineHeight: '24px'
    },
    valueTextStyle: {
      fontSize: 16,
      fontWeight: 700,
      color: '#DC6803',
      lineHeight: '24px'
    },
    expandIconStyle: {
      size: 16,
      width: 16,
      height: 16
    }
  },
  2: {
    labelTextStyle: {
      fontSize: 16,
      fontWeight: 700,
      color: '#1B1B1B',
      lineHeight: '24px'
    },
    valueTextStyle: {
      fontSize: 16,
      fontWeight: 700,
      color: '#DC6803',
      lineHeight: '24px'
    },
    expandIconStyle: {
      size: 16,
      width: 16,
      height: 16
    },
    divider: {
      show: true,
      color: '#D0D5DD',
      style: 'solid'
    },
    showDotSeparator: false
  },
  3: {
    labelTextStyle: {
      fontSize: 16,
      fontWeight: 500,
      color: '#000000',
      lineHeight: '24px'
    },
    valueTextStyle: {
      fontSize: 16,
      fontWeight: 500,
      color: '#000000',
      lineHeight: '24px'
    },
    metaTextStyle: {
      fontSize: 16,
      fontWeight: 400,
      color: '#667085',
      lineHeight: '24px'
    },
    infoIconStyle: {
      size: 16,
      width: 16,
      height: 16
    }
  }
};
export var PisellFinancialSummary = /*#__PURE__*/React.memo(function (_ref) {
  var _data$paid$length, _data$paid2, _data$refund$length, _data$refund2;
  var data = _ref.data,
    _ref$showTotal = _ref.showTotal,
    showTotal = _ref$showTotal === void 0 ? true : _ref$showTotal,
    _ref$showPaid = _ref.showPaid,
    showPaid = _ref$showPaid === void 0 ? true : _ref$showPaid,
    _ref$showRefund = _ref.showRefund,
    showRefund = _ref$showRefund === void 0 ? true : _ref$showRefund,
    _ref$showItemsCount = _ref.showItemsCount,
    showItemsCount = _ref$showItemsCount === void 0 ? true : _ref$showItemsCount,
    _ref$showInfoIcon = _ref.showInfoIcon,
    showInfoIcon = _ref$showInfoIcon === void 0 ? true : _ref$showInfoIcon,
    _ref$hideZeroAmountRo = _ref.hideZeroAmountRows,
    hideZeroAmountRows = _ref$hideZeroAmountRo === void 0 ? false : _ref$hideZeroAmountRo,
    titleBalanceDue = _ref.titleBalanceDue,
    titleTotal = _ref.titleTotal,
    titlePaid = _ref.titlePaid,
    titleRefund = _ref.titleRefund,
    _ref$currencySymbol = _ref.currencySymbol,
    currencySymbol = _ref$currencySymbol === void 0 ? '' : _ref$currencySymbol,
    _ref$amountPrecision = _ref.amountPrecision,
    amountPrecision = _ref$amountPrecision === void 0 ? 2 : _ref$amountPrecision,
    _ref$useThousandsSepa = _ref.useThousandsSeparator,
    useThousandsSeparator = _ref$useThousandsSepa === void 0 ? false : _ref$useThousandsSepa,
    _ref$hideDecimalForWh = _ref.hideDecimalForWholeNumbers,
    hideDecimalForWholeNumbers = _ref$hideDecimalForWh === void 0 ? true : _ref$hideDecimalForWh,
    _ref$missingValuePlac = _ref.missingValuePlaceholder,
    missingValuePlaceholder = _ref$missingValuePlac === void 0 ? '—' : _ref$missingValuePlac,
    _ref$defaultExpandedL = _ref.defaultExpandedLevel,
    defaultExpandedLevel = _ref$defaultExpandedL === void 0 ? 0 : _ref$defaultExpandedL,
    className = _ref.className,
    style = _ref.style;
  var formatOpts = useMemo(function () {
    return {
      precision: amountPrecision !== null && amountPrecision !== void 0 ? amountPrecision : 2,
      showCurrencySymbol: !!currencySymbol,
      useThousandsSeparator: useThousandsSeparator !== null && useThousandsSeparator !== void 0 ? useThousandsSeparator : false,
      hideDecimalForWholeNumbers: hideDecimalForWholeNumbers !== null && hideDecimalForWholeNumbers !== void 0 ? hideDecimalForWholeNumbers : true
    };
  }, [amountPrecision, currencySymbol, useThousandsSeparator, hideDecimalForWholeNumbers]);
  var formatAmountDisplay = useCallback(function (amount) {
    return formatAmountWithOptions(amount, currencySymbol !== null && currencySymbol !== void 0 ? currencySymbol : '', formatOpts);
  }, [currencySymbol, formatOpts]);
  var getTitle = useCallback(function (key, override) {
    return override !== undefined ? override : locales.getText(key);
  }, [titleBalanceDue, titleTotal, titlePaid, titleRefund]);
  var paidSum = useMemo(function () {
    var _data$paid;
    return ((_data$paid = data.paid) !== null && _data$paid !== void 0 ? _data$paid : []).reduce(function (s, p) {
      return s + p.amount;
    }, 0);
  }, [data.paid]);
  var refundSum = useMemo(function () {
    var _data$refund;
    return ((_data$refund = data.refund) !== null && _data$refund !== void 0 ? _data$refund : []).reduce(function (s, r) {
      return s + r.amount;
    }, 0);
  }, [data.refund]);
  var useCollapseForPaidRefund = showPaid !== false && ((_data$paid$length = (_data$paid2 = data.paid) === null || _data$paid2 === void 0 ? void 0 : _data$paid2.length) !== null && _data$paid$length !== void 0 ? _data$paid$length : 0) > 0 || showRefund !== false && ((_data$refund$length = (_data$refund2 = data.refund) === null || _data$refund2 === void 0 ? void 0 : _data$refund2.length) !== null && _data$refund$length !== void 0 ? _data$refund$length : 0) > 0;
  var items = useMemo(function () {
    var _root$children, _data$paid$length2, _data$paid3, _data$refund$length2, _data$refund3;
    var base = buildSummaryItems(data, {
      currencySymbol: currencySymbol,
      amountPrecision: amountPrecision,
      useThousandsSeparator: useThousandsSeparator,
      hideDecimalForWholeNumbers: hideDecimalForWholeNumbers,
      showItemsCount: showItemsCount,
      showInfoIcon: showInfoIcon,
      hideZeroAmountRows: hideZeroAmountRows,
      missingValuePlaceholder: missingValuePlaceholder,
      getText: function getText(key) {
        return locales.getText(key);
      },
      titleBalanceDue: titleBalanceDue,
      titleTotal: titleTotal,
      titlePaid: titlePaid,
      titleRefund: titleRefund,
      showTotal: showTotal,
      showPaid: useCollapseForPaidRefund ? false : showPaid,
      showRefund: useCollapseForPaidRefund ? false : showRefund,
      skipPaidAndRefund: useCollapseForPaidRefund
    });
    if (!useCollapseForPaidRefund) return base;
    var list = base.slice();
    var root = list[0];
    var group = root === null || root === void 0 || (_root$children = root.children) === null || _root$children === void 0 ? void 0 : _root$children[0];
    if (!(group !== null && group !== void 0 && group.children)) return base;
    var newChildren = group.children.slice();
    if (showPaid !== false && ((_data$paid$length2 = (_data$paid3 = data.paid) === null || _data$paid3 === void 0 ? void 0 : _data$paid3.length) !== null && _data$paid$length2 !== void 0 ? _data$paid$length2 : 0) > 0) {
      var _data$paid4;
      newChildren.push({
        key: 'paid',
        label: getTitle('pisell2.financialSummary.paid', titlePaid),
        value: formatAmountDisplay(paidSum),
        expandedContent: /*#__PURE__*/React.createElement("div", {
          className: "".concat(PREFIX_CLS, "-collapse-list"),
          style: {
            marginTop: 8
          }
        }, ((_data$paid4 = data.paid) !== null && _data$paid4 !== void 0 ? _data$paid4 : []).map(function (p, i) {
          var _p$key;
          return /*#__PURE__*/React.createElement(PaymentCollapseItem, {
            key: (_p$key = p.key) !== null && _p$key !== void 0 ? _p$key : i,
            item: p,
            formatAmount: formatAmountDisplay
          });
        }))
      });
    }
    if (showRefund !== false && ((_data$refund$length2 = (_data$refund3 = data.refund) === null || _data$refund3 === void 0 ? void 0 : _data$refund3.length) !== null && _data$refund$length2 !== void 0 ? _data$refund$length2 : 0) > 0) {
      var _data$refund4;
      newChildren.push({
        key: 'refund',
        label: getTitle('pisell2.financialSummary.refund', titleRefund),
        value: formatAmountDisplay(refundSum),
        expandedContent: /*#__PURE__*/React.createElement("div", {
          className: "".concat(PREFIX_CLS, "-collapse-list"),
          style: {
            marginTop: 8
          }
        }, ((_data$refund4 = data.refund) !== null && _data$refund4 !== void 0 ? _data$refund4 : []).map(function (r, i) {
          var _r$key;
          return /*#__PURE__*/React.createElement(RefundCollapseItem, {
            key: (_r$key = r.key) !== null && _r$key !== void 0 ? _r$key : i,
            item: r,
            formatAmount: formatAmountDisplay
          });
        }))
      });
    }
    return [_objectSpread(_objectSpread({}, root), {}, {
      children: [_objectSpread(_objectSpread({}, group), {}, {
        children: newChildren
      })]
    })];
  }, [data, currencySymbol, amountPrecision, useThousandsSeparator, hideDecimalForWholeNumbers, showItemsCount, showInfoIcon, hideZeroAmountRows, missingValuePlaceholder, titleBalanceDue, titleTotal, titlePaid, titleRefund, showTotal, showPaid, showRefund, getTitle, formatAmountDisplay, paidSum, refundSum, useCollapseForPaidRefund]);
  return /*#__PURE__*/React.createElement("div", {
    className: classNames(PREFIX_CLS, className),
    style: style
  }, /*#__PURE__*/React.createElement(PisellHierarchicalSummaryList, {
    items: items,
    indent: 16,
    rowGap: 8,
    padding: 20,
    gaps: FIGMA_GAPS,
    levelConfig: DEFAULT_LEVEL_CONFIG,
    defaultExpandedLevel: defaultExpandedLevel
  }));
});
function paymentToCollapseProps(p, formatAmount) {
  var _p$bodyRows$length, _p$bodyRows, _p$bodyRows2, _p$methodName;
  var bodyRows = ((_p$bodyRows$length = (_p$bodyRows = p.bodyRows) === null || _p$bodyRows === void 0 ? void 0 : _p$bodyRows.length) !== null && _p$bodyRows$length !== void 0 ? _p$bodyRows$length : 0) > 0 ? ((_p$bodyRows2 = p.bodyRows) !== null && _p$bodyRows2 !== void 0 ? _p$bodyRows2 : []).map(function (r) {
    var _r$amount;
    return {
      label: r.label,
      amount: (_r$amount = r.amount) !== null && _r$amount !== void 0 ? _r$amount : formatAmount(p.amount),
      action: r.action
    };
  }) : [{
    label: (_p$methodName = p.methodName) !== null && _p$methodName !== void 0 ? _p$methodName : '—',
    amount: formatAmount(p.amount),
    action: {
      label: 'Void',
      onClick: undefined
    }
  }];
  return {
    headMeta: {
      time: p.time,
      date: p.date,
      customer: p.customer,
      channel: p.channel
    },
    headAmount: formatAmount(p.amount),
    bodyRows: bodyRows
  };
}
function PaymentCollapseItem(_ref2) {
  var item = _ref2.item,
    formatAmount = _ref2.formatAmount;
  var _useMemo = useMemo(function () {
      return paymentToCollapseProps(item, formatAmount);
    }, [item, formatAmount]),
    headMeta = _useMemo.headMeta,
    headAmount = _useMemo.headAmount,
    bodyRows = _useMemo.bodyRows;
  return /*#__PURE__*/React.createElement(Collapse, {
    headMeta: headMeta,
    headAmount: headAmount,
    defaultExpanded: true,
    bodyRows: bodyRows
  });
}
function RefundCollapseItem(_ref3) {
  var _item$bodyRows$length, _item$bodyRows, _item$bodyRows2, _item$label;
  var item = _ref3.item,
    formatAmount = _ref3.formatAmount;
  var bodyRows = ((_item$bodyRows$length = (_item$bodyRows = item.bodyRows) === null || _item$bodyRows === void 0 ? void 0 : _item$bodyRows.length) !== null && _item$bodyRows$length !== void 0 ? _item$bodyRows$length : 0) > 0 ? (_item$bodyRows2 = item.bodyRows) !== null && _item$bodyRows2 !== void 0 ? _item$bodyRows2 : [] : [{
    label: (_item$label = item.label) !== null && _item$label !== void 0 ? _item$label : '—',
    amount: formatAmount(item.amount),
    action: {
      label: 'Void',
      onClick: undefined
    }
  }];
  return /*#__PURE__*/React.createElement(Collapse, {
    headMeta: {
      time: item.time,
      date: item.date,
      customer: item.customer,
      channel: item.channel
    },
    headAmount: formatAmount(item.amount),
    defaultExpanded: true,
    bodyRows: bodyRows
  });
}
PisellFinancialSummary.displayName = 'PisellFinancialSummary';