function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
import { formatAmountWithOptions } from '@pisell/utils';

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

function formatAmount(amount, options) {
  var _options$currencySymb, _options$amountPrecis, _options$useThousands, _options$hideDecimalF;
  if (amount == null || typeof amount === 'number' && Number.isNaN(amount)) {
    var _options$missingValue;
    return (_options$missingValue = options.missingValuePlaceholder) !== null && _options$missingValue !== void 0 ? _options$missingValue : '—';
  }
  var symbol = (_options$currencySymb = options.currencySymbol) !== null && _options$currencySymb !== void 0 ? _options$currencySymb : '';
  return formatAmountWithOptions(amount, symbol, {
    precision: (_options$amountPrecis = options.amountPrecision) !== null && _options$amountPrecis !== void 0 ? _options$amountPrecis : 2,
    showCurrencySymbol: !!symbol,
    useThousandsSeparator: (_options$useThousands = options.useThousandsSeparator) !== null && _options$useThousands !== void 0 ? _options$useThousands : false,
    hideDecimalForWholeNumbers: (_options$hideDecimalF = options.hideDecimalForWholeNumbers) !== null && _options$hideDecimalF !== void 0 ? _options$hideDecimalF : true
  });
}
function lineItemToSummary(item, options, level) {
  var _options$missingValue2, _item$children, _item$key;
  if (options.hideZeroAmountRows && item.value === 0) return null;
  var valueDisplay = item.value != null && !Number.isNaN(Number(item.value)) ? formatAmount(Number(item.value), options) : (_options$missingValue2 = options.missingValuePlaceholder) !== null && _options$missingValue2 !== void 0 ? _options$missingValue2 : '—';
  var children = ((_item$children = item.children) !== null && _item$children !== void 0 ? _item$children : []).map(function (c) {
    return lineItemToSummary(c, options, level + 1);
  }).filter(function (x) {
    return x != null;
  });
  return {
    key: (_item$key = item.key) !== null && _item$key !== void 0 ? _item$key : "line-".concat(level, "-").concat(item.label),
    label: item.label,
    value: valueDisplay,
    children: children.length > 0 ? children : undefined,
    itemsCount: options.showItemsCount ? item.itemsCount : undefined,
    infoTooltip: options.showInfoIcon ? item.infoTooltip : undefined
  };
}
function totalBlockToChildren(block, options) {
  var _block$children;
  if (!(block !== null && block !== void 0 && (_block$children = block.children) !== null && _block$children !== void 0 && _block$children.length)) return [];
  return block.children.map(function (c) {
    return lineItemToSummary(c, options, 2);
  }).filter(function (x) {
    return x != null;
  });
}
function sumLineItems(items) {
  var sum = 0;
  var _iterator = _createForOfIteratorHelper(items),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _item$children2;
      var item = _step.value;
      if (typeof item.value === 'number' && !Number.isNaN(item.value)) {
        sum += item.value;
      }
      if ((_item$children2 = item.children) !== null && _item$children2 !== void 0 && _item$children2.length) {
        sum += sumLineItems(item.children);
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return sum;
}
function paymentToItem(p, options) {
  var _p$methodName, _p$time, _p$key;
  var labelParts = [(_p$methodName = p.methodName) !== null && _p$methodName !== void 0 ? _p$methodName : '', (_p$time = p.time) !== null && _p$time !== void 0 ? _p$time : ''].filter(Boolean);
  var label = labelParts.length > 0 ? labelParts.join(' · ') : undefined;
  return {
    key: (_p$key = p.key) !== null && _p$key !== void 0 ? _p$key : "paid-".concat(p.amount, "-").concat(p.methodName),
    label: label !== null && label !== void 0 ? label : '—',
    value: formatAmount(p.amount, options),
    extra: p.detail
  };
}
function refundToItem(r, options) {
  var _r$key, _r$label;
  return {
    key: (_r$key = r.key) !== null && _r$key !== void 0 ? _r$key : "refund-".concat(r.amount, "-").concat(r.label),
    label: (_r$label = r.label) !== null && _r$label !== void 0 ? _r$label : '—',
    value: formatAmount(r.amount, options),
    extra: r.detail
  };
}

/**
 * 将 FinancialSummaryData 转为 PisellHierarchicalSummaryList 所需的 items
 */
export function buildSummaryItems(data, options) {
  var _data$paid, _data$refund;
  var items = [];
  var getTitle = function getTitle(key, override) {
    return override !== undefined ? override : options.getText(key);
  };

  // 1. 费用合计 / 付款历史 / 退款 同属一个父级（仅作为分组，不渲染父级行）
  var secondary = [];
  if (options.showTotal !== false && data.total) {
    var _data$total$children;
    var totalChildren = totalBlockToChildren(data.total, options);
    var totalValueRaw = data.total.value != null && !Number.isNaN(Number(data.total.value)) ? Number(data.total.value) : (_data$total$children = data.total.children) !== null && _data$total$children !== void 0 && _data$total$children.length ? sumLineItems(data.total.children) : undefined;
    var totalValue = totalValueRaw !== undefined && !Number.isNaN(totalValueRaw) ? formatAmount(totalValueRaw, options) : undefined;
    secondary.push({
      key: 'total',
      label: getTitle('pisell2.financialSummary.total', options.titleTotal),
      value: totalValue,
      children: totalChildren.length > 0 ? totalChildren : undefined
    });
  }
  if (!options.skipPaidAndRefund && options.showPaid !== false && (_data$paid = data.paid) !== null && _data$paid !== void 0 && _data$paid.length) {
    var paidChildren = data.paid.map(function (p) {
      return paymentToItem(p, options);
    });
    secondary.push({
      key: 'paid',
      label: getTitle('pisell2.financialSummary.paid', options.titlePaid),
      children: paidChildren
    });
  }
  if (!options.skipPaidAndRefund && options.showRefund !== false && (_data$refund = data.refund) !== null && _data$refund !== void 0 && _data$refund.length) {
    var refundChildren = data.refund.map(function (r) {
      return refundToItem(r, options);
    });
    secondary.push({
      key: 'refund',
      label: getTitle('pisell2.financialSummary.refund', options.titleRefund),
      children: refundChildren
    });
  }

  // 2. 一级标题：应付余额，其 children 为上述分组（支持展开/收起）
  var groupNode = secondary.length > 0 ? {
    key: 'summary-sections',
    label: '',
    value: undefined,
    children: secondary
  } : {
    key: 'summary-sections',
    label: '',
    value: undefined,
    children: []
  };
  items.push({
    key: 'balance-due',
    label: getTitle('pisell2.financialSummary.balanceDue', options.titleBalanceDue),
    value: formatAmount(data.balanceDue, options),
    children: secondary.length > 0 ? [groupNode] : undefined
  });
  return items;
}