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 _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 _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; }
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; }
/**
 * HUD 抽屉右侧竖栏：与 Filter「Resource」同源，写入 `filter.values.form_record_ids`。
 * 资源列表来自 GET /shop/form/resource/page。
 *
 * 优先按列表内 `parent_id` 推断树的第一层节点；若父链缺失会导致「每条记录都是根」、按钮爆炸，
 * 则回退为按 `form_id`（资源所属表单）聚合——对应 Filter 里顶层资源类型/主类，而非单个 form_record。
 */

/** 推断出的树根超过该数量时，视为树链不可靠，改用 form 维度聚合 */
var HUD_RAIL_TREE_ROOT_CAP = 20;
function normalizeRecordId(raw) {
  if (typeof raw === 'number' && Number.isFinite(raw)) {
    var n = Math.trunc(raw);
    if (n > 0) return String(n);
    return null;
  }
  if (typeof raw === 'string') {
    var t = raw.trim();
    if (!t || t === '0') return null;
    var _n = Number(t);
    if (Number.isFinite(_n) && _n > 0) return String(Math.trunc(_n));
    if (/^\d+$/.test(t)) return t;
  }
  return null;
}
function normalizeMainFieldFirstLine(raw) {
  var _first$trim;
  if (raw == null || typeof raw !== 'string') return '';
  var first = raw.split(' ## ')[0];
  return (_first$trim = first === null || first === void 0 ? void 0 : first.trim()) !== null && _first$trim !== void 0 ? _first$trim : '';
}
function getParentRecordId(item) {
  var _item$parent_id;
  var p = (_item$parent_id = item.parent_id) !== null && _item$parent_id !== void 0 ? _item$parent_id : item.parentId;
  if (p == null || p === '') return null;
  if (typeof p === 'number' && Number.isFinite(p)) {
    var n = Math.trunc(p);
    return n > 0 ? String(n) : null;
  }
  return normalizeRecordId(p);
}
function normalizeFormId(row) {
  var _row$form_id;
  var f = (_row$form_id = row.form_id) !== null && _row$form_id !== void 0 ? _row$form_id : row.formId;
  if (typeof f === 'number' && Number.isFinite(f)) {
    var n = Math.trunc(f);
    return n > 0 ? String(n) : null;
  }
  if (typeof f === 'string') {
    var t = f.trim();
    if (!t || t === '0') return null;
    var _n2 = Number(t);
    if (Number.isFinite(_n2) && _n2 > 0) return String(Math.trunc(_n2));
    if (/^\d+$/.test(t)) return t;
  }
  return null;
}
function pickFormAggregateLabel(rows) {
  var codes = new Set();
  var _iterator = _createForOfIteratorHelper(rows),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var r = _step.value;
      var c = typeof r.form_code === 'string' ? r.form_code.trim() : '';
      if (c) codes.add(c);
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  if (codes.size >= 1) {
    var _sort$;
    return (_sort$ = _toConsumableArray(codes).sort(function (a, b) {
      return a.localeCompare(b);
    })[0]) !== null && _sort$ !== void 0 ? _sort$ : 'Resource';
  }
  var shortest = '';
  var _iterator2 = _createForOfIteratorHelper(rows),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var _r = _step2.value;
      var m = normalizeMainFieldFirstLine(_r.main_field);
      if (!m) continue;
      if (!shortest || m.length < shortest.length) shortest = m;
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return shortest || 'Other';
}

/** 按 form_id 分桶：每桶含该表单下全部资源 id（多选任一主类等同筛该表单下全部具体资源） */
function buildFormAggregateBuckets(rows) {
  var groups = new Map();
  var _iterator3 = _createForOfIteratorHelper(rows),
    _step3;
  try {
    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      var row = _step3.value;
      var id = normalizeRecordId(row.id);
      if (!id) continue;
      var fk = normalizeFormId(row);
      var gk = fk !== null && fk !== void 0 ? fk : '__nof__';
      if (!groups.has(gk)) groups.set(gk, []);
      groups.get(gk).push(row);
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }
  var entries = _toConsumableArray(groups.entries()).map(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      formKey = _ref2[0],
      groupRows = _ref2[1];
    var minSort = Infinity;
    var _iterator4 = _createForOfIteratorHelper(groupRows),
      _step4;
    try {
      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
        var r = _step4.value;
        var s = typeof r.sort === 'number' && Number.isFinite(r.sort) ? r.sort : Infinity;
        if (s < minSort) minSort = s;
      }
    } catch (err) {
      _iterator4.e(err);
    } finally {
      _iterator4.f();
    }
    if (!Number.isFinite(minSort)) minSort = 0;
    var label = pickFormAggregateLabel(groupRows);
    var keySet = new Set();
    var _iterator5 = _createForOfIteratorHelper(groupRows),
      _step5;
    try {
      for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
        var _r2 = _step5.value;
        var rid = normalizeRecordId(_r2.id);
        if (rid) keySet.add(rid);
      }
    } catch (err) {
      _iterator5.e(err);
    } finally {
      _iterator5.f();
    }
    var bucket = {
      id: "resourceForm:".concat(formKey),
      label: label,
      keys: _toConsumableArray(keySet)
    };
    return {
      sortKey: minSort,
      bucket: bucket
    };
  });
  entries.sort(function (a, b) {
    return a.sortKey - b.sortKey;
  });
  return entries.map(function (e) {
    return e.bucket;
  });
}

