package cn.palmte.work.pojo;


import cn.palmte.work.model.SysPermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class PermissionTree {



    private static final Logger logger = LoggerFactory.getLogger(PermissionTree.class);

    private static final int LEAF_NODE = 2;



    public static PermissionNode parsePermsNodeTree(List<SysPermission> permList, List<Integer> selectedPermIdList){
        PermissionNode root = new PermissionNode();
        for(int i = 0; i < permList.size(); i++){
            SysPermission perms = permList.get(i);
            PermissionNode subNode = getPermNode(perms);
            if(selectedPermIdList.contains(subNode.getId())){
                //设置该节点已被选择
                subNode.setSelected(true);
            }
            // 如果父id为0，则该节点为主节点
            if(subNode.getParentId() == 0){
                root = subNode;
            } else{
                PermissionNode node = findParentNode(root, subNode.getParentId());
                if(node != null){
                    node.addSubNode(subNode);
                }
            }
        }
        return root;
    }

    private static PermissionNode getPermNode(SysPermission perms){
        PermissionNode subNode = new PermissionNode();
        subNode.setId(perms.getId());
        subNode.setName(perms.getName());
        subNode.setParentId(perms.getParentId());
        subNode.setLevel(perms.getLevel());
        Integer type = perms.getType();

        if(LEAF_NODE == type){
            //设置为叶子节点
            subNode.setLeafNode(true);
        } else{
            subNode.setLeafNode(false);
        }
        return subNode;
    }

    private static PermissionNode findParentNode(PermissionNode node, int nodeId){
        if(node == null){
            return null;
        }
        if(node.getId() == nodeId){
            return node;
        }
        if(node.getSubNodes() == null){
            return null;
        }
        for(PermissionNode subNode : node.getSubNodes()){
            PermissionNode parentNode = findParentNode(subNode, nodeId);
            if(parentNode != null){
                return parentNode;
            }
        }
        return null;
    }




}
