package com.lightinit.hsdatashow.service.admin;

import com.lightinit.hsdatashow.model.admin.TreeModel;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

/**
 * @author WangYao
 * @date 2018/6/2 17:40
 * @description 树模型数据组装器
 */
public class TreeDataBuilder {

    /**
     * @param treeModelList 顶层树节点模型列表
     * @param dataList 泛型数据列表
     * @param dataFunction 泛型方法，用于将数据转换为树节点模型
     * @param afterFunction 泛型方法，用于处理在给当前树模型添加子模型集合后的事件
     * @param <T> 泛型数据类型
     */
    public static <T> void buildTreeModelRecursively(List<TreeModel> treeModelList, final List<T> dataList, BiFunction<TreeModel, List<T>, List<TreeModel>> dataFunction, BiConsumer<TreeModel,List<TreeModel>> afterFunction){
        if (treeModelList == null || treeModelList.size() == 0 || dataList == null || dataList.size() == 0){
            return ;
        }
        for (TreeModel currentTreeModel : treeModelList){
            List<TreeModel> childTreeModelList = dataFunction.apply(currentTreeModel, dataList);
            if (currentTreeModel.getNodes() == null){
                currentTreeModel.setNodes(childTreeModelList);
            }else {
                currentTreeModel.getNodes().addAll(childTreeModelList);
            }

            /*if (childTreeModelList.stream().anyMatch(q -> q.getState() != null && (q.getState().getSelected() || q.getState().getExpanded()))){
                currentTreeModel.setState(currentTreeModel.new State(false, false, true, false));
            }*/
            /*List<String> tags = new ArrayList<>();
            tags.add(String.valueOf(childTreeModelList.size()));
            currentTreeModel.setTags(tags);*/
            if(afterFunction != null){
                afterFunction.accept(currentTreeModel, childTreeModelList);
            }
            buildTreeModelRecursively(childTreeModelList, dataList, dataFunction, afterFunction);
        }
    }

    /**
     * @param treeModelList 顶层树节点模型列表
     * @param dataList 泛型数据列表
     * @param dataFunction 泛型方法，用于将数据转换为树节点模型
     * @param <T> 泛型数据类型
     */
    public static <T> void buildTreeModelRecursively(List<TreeModel> treeModelList, final List<T> dataList, BiFunction<TreeModel, List<T>, List<TreeModel>> dataFunction){
        buildTreeModelRecursively(treeModelList, dataList, dataFunction, null);
    }
}
