package cc.smtweb.system.bpm.test;

import cc.smtweb.system.bpm.util.ITreeDataLevelHandler;
import cc.smtweb.system.bpm.util.TreeDataUtil;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

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

public class TreeDataBuilderTest {
  @Test
  public void testFindParent() {
    // 树结构数据句柄
    TreeDataHandler handler = new TreeDataHandler();

    List<TreeData> list = new ArrayList<>();
    list.add(new TreeData(1L, null));
    list.add(new TreeData(2L, 1L));
    list.add(new TreeData(3L, 2L));
    list.add(new TreeData(4L, 3L));
    list.add(new TreeData(5L, 6L));

    TreeData root = new TreeData();

    TreeDataUtil.buildTree(root, list, handler);

    {
      TreeData node = TreeDataUtil.findParent(root, 4L, 1, handler);
      Assertions.assertEquals(1L, node.getId());
    }

    {
      TreeData node = TreeDataUtil.findParent(root, 3L, 1, handler);
      Assertions.assertEquals(1L, node.getId());
    }

    {
      TreeData node = TreeDataUtil.findParent(root, 3L, 2, handler);
      Assertions.assertEquals(2L, node.getId());
    }

    {
      TreeData node = TreeDataUtil.findParent(root, 1L, 2, handler);
      Assertions.assertNull(node);
    }
  }
}

@Data
class TreeData {
  private Long id;
  private Long parentId;
  private int level;
  private List<TreeData> children;

  TreeData() {
  }

  TreeData(Long id, Long parentId) {
    this.id = id;
    this.parentId = parentId;
  }
}

class TreeDataHandler implements ITreeDataLevelHandler<TreeData> {
  @Override
  public Long getId(TreeData node) {
    return node.getId();
  }

  @Override
  public Long getParentId(TreeData node) {
    return node.getParentId();
  }

  @Override
  public List<TreeData> getChildren(TreeData node) {
    return node.getChildren();
  }

  @Override
  public void setChildren(TreeData node, List<TreeData> children) {
    node.setChildren(children);
  }

  @Override
  public int getLevel(TreeData node) {
    return node.getLevel();
  }

  @Override
  public void setLevel(TreeData node, int level) {
    node.setLevel(level);
  }
}
