package com.energy.manage.service.util;

import com.energy.manage.common.constant.Constants;
import com.energy.manage.service.domain.vo.system.PermissionVo;
import com.energy.manage.service.domain.vo.system.SystemPermissionVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.testng.collections.Lists;

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


public class TreeUtil {

  /**
   * 集合转树结构
   *
   * @param dataList
   * @return
   */
  public static List<PermissionVo> convert2Tree(List<PermissionVo> dataList) {
    if (CollectionUtils.isEmpty(dataList)) {
      return Collections.EMPTY_LIST;
    }
    int maxDepth = getMaxDepth(dataList);
    Map<Integer, List<PermissionVo>> dataMap = new HashMap<>(dataList.size());
    for (int i = maxDepth; i >= 1; i--) {
      int depth = i;
      List<PermissionVo> child = dataList.stream().filter(item -> item.getPermissionDepth() == depth).collect(Collectors.toList());
      for (PermissionVo item : child) {
        List<PermissionVo> childList = dataMap.get(item.getPermissionId());
        if (!CollectionUtils.isEmpty(childList)) {
          item.setChildren(childList);
          int isSelect = item.getChecked();
          if (isSelect == 1) {
            // 根据子节点判断本节点是全选还是部分选中，子节点存在未选中或者存在部分选中的时候，当前是部分选中
            childList.stream().forEach(childItem -> {
              if (childItem.getChecked().intValue() == Constants.GLOBAL_NOT_USE || childItem.getChecked().intValue() == 2) {
                item.setChecked(2);
              }
            });
          }
        }
        List<PermissionVo> list = dataMap.get(item.getParentId());
        if (CollectionUtils.isEmpty(list)) {
          list = new ArrayList<>();
        }
        list.add(item);
        dataMap.put(item.getParentId(), list);
      }
    }
    return dataMap.get(0);
  }


  /**
   * 内部方法，获取集合内最深的节点数
   *
   * @param list
   * @return
   */
  private static int getMaxDepth(List<PermissionVo> list) {
    if (CollectionUtils.isEmpty(list)) {
      return 0;
    }
    int maxDepth = 0;
    for (PermissionVo item : list) {
      maxDepth = Math.max(maxDepth, item.getPermissionDepth());
    }
    return maxDepth;
  }


  /**
   * 根据父级节点获取所有的子集节点
   *
   * @param parentNode
   * @param allList
   * @return
   */
  public static List<Map<String, Object>> getJava8Children(Map<String, Object> parentNode, List<Map<String, Object>> allList) {
    return allList.stream()
            .filter(curNode ->curNode.get("parentCode")!=null && curNode.get("parentCode").equals(parentNode.get("codeNumber")))
            .peek(m -> m.put("children", getJava8Children(m, allList))).collect(Collectors.toList());
  }


  /**
   * 获取树形结构
   *
   * @param mapList
   * @return treeList 树形结果集
   */
  public static List<Map<String, Object>> getJava8ResultTree(List<Map<String, Object>> mapList) {
    if (org.springframework.util.CollectionUtils.isEmpty(mapList)) {
      return Lists.newArrayList();
    }
    //filter过滤出所有的一级节点
    return mapList.stream().filter(m ->m.get("parentCode").toString().equals("0"))
            .peek(m -> m.put("children", sortJava8Map(getJava8Children(m, mapList)))).collect(Collectors.toList());
  }

  /**
   * 获取树形结构
   * @param mapList
   * @param parentKeyName 父类key名称
   * @return
   */
  public static List<Map<String, Object>> getJava8ResultTree(List<Map<String,
                                                            Object>> mapList,
                                                            String parentKeyName,
                                                            String keyName) {
    if (org.springframework.util.CollectionUtils.isEmpty(mapList)) {
      return Lists.newArrayList();
    }
    return mapList.stream().filter(m ->m.get(parentKeyName).toString().equals("0"))
            .peek(m -> m.put("children", sortJava8Map(getJava8Children(m, mapList,parentKeyName,keyName)))).collect(Collectors.toList());
  }

  /**
   * 根据父级节点获取所有的子集节点
   *
   * @param parentNode
   * @param allList
   * @return
   */
  public static List<Map<String, Object>> getJava8Children(Map<String, Object> parentNode,
                                                           List<Map<String, Object>> allList,
                                                           String parentKeyName,
                                                           String keyName) {
    return allList.stream()
            .filter(curNode ->curNode.get(parentKeyName)!=null && curNode.get(parentKeyName).toString().equals(parentNode.get(keyName).toString()))
            .peek(m -> m.put("children", getJava8Children(m, allList,parentKeyName,keyName))).collect(Collectors.toList());
  }

  /**
   * 根据orderNo排序树形结构的每一个层级
   *
   * @param list
   * @return
   */
  public static List<Map<String, Object>> sortJava8Map(List<Map<String, Object>> list) {
    if (org.springframework.util.CollectionUtils.isEmpty(list)) {
      return Lists.newArrayList();
    }
    //关键之处，一行代码搞定
    list.sort(Comparator.comparing(m -> String.valueOf(m.get("sort"))));
    return list;
  }

  /**
   * 集合转树结构
   *
   * @param dataList
   * @return
   */
  public static List<SystemPermissionVo> newConvert2Tree(List<SystemPermissionVo> dataList) {
    if (CollectionUtils.isEmpty(dataList)) {
      return Collections.EMPTY_LIST;
    }
    int maxDepth = getNewMaxDepth(dataList);
    Map<Integer, List<SystemPermissionVo>> dataMap = new HashMap<>(dataList.size());
    for (int i = maxDepth; i >= 1; i--) {
      int depth = i;
      List<SystemPermissionVo> child =
              dataList.stream().filter(item -> item.getPermissionDepth() == depth)
                      .collect(Collectors.toList());
      for (SystemPermissionVo item : child) {
        List<SystemPermissionVo> childList = dataMap.get(item.getPermissionId());
        if (!CollectionUtils.isEmpty(childList)) {
          item.setChildren(childList);
          int isSelect = item.getChecked();
          if (isSelect == 1) {
            // 根据子节点判断本节点是全选还是部分选中，子节点存在未选中或者存在部分选中的时候，当前是部分选中
            childList.stream().forEach(childItem -> {
              if (childItem.getChecked().intValue() == Constants.GLOBAL_NOT_USE
                      || childItem.getChecked().intValue() == 2) {
                item.setChecked(2);
              }
            });
          }
        }
        List<SystemPermissionVo> list = dataMap.get(item.getParentId());
        if (CollectionUtils.isEmpty(list)) {
          list = new ArrayList<>();
        }
        list.add(item);
        dataMap.put(item.getParentId(), list);
      }
    }

    List<SystemPermissionVo> result = new ArrayList<>();
    //优化
    Map<Integer, SystemPermissionVo> existPermissionMap = dataList.stream()
            .collect(Collectors.toMap(SystemPermissionVo::getPermissionId, v -> v, (key1, key2) -> key2));

    dataMap.forEach((id, list) -> {
      if (existPermissionMap.containsKey(id)) {
        return;
      }
      result.addAll(list);
    });

    return result;
  }

  /**
   * 内部方法，获取集合内最深的节点数
   *
   * @param list
   * @return
   */
  private static int getNewMaxDepth(List<SystemPermissionVo> list) {
    if (CollectionUtils.isEmpty(list)) {
      return 0;
    }
    int maxDepth = 0;
    for (SystemPermissionVo item : list) {
      if(ObjectUtils.isEmpty(item)){
        continue;
      }
      maxDepth = Math.max(maxDepth, item.getPermissionDepth());
    }
    return maxDepth;
  }

}
