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 _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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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 React, { useCallback, useMemo } from 'react';
import { Tooltip } from 'antd';
import { QuestionCircleOutlined, UpOutlined } from '@ant-design/icons';
import classNames from 'classnames';
/** 取当前层级的配置，若无则回退到上一层级（便于 L2+ 共用同一套样式） */
function getLevelCfg(levelConfig, level) {
  for (var lv = level; lv >= 1; lv--) {
    var cfg = levelConfig === null || levelConfig === void 0 ? void 0 : levelConfig[lv];
    if (cfg) return cfg;
  }
  return undefined;
}
function normalizeChildren(children) {
  if (!(children !== null && children !== void 0 && children.length)) return [];
  return children.filter(function (c) {
    return !c.hidden;
  }).slice().sort(function (a, b) {
    var _a$order, _b$order;
    return ((_a$order = a.order) !== null && _a$order !== void 0 ? _a$order : 0) - ((_b$order = b.order) !== null && _b$order !== void 0 ? _b$order : 0);
  });
}
function defaultGetNumberValue(item) {
  return typeof item.value === 'number' ? item.value : null;
}
function aggregateSum(item, getNumberValue) {
  var children = normalizeChildren(item.children);
  if (!children.length) return 0;
  var sum = 0;
  var _iterator = _createForOfIteratorHelper(children),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _child$children;
      var child = _step.value;
      var self = getNumberValue(child);
      if (typeof self === 'number' && !Number.isNaN(self)) {
        sum += self;
      }
      if ((_child$children = child.children) !== null && _child$children !== void 0 && _child$children.length) {
        sum += aggregateSum(child, getNumberValue);
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return sum;
}
export var Row = /*#__PURE__*/React.memo(function (props) {
  var _cfg$indent, _cfg$showDotSeparator, _ref, _cfg$infoIconStyle$wi, _ref2, _cfg$infoIconStyle$he, _cfg$divider, _cfg$divider$style, _cfg$divider$color, _ref3, _cfg$expandIconStyle$, _ref4, _cfg$expandIconStyle$2, _cfg$expandIconStyle, _cfg$expandIconStyle2;
  var prefixCls = props.prefixCls,
    item = props.item,
    level = props.level,
    index = props.index,
    parentPathKeys = props.parentPathKeys,
    expandedKeySet = props.expandedKeySet,
    toggleExpanded = props.toggleExpanded,
    getKey = props.getKey,
    levelConfig = props.levelConfig,
    indent = props.indent,
    rowGap = props.rowGap,
    gaps = props.gaps,
    maxRenderLevel = props.maxRenderLevel,
    maxExpandLevel = props.maxExpandLevel,
    aggregate = props.aggregate,
    renderLabel = props.renderLabel,
    renderValue = props.renderValue,
    _props$parentHasItems = props.parentHasItemsCount,
    parentHasItemsCount = _props$parentHasItems === void 0 ? false : _props$parentHasItems;
  var key = useMemo(function () {
    var _item$key;
    return (_item$key = item.key) !== null && _item$key !== void 0 ? _item$key : getKey(item, {
      level: level,
      index: index,
      parentPathKeys: parentPathKeys
    });
  }, [getKey, index, item, level, parentPathKeys]);
  var pathKeys = useMemo(function () {
    return [].concat(_toConsumableArray(parentPathKeys), [key]);
  }, [parentPathKeys, key]);
  var children = useMemo(function () {
    return normalizeChildren(item.children);
  }, [item.children]);
  var hasExpandedContent = item.expandedContent != null;
  var canRenderChildren = maxRenderLevel ? level < maxRenderLevel : true;
  var hasChildren = canRenderChildren && children.length > 0 || hasExpandedContent;
  var canExpand = hasChildren && (maxExpandLevel ? level < maxExpandLevel : true);
  var expanded = canExpand && expandedKeySet.has(key);
  var cfg = getLevelCfg(levelConfig, level);
  var nextIndent = (_cfg$indent = cfg === null || cfg === void 0 ? void 0 : cfg.indent) !== null && _cfg$indent !== void 0 ? _cfg$indent : indent;
  var rowStyleMerged = _objectSpread(_objectSpread({}, cfg === null || cfg === void 0 ? void 0 : cfg.rowStyle), item.rowStyle);
  if (level === 1) {
    rowStyleMerged.paddingTop = 20;
    rowStyleMerged.paddingBottom = 20;
  }
  if (level === 2) {
    rowStyleMerged.paddingTop = 20;
    rowStyleMerged.paddingBottom = expanded ? 16 : 20;
  }
  var aggregatedValue = useMemo(function () {
    var _aggregate$mode, _aggregate$mode2, _aggregate$getNumberV;
    if (item.value !== undefined) return undefined;
    if (!aggregate || ((_aggregate$mode = aggregate.mode) !== null && _aggregate$mode !== void 0 ? _aggregate$mode : 'none') === 'none') return undefined;
    if (((_aggregate$mode2 = aggregate.mode) !== null && _aggregate$mode2 !== void 0 ? _aggregate$mode2 : 'none') !== 'sum') return undefined;
    var sum = aggregateSum(item, (_aggregate$getNumberV = aggregate.getNumberValue) !== null && _aggregate$getNumberV !== void 0 ? _aggregate$getNumberV : defaultGetNumberValue);
    return aggregate.format ? aggregate.format(sum, {
      item: item,
      level: level
    }) : sum;
  }, [aggregate, item, level]);
  var ctx = useMemo(function () {
    return {
      level: level,
      pathKeys: pathKeys,
      expanded: expanded,
      hasChildren: hasChildren,
      aggregatedValue: aggregatedValue
    };
  }, [aggregatedValue, expanded, hasChildren, level, pathKeys]);
  var siblingKeys = useMemo(function () {
    return hasExpandedContent ? [] : children.map(function (c, i) {
      var _c$key;
      return (_c$key = c.key) !== null && _c$key !== void 0 ? _c$key : getKey(c, {
        level: level + 1,
        index: i,
        parentPathKeys: pathKeys
      });
    });
  }, [children, getKey, hasExpandedContent, level, pathKeys]);
  var onToggle = useCallback(function () {
    if (!canExpand) return;
    toggleExpanded(key, {
      siblingKeys: siblingKeys
    });
  }, [canExpand, key, siblingKeys, toggleExpanded]);
  var left = renderLabel ? renderLabel(item, ctx) : item.label;
  var right = renderValue ? renderValue(item, ctx) : aggregatedValue !== null && aggregatedValue !== void 0 ? aggregatedValue : item.value;
  var showDotSeparator = (_cfg$showDotSeparator = cfg === null || cfg === void 0 ? void 0 : cfg.showDotSeparator) !== null && _cfg$showDotSeparator !== void 0 ? _cfg$showDotSeparator : true;
  var showItemsCount = item.itemsCount !== undefined && item.itemsCount !== null;
  var showInfo = item.infoTooltip !== undefined && item.infoTooltip !== null;
  var metaStyle = cfg === null || cfg === void 0 ? void 0 : cfg.metaTextStyle;
  var infoIconStyleObj = (cfg === null || cfg === void 0 ? void 0 : cfg.infoIconStyle) != null ? {
    fontSize: cfg.infoIconStyle.size,
    color: cfg.infoIconStyle.color,
    width: (_ref = (_cfg$infoIconStyle$wi = cfg.infoIconStyle.width) !== null && _cfg$infoIconStyle$wi !== void 0 ? _cfg$infoIconStyle$wi : cfg.infoIconStyle.size) !== null && _ref !== void 0 ? _ref : 16,
    height: (_ref2 = (_cfg$infoIconStyle$he = cfg.infoIconStyle.height) !== null && _cfg$infoIconStyle$he !== void 0 ? _cfg$infoIconStyle$he : cfg.infoIconStyle.size) !== null && _ref2 !== void 0 ? _ref2 : 16,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center'
  } : showInfo ? {
    fontSize: 16,
    width: 16,
    height: 16,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center'
  } : undefined;
  var leftMeta = (showItemsCount || showInfo) && /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-meta"),
    style: _objectSpread(_objectSpread({}, metaStyle), (gaps === null || gaps === void 0 ? void 0 : gaps.meta) !== undefined ? {
      gap: gaps.meta
    } : undefined)
  }, showItemsCount ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-items-count"),
    style: metaStyle
  }, item.itemsCount) : null, showInfo ? /*#__PURE__*/React.createElement(Tooltip, {
    title: item.infoTooltip
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-info"),
    "aria-label": "info",
    style: infoIconStyleObj
  }, /*#__PURE__*/React.createElement(QuestionCircleOutlined, null))) : null);
  var isTitleRow = level <= 2;
  var nodeStyle = _objectSpread(_objectSpread(_objectSpread({}, isTitleRow ? expanded ? {
    paddingBottom: 20
  } : {} : {
    marginTop: rowGap
  }), level === 2 ? {
    paddingLeft: 20,
    paddingRight: 20
  } : {}), level === 2 && cfg !== null && cfg !== void 0 && (_cfg$divider = cfg.divider) !== null && _cfg$divider !== void 0 && _cfg$divider.show ? {
    borderTop: "1px ".concat((_cfg$divider$style = cfg.divider.style) !== null && _cfg$divider$style !== void 0 ? _cfg$divider$style : 'solid', " ").concat((_cfg$divider$color = cfg.divider.color) !== null && _cfg$divider$color !== void 0 ? _cfg$divider$color : '#D0D5DD')
  } : {});

  /** 仅分组节点：label 为空、无 value、有 children 时只渲染子节点，不渲染当前行；子节点沿用当前 level（与父同级样式） */
  var isGroupOnly = hasChildren && (item.label === '' || item.label === null || item.label === undefined) && item.value === undefined;
  if (isGroupOnly) {
    return /*#__PURE__*/React.createElement(React.Fragment, null, children.map(function (child, childIndex) {
      var _child$key;
      return /*#__PURE__*/React.createElement(Row, _extends({
        key: (_child$key = child.key) !== null && _child$key !== void 0 ? _child$key : getKey(child, {
          level: level,
          index: childIndex,
          parentPathKeys: pathKeys
        })
      }, props, {
        item: child,
        level: level,
        index: childIndex,
        parentPathKeys: pathKeys
      }));
    }));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-node"),
    style: nodeStyle
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(prefixCls, "-row"), cfg === null || cfg === void 0 ? void 0 : cfg.rowClassName, item.rowClassName, _defineProperty(_defineProperty({}, "".concat(prefixCls, "-row-expandable"), canExpand), "".concat(prefixCls, "-row-expanded"), expanded)),
    style: _objectSpread(_objectSpread({}, rowStyleMerged), (gaps === null || gaps === void 0 ? void 0 : gaps.row) !== undefined ? {
      gap: gaps.row
    } : undefined),
    onClick: onToggle,
    role: canExpand ? 'button' : undefined,
    tabIndex: canExpand ? 0 : undefined,
    onKeyDown: function onKeyDown(e) {
      if (!canExpand) return;
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        onToggle();
      }
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-row-left"),
    style: (gaps === null || gaps === void 0 ? void 0 : gaps.rowLeft) !== undefined ? {
      gap: gaps.rowLeft
    } : undefined
  }, parentHasItemsCount && !showItemsCount ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-bullet"),
    style: {
      color: '#667085',
      flexShrink: 0
    },
    "aria-hidden": true
  }, "\u2022") : null, /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-label"),
    style: parentHasItemsCount ? _objectSpread(_objectSpread({}, cfg === null || cfg === void 0 ? void 0 : cfg.labelTextStyle), {}, {
      color: '#667085',
      fontWeight: 400
    }) : cfg === null || cfg === void 0 ? void 0 : cfg.labelTextStyle,
    title: typeof item.label === 'string' ? item.label : undefined
  }, left), leftMeta, /*#__PURE__*/React.createElement("span", {
    style: {
      flex: 1,
      minWidth: 0
    },
    "aria-hidden": true
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-row-right"),
    style: (gaps === null || gaps === void 0 ? void 0 : gaps.rowRight) !== undefined ? {
      gap: gaps.rowRight
    } : undefined
  }, /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-value"),
    style: parentHasItemsCount ? _objectSpread(_objectSpread({}, cfg === null || cfg === void 0 ? void 0 : cfg.valueTextStyle), {}, {
      color: '#667085',
      fontWeight: 400
    }) : cfg === null || cfg === void 0 ? void 0 : cfg.valueTextStyle
  }, right), item.extra ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-extra")
  }, item.extra) : null, canExpand ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-row-expand-icon"),
    "aria-label": expanded ? 'collapse' : 'expand',
    style: cfg !== null && cfg !== void 0 && cfg.expandIconStyle ? {
      width: (_ref3 = (_cfg$expandIconStyle$ = cfg.expandIconStyle.width) !== null && _cfg$expandIconStyle$ !== void 0 ? _cfg$expandIconStyle$ : cfg.expandIconStyle.size) !== null && _ref3 !== void 0 ? _ref3 : 24,
      height: (_ref4 = (_cfg$expandIconStyle$2 = cfg.expandIconStyle.height) !== null && _cfg$expandIconStyle$2 !== void 0 ? _cfg$expandIconStyle$2 : cfg.expandIconStyle.size) !== null && _ref4 !== void 0 ? _ref4 : 24
    } : undefined
  }, /*#__PURE__*/React.createElement(UpOutlined, {
    style: _objectSpread(_objectSpread({
      transform: expanded ? 'rotate(0deg)' : 'rotate(180deg)'
    }, cfg !== null && cfg !== void 0 && (_cfg$expandIconStyle = cfg.expandIconStyle) !== null && _cfg$expandIconStyle !== void 0 && _cfg$expandIconStyle.color ? {
      color: cfg.expandIconStyle.color
    } : null), cfg !== null && cfg !== void 0 && (_cfg$expandIconStyle2 = cfg.expandIconStyle) !== null && _cfg$expandIconStyle2 !== void 0 && _cfg$expandIconStyle2.size ? {
      fontSize: cfg.expandIconStyle.size
    } : null)
  })) : null)), hasChildren && expanded ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-children"),
    style: {
      paddingLeft: 0,
      marginTop: 8
    }
  }, hasExpandedContent ? item.expandedContent : children.map(function (child, childIndex) {
    var _child$key2;
    return /*#__PURE__*/React.createElement(Row, _extends({
      key: (_child$key2 = child.key) !== null && _child$key2 !== void 0 ? _child$key2 : getKey(child, {
        level: level + 1,
        index: childIndex,
        parentPathKeys: pathKeys
      })
    }, props, {
      item: child,
      level: level + 1,
      index: childIndex,
      parentPathKeys: pathKeys,
      parentHasItemsCount: showItemsCount || parentHasItemsCount
    }));
  })) : null);
});
Row.displayName = 'PisellHierarchicalSummaryListRow';