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 { parseNestedPathSegments } from '@pisell/materials';
function normalizeSegment(value) {
  if (value == null) return null;
  var t = String(value).trim();
  return t ? t : null;
}

/** 解析单条记录在最多 3 级上的分类 key */
export function resolveCategoryPath(item, config) {
  var _config$levels;
  if (!config) return [null, null, null];
  if (config.getCategoryPath) {
    var raw = config.getCategoryPath(item);
    return [normalizeSegment(raw === null || raw === void 0 ? void 0 : raw[0]), normalizeSegment(raw === null || raw === void 0 ? void 0 : raw[1]), normalizeSegment(raw === null || raw === void 0 ? void 0 : raw[2])];
  }
  if (config.nestedPathField) {
    var nested = parseNestedPathSegments(item[config.nestedPathField], 3);
    return [normalizeSegment(nested[0]), normalizeSegment(nested[1]), normalizeSegment(nested[2])];
  }
  var out = [null, null, null];
  var levels = (_config$levels = config.levels) !== null && _config$levels !== void 0 ? _config$levels : [];
  for (var i = 0; i < 3; i++) {
    var _levels$i;
    var field = (_levels$i = levels[i]) === null || _levels$i === void 0 ? void 0 : _levels$i.field;
    if (field) out[i] = normalizeSegment(item[field]);
  }
  return out;
}

/** 是否匹配当前已选层级路径（前缀匹配） */
export function matchesSelection(item, selection, config) {
  if (!config) return true;
  var path = resolveCategoryPath(item, config);
  for (var i = 0; i < 3; i++) {
    var picked = selection[i];
    if (picked != null && path[i] !== picked) return false;
  }
  return true;
}

/**
 * 根据 records 派生 PisellTabbarTemplate1 的多层级 dataSource。
 * - id 使用「分类 key」（已确保非空字符串）
 * - 顶部不再额外注入「全部」节点；不选层级即视为全部
 */
export function buildTabbarDataSourceFromRecords(items, config) {
  if (!config || items.length === 0) return [];
  var root = [];
  var ensureChild = function ensureChild(list, key, label) {
    var found = list.find(function (n) {
      return n.id === key;
    });
    if (!found) {
      found = {
        id: key,
        name: label,
        children: []
      };
      list.push(found);
    }
    return found;
  };
  var _iterator = _createForOfIteratorHelper(items),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      var path = resolveCategoryPath(item, config);
      var cursor = root;
      for (var i = 0; i < 3; i++) {
        var seg = path[i];
        if (!seg) break;
        var node = ensureChild(cursor, seg, seg);
        if (!node.children) node.children = [];
        cursor = node.children;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  var cleanup = function cleanup(nodes) {
    nodes.forEach(function (n) {
      if (n.children && n.children.length === 0) {
        delete n.children;
      } else if (n.children) {
        cleanup(n.children);
      }
    });
    nodes.sort(function (a, b) {
      return String(a.name).localeCompare(String(b.name), 'zh-CN');
    });
    return nodes;
  };
  return cleanup(root);
}

/** 数据中实际用到的最大嵌套深度，0 表示没有有效分类路径 */
export function getMaxCategoryDepth(items, config) {
  if (!config || items.length === 0) return 0;
  var max = 0;
  var _iterator2 = _createForOfIteratorHelper(items),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var item = _step2.value;
      var path = resolveCategoryPath(item, config);
      for (var i = 2; i >= 0; i--) {
        if (path[i]) {
          if (i + 1 > max) max = i + 1;
          break;
        }
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return max;
}

/** 默认搜索匹配文本：拼接 record 标题 + id */
export function defaultGetSearchText(record) {
  var _record$id;
  var title = typeof record.title === 'string' ? record.title : typeof record.name === 'string' ? record.name : '';
  var idStr = String((_record$id = record.id) !== null && _record$id !== void 0 ? _record$id : '').trim();
  return "".concat(title, " ").concat(idStr).toLowerCase();
}