package com.inkasso.adapter.tree;

import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class TreeUtils<T extends TreeNode> {

  //把一个List转成树
  public   List<T> buidTree(List<T> list, Object parentId) {
    List<T> tree = new ArrayList<>();
    for (T node : list) {
      if (node.getPid().equals(parentId)) {
        tree.add(findChild(node, list));
      }
    }
    return tree;
  }

  private   T findChild(T node, List<T> list) {
    for (T n : list) {
      if (node.getId().equals(n.getPid())) {
        if (node.getChildren() == null) {
          node.setChildren(new ArrayList<T>());
        }
        node.getChildren().add(findChild(n, list));
      }
    }
    return node;
  }

  public static void main(String[] args) {
//    TestNode node1 = new TestNode(1L, "山东省", 0L);
//    TestNode node2 = new TestNode(2L, "德州市", 1L);
//    TestNode node3 = new TestNode(3L, "夏津县", 2L);
//    TestNode node4 = new TestNode(4L, "济南市", 2L);
//    TestNode node5 = new TestNode(5L, "天津", 3L);
//    TestNode node6 = new TestNode(6L, "红桥区", 5L);
//    List<TestNode> list = new ArrayList<>();
//    list.add(node1);
//    list.add(node2);
//    list.add(node3);
//    list.add(node4);
//    list.add(node5);
//    list.add(node6);
//    TreeUtils treeUtils = new TreeUtils();
//    List<TestNode> nodes = treeUtils.buidTree(list, 0L);
//    // System.out.println(JSON.toJSONString(nodes));
//    show(nodes, null);


  }


  public static void show(List<TestNode> test, String... str) {
    if (!CollectionUtils.isEmpty(test)) {
      String[] newStr = null;
      for (TestNode t : test) {
        if (str == null) {
          newStr = new String[1];
          newStr[0] = t.getName();
        } else {
          newStr = Arrays.copyOf(str, str.length + 1);
          newStr[newStr.length - 1] = t.getName();
        }
        show(t.getChildren(), newStr);
        System.out.println(Arrays.toString(newStr) + "===" + t.getId());
      }
    }
  }


  @Data
  static class TestNode implements TreeNode {

    private Long id;

    private String name;

    private Long parentId;

    private List children;


    public TestNode(Long id, String name, Long parentId) {
      this.id = id;
      this.name = name;
      this.parentId = parentId;
    }

    @Override
    public Long getId() {
      return id;
    }

    @Override
    public Long getPid() {
      return parentId;
    }

    @Override
    public void setChildren(List treeNode) {
      this.children = treeNode;
    }

    @Override
    public List getChildren() {

      return children;
    }
  }

}