package cn.com.ty.lift.common.utils;

import cn.com.ty.lift.common.model.BaseTree;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author huangyuan
 * @date 2019-12-02
 * @description 树工具类
 */
public class TreeUtil {
    /**
     * 将包含所有对象的集合转化为树结构
     *
     * @param treeList
     * @param parentAttr
     * @param rootParentId
     * @return List<? extends BaseTree>
     * @throws
     * @author huangy
     */
    public static <T> List listToTree(List treeList, String parentAttr, T rootParentId, String attrName) {
        BaseTree rootBaseTree = new BaseTree();
        Map parentIdToChild = ProjectUtils.attrToListMap(treeList, parentAttr, null);
        getChildren(rootBaseTree, parentIdToChild, rootParentId, attrName);
        return rootBaseTree.getChildren();
    }

    /**
     * 递归设置子集合
     *
     * @param baseTree
     * @param parentIdToChild
     * @param rootParentId    根节点父id
     * @throws
     * @author huangy
     */
    private static <T> void getChildren(BaseTree baseTree, Map<? extends Object, List<? extends BaseTree>> parentIdToChild,
                                        T rootParentId, String attrName){
        List<? extends BaseTree> children = parentIdToChild.get(rootParentId);
        if (children != null && children.size() > 0) {
            for (BaseTree baseTreeInfo : children) {
                //info:递归设置子集合
                getChildren(baseTreeInfo, parentIdToChild, getAttrValue(baseTreeInfo, attrName), attrName);
            }
        }
        //info:设置子集合
        baseTree.setChildren(children);
    }

    public static Object getAttrValue(Object t,String attrName){
        try{
            Class<?> classObj = t.getClass();
            String attrGetMethod = PojoUtils.attrGetMethodName(attrName);
            Method method = classObj.getMethod(attrGetMethod, null);
            return method.invoke(t, null);
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
