package com.zbkj.common.vo;

import cn.hutool.core.collection.CollUtil;
import com.zbkj.common.response.BcxProductMenuResponse;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商城商品菜单树
 */
public class BcxProductMenuTree {

    private List<BcxProductMenuResponse> menuList = new ArrayList<BcxProductMenuResponse>();

    public BcxProductMenuTree(List<BcxProductMenuResponse> menuList) {
        this.menuList = menuList;
    }

    //建立树形结构
    public List<BcxProductMenuResponse> buildTree() {
        List<BcxProductMenuResponse> treeMenus = new ArrayList<BcxProductMenuResponse>();
        for (BcxProductMenuResponse menuNode : getRootNode()) {
            menuNode = buildChildTree(menuNode);
            treeMenus.add(menuNode);
        }
        return sortList(treeMenus);
    }

    // 正序排序 0-9
    private List<BcxProductMenuResponse> sortList(List<BcxProductMenuResponse> treeMenus) {
        treeMenus = treeMenus.stream().sorted(Comparator.comparing(BcxProductMenuResponse::getSort)).collect(Collectors.toList());
        treeMenus.forEach(e -> {
            if (CollUtil.isNotEmpty(e.getChildList())) {
                e.setChildList(sortList(e.getChildList()));
            }
        });
        return treeMenus;
    }

    //递归，建立子树形结构
    private BcxProductMenuResponse buildChildTree(BcxProductMenuResponse pNode) {
        List<BcxProductMenuResponse> childMenus = new ArrayList<BcxProductMenuResponse>();
        for (BcxProductMenuResponse menuNode : menuList) {
            if (menuNode.getPid().equals(pNode.getId())) {
                childMenus.add(buildChildTree(menuNode));
            }
        }
        pNode.setChildList(childMenus);
        return pNode;
    }

    //获取根节点
    private List<BcxProductMenuResponse> getRootNode() {
        List<BcxProductMenuResponse> rootMenuLists = new ArrayList<BcxProductMenuResponse>();
        for (BcxProductMenuResponse menuNode : menuList) {
            if (menuNode.getPid().equals(0)) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

}
