/**
 * 生成以"全部"为根目录的树形结构
 * @param {Array} data - 原始数据数组
 * @param {Object} options - 配置选项
 * @returns {Array} 树形结构数据
 */
export function generateTreeWithRoot(data = [], options = {}) {
  const {
    rootLabel = '全部',
    rootId = 'root',
    idKey = 'id',
    nameKey = 'name',
    childrenKey = 'children'
  } = options

  // 创建根节点
  const rootNode = {
    [idKey]: rootId,
    [nameKey]: rootLabel,
    [childrenKey]: data.map(item => ({
      ...item,
      [childrenKey]: item[childrenKey] || []
    }))
  }

  return [rootNode]
}

/**
 * 从扁平数据生成树形结构（以"全部"为根）
 * @param {Array} flatData - 扁平数据
 * @param {Object} options - 配置选项
 * @returns {Array} 树形结构
 */
export function generateTreeFromFlat(flatData = [], options = {}) {
  const {
    rootLabel = '全部',
    rootId = 'root',
    idKey = 'id',
    parentIdKey = 'parentId',
    nameKey = 'name',
    childrenKey = 'children'
  } = options

  // 构建树形结构
  const tree = []
  const map = {}

  // 创建映射
  flatData.forEach(item => {
    map[item[idKey]] = { ...item, [childrenKey]: [] }
  })

  // 构建父子关系
  flatData.forEach(item => {
    if (item[parentIdKey] && map[item[parentIdKey]]) {
      map[item[parentIdKey]][childrenKey].push(map[item[idKey]])
    } else {
      tree.push(map[item[idKey]])
    }
  })

  // 创建根节点
  return [{
    [idKey]: rootId,
    [nameKey]: rootLabel,
    [childrenKey]: tree
  }]
}