import { PermissionView, PermissionViewTree, PermissionTreeKey } from "@/types/permission/type";

export function transformToViewTree<T>(rawTree: Array<T>, labelKey='label', valueKey='value', childrenKey='children'): PermissionViewTree {
  if (rawTree == null || !Array.isArray(rawTree) ) {
    throw 'Tree data must be an array';
  }

  if (!rawTree.length) {
    return [];
  }

  const viewTree: PermissionViewTree = [];

  for (const item of rawTree) {
    const viewItem: PermissionView = {
      // @ts-ignore
      value: item.nodeType ? `${item.nodeType}-${item[valueKey]}` : item[valueKey],
      label: item[labelKey],
      children: [],
    };

    if (Array.isArray(item[childrenKey]) && item[childrenKey].length) {
      viewItem.children = transformToViewTree(item[childrenKey], labelKey, valueKey, childrenKey);
      viewTree.push(viewItem);
    } else {
      viewTree.push(viewItem);
    }
  }

  return viewTree;
}


function pruneTreeNode(node: PermissionView, values: PermissionTreeKey[]) {
  if (!node) return;

  // 如果是叶子节点
  if (!node.children?.length) {
    // 如果叶子节点 value 在 values中，则保留，否则标记删除
    return values.includes(node.value) ? node : null;
  }

  // 如果不是叶子节点，递归修剪其子节点
  const prunedChildren = node.children.map(child => pruneTreeNode(child, values)).filter(Boolean);
  // 如果修改修剪后的子节点为空，也标记删除
  if (!prunedChildren.length) return null;

  node.children = prunedChildren as PermissionViewTree;
  return node;
}

/**
 * 根据已有的权限分配修剪权限树
 */
export function pruneTree(tree: PermissionViewTree, values: PermissionTreeKey[]) {
  return tree.map(node => pruneTreeNode(node, values)).filter(Boolean) as PermissionViewTree;
}
