package com.engine.organization.util.tree;

import com.api.hrm.bean.TreeNode;
import com.engine.organization.entity.searchtree.SearchTree;
import org.apache.commons.collections4.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:dxfeng
 * @createTime: 2022/06/06
 * @version: 1.0
 */
public class SearchTreeUtil {
    /**
     * 左侧树 类型表示
     * <p>
     * 0：集团
     * 1：分部
     * 2：部门
     */
    private static final String TYPE_GROUP = "0";

    public static Map<String, Object> getSearchTree(String type, List<SearchTree> treeList) {
        Map<String, Object> dataMap = new HashMap<>();
        SearchTree topGroup = getTopGroup();
        // 集团
        List<SearchTree> companyList = new ArrayList<>();
        companyList.add(topGroup);

        List<TreeNode> treeDatas = new ArrayList<>();
        // 排序，设置是否为叶子节点
        List<TreeNode> collect = treeList.stream().peek(item ->
                item.setIsParent(CollectionUtils.isNotEmpty(item.getSubs()))
        ).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            treeDatas.addAll(collect);
        }

        // 未点击，初始化树结构
        if (StringUtil.isEmpty(type)) {
            dataMap.put("companys", companyList);
            SearchTree rootCompany = getTopGroup();
            rootCompany.setSubs(treeDatas);
            rootCompany.setIsParent(CollectionUtils.isNotEmpty(rootCompany.getSubs()));
            Map<String, Object> rootCompanyMap = new HashMap<>();
            rootCompanyMap.put("rootCompany", rootCompany);
            dataMap.put("datas", rootCompanyMap);
        } else {
            // 根据ID查询
            dataMap.put("datas", treeDatas);
        }
        return dataMap;
    }

    /**
     * 获取集团
     *
     * @return
     */
    public static SearchTree getTopGroup() {
        RecordSet rs = new RecordSet();
        String sql = "select * from HrmCompany ";
        rs.executeQuery(sql);
        SearchTree groupTree = new SearchTree();
        groupTree.setCanClick(false);
        groupTree.setCanceled(false);
        groupTree.setCompanyid("1");
        groupTree.setIcon("icon-coms-LargeArea");
        groupTree.setId("0");
        groupTree.setIsVirtual("0");
        while (rs.next()) {
            groupTree.setName(rs.getString("COMPANYNAME"));
        }
        groupTree.setSelected(false);
        groupTree.setType(TYPE_GROUP);
        return groupTree;
    }

    /**
     * 处理树层级
     *
     * @param treeList
     * @return
     */
    public static List<SearchTree> builderTreeMode(List<SearchTree> treeList) {
        Map<String, List<SearchTree>> collects = treeList.stream().collect(Collectors.groupingBy(TreeNode::getPid));
        Set<String> leafIds = new HashSet<>();
        List<SearchTree> collect = treeList.stream().peek(e -> {
            if (null != collects && CollectionUtils.isNotEmpty(collects.get(e.getId()))) {
                List<TreeNode> nodes = collects.get(e.getId()).stream().sorted(Comparator.comparing(item -> null == item.getOrderNum() ? 0 : item.getOrderNum())).collect(Collectors.toList());
                e.setSubs(nodes);
                leafIds.add(e.getId());
                if (CollectionUtils.isNotEmpty(e.getSubs())) {
                    e.setIsParent(true);
                }
            }
        }).collect(Collectors.toList());
        return collect.stream().filter(item -> !leafIds.contains(item.getPid())).collect(Collectors.toList());
    }

    /**
     * 组合分部、部门层级关系
     *
     * @param treeList
     * @param deptTrees
     * @return
     */
    public static List<SearchTree> builderTreeMode(List<SearchTree> treeList, List<SearchTree> deptTrees) {
        Map<String, List<TreeNode>> parentMap = treeList.stream().collect(Collectors.groupingBy(TreeNode::getPid));
        Map<String, List<SearchTree>> childMap = deptTrees.stream().collect(Collectors.groupingBy(SearchTree::getParentComp));
        boolean isAdd = !childMap.isEmpty();
        Set<String> leafIds = new HashSet<>();
        List<SearchTree> collect = treeList.stream().peek(e -> {
            Set<TreeNode> treeNodes = new LinkedHashSet<>();
            List<TreeNode> nodes = parentMap.get(e.getId());
            if (CollectionUtils.isNotEmpty(nodes)) {
                treeNodes.addAll(nodes);
            }
            if (isAdd && CollectionUtils.isNotEmpty(childMap.get(e.getId()))) {
                List<SearchTree> searchTrees = childMap.get(e.getId()).stream().sorted(Comparator.comparing(SearchTree::getOrderNum)).collect(Collectors.toList());
                treeNodes.addAll(searchTrees);
            }
            if (CollectionUtils.isNotEmpty(e.getSubs())) {
                treeNodes.addAll(e.getSubs());
            }
            e.setSubs(new ArrayList<>(treeNodes));
            leafIds.add(e.getId());
        }).collect(Collectors.toList());
        return collect.stream().peek(item -> {
            if (CollectionUtils.isNotEmpty(item.getSubs())) {
                item.setIsParent(true);
            }
        }).filter(item -> !leafIds.contains(item.getPid())).collect(Collectors.toList());
    }

    /**
     * 判断是为顶层数据
     *
     * @param pid
     * @return
     */
    private static boolean isTop(String pid) {
        return StringUtil.isEmpty(pid) || "0".equals(pid);
    }

    /**
     * 判断是为顶层数据
     *
     * @param pid
     * @return
     */
    public static boolean isTop(Long pid) {
        return null == pid;
    }

    public static boolean isTop(Integer pid) {
        return null == pid;
    }
}
