package com.mx.cneeds.common.generate;

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

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

public class CascaderToolUtils {
    /**
     * 根节点对象存放到这里
     */
    private List<CascaderVo> rootList;
    /**
     * 其他节点存放到这里，可以包含根节点
     */
    private List<CascaderVo> bodyList;

    public CascaderToolUtils(List<CascaderVo> rootList, List<CascaderVo> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }
 
    public List<CascaderVo> 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(CascaderVo treeDto,Map<Long,Long> map){
        List<CascaderVo> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getValue()))
                .filter(c ->c.getPid().equals(treeDto.getValue()))
                .forEach(c ->{
                    map.put(c.getValue(),c.getPid());
                    getChild(c,map);
                    childList.add(c);
                });
        treeDto.setChildren(childList);
 
    }
}