/** 与抽屉 / Filter 共用的 `searchParams.filter.values.form_record_ids` 读取 */
export function extractFilterFormRecordIds(searchParams) {
  var filter = searchParams.filter;
  var values = _typeof(filter === null || filter === void 0 ? void 0 : filter.values) === 'object' && (filter === null || filter === void 0 ? void 0 : filter.values) !== null && !Array.isArray(filter.values) ? filter.values : undefined;
  var raw = values === null || values === void 0 ? void 0 : values.form_record_ids;
  if (!Array.isArray(raw)) return [];
  return raw.map(String).filter(Boolean);
}
function buildTreeResourceRootBuckets(rows) {
  var idSet = new Set();
  var _iterator6 = _createForOfIteratorHelper(rows),
    _step6;
  try {
    for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
      var _row = _step6.value;
      var _id = normalizeRecordId(_row.id);
      if (_id) idSet.add(_id);
    }
  } catch (err) {
    _iterator6.e(err);
  } finally {
    _iterator6.f();
  }
  var childrenByParent = new Map();
  var _iterator7 = _createForOfIteratorHelper(rows),
    _step7;
  try {
    for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
      var _row2 = _step7.value;
      var _id2 = normalizeRecordId(_row2.id);
      if (!_id2) continue;
      var pid = getParentRecordId(_row2);
      if (!pid || !idSet.has(pid)) continue;
      if (!childrenByParent.has(pid)) childrenByParent.set(pid, []);
      childrenByParent.get(pid).push(_id2);
    }
  } catch (err) {
    _iterator7.e(err);
  } finally {
    _iterator7.f();
  }
  var roots = [];
  var seen = new Set();
  var _iterator8 = _createForOfIteratorHelper(rows),
    _step8;
  try {
    for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
      var _row3 = _step8.value;
      var _id3 = normalizeRecordId(_row3.id);
      if (!_id3 || seen.has(_id3)) continue;
      var _pid = getParentRecordId(_row3);
      if (!_pid || !idSet.has(_pid)) {
        roots.push(_row3);
        seen.add(_id3);
      }
    }
  } catch (err) {
    _iterator8.e(err);
  } finally {
    _iterator8.f();
  }
  roots.sort(function (a, b) {
    var sa = typeof a.sort === 'number' && Number.isFinite(a.sort) ? a.sort : 0;
    var sb = typeof b.sort === 'number' && Number.isFinite(b.sort) ? b.sort : 0;
    return sa - sb;
  });
  function collectSubtreeIds(rootId) {
    var out = [];
    var stack = [rootId];
    while (stack.length) {
      var cur = stack.pop();
      out.push(cur);
      var kids = childrenByParent.get(cur);
      if (!(kids !== null && kids !== void 0 && kids.length)) continue;
      var _iterator9 = _createForOfIteratorHelper(kids),
        _step9;
      try {
        for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
          var k = _step9.value;
          stack.push(k);
        }
      } catch (err) {
        _iterator9.e(err);
      } finally {
        _iterator9.f();
      }
    }
    return out;
  }
  var buckets = [];
  for (var _i = 0, _roots = roots; _i < _roots.length; _i++) {
    var row = _roots[_i];
    var id = normalizeRecordId(row.id);
    if (!id) continue;
    var main = normalizeMainFieldFirstLine(row.main_field);
    var code = typeof row.form_code === 'string' && row.form_code.trim() !== '' ? String(row.form_code).trim() : '';
    var label = (main || code || id).trim();
    var keys = collectSubtreeIds(id);
    buckets.push({
      id: "resourceRoot:".concat(id),
      label: label,
      keys: keys
    });
  }
  return buckets;
}

/**
 * 从 form/resource/page 扁平 list 构建第一层桶。
 * - 列表内父子链完整时：与 TreeSelect 第一层语义一致（根及其子树 id）；
 * - 父链缺失导致伪根过多时：按 `form_id` 聚合为「主类」桶，避免竖栏铺满具体资源名。
 */
export function buildResourceRootBuckets(rawList) {
  if (!Array.isArray(rawList) || rawList.length === 0) return [];
  var rows = rawList.filter(function (x) {
    return x != null && _typeof(x) === 'object' && !Array.isArray(x);
  });
  var treeBuckets = buildTreeResourceRootBuckets(rows);
  if (treeBuckets.length <= HUD_RAIL_TREE_ROOT_CAP) {
    return treeBuckets;
  }
  return buildFormAggregateBuckets(rows);
}