package com.mx.cneeds.common.generate;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mx.cneeds.common.vo.TreeVo;

import java.util.List;
import java.util.Map;

public class TreeToolUtils {
    /**
     * 根节点对象存放到这里
     */
    private List<TreeVo> rootList;
    /**
     * 其他节点存放到这里，可以包含根节点
     */
    private List<TreeVo> bodyList;
 
    public TreeToolUtils(List<TreeVo> rootList, List<TreeVo> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }
 
    public List<TreeVo> getTree(){   //调用的方法入口
        if(bodyList != null && !bodyList.isEmpty()){
            //声明一个map，用来过滤已操作过的数据
            Map<Long,Long> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree,map));
            return rootList;
        }
        return null;
    }
 
    public void getChild(TreeVo treeDto, Map<Long,Long> map){
        List<TreeVo> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getId()))
                .filter(c ->c.getPid().equals(treeDto.getId()))
                .forEach(c ->{
                    map.put(c.getId(),c.getPid());
                    getChild(c,map);
                    childList.add(c);
                });
        treeDto.setChildren(childList);
 
    }
}