package foundation.dao.preload;
|
|
import java.util.Comparator;
|
|
import foundation.json.IJSONProvider;
|
import foundation.json.IJSONWriter;
|
import foundation.util.MapList;
|
|
public class Tree<T extends Node> extends Bucket<T> implements IJSONProvider {
|
|
private MapList<String, T> roots;
|
|
public Tree() {
|
roots = new MapList<String, T>();
|
}
|
|
@SuppressWarnings("unchecked")
|
public void onAfterLoad(boolean sort) {
|
//1. 初始化父子关系
|
initRelation();
|
|
//2. 排序
|
if (!sort || roots.isEmpty()) {
|
return;
|
}
|
|
for (T node: roots) {
|
if (node.containsChildren()) {
|
node.sort(null);
|
}
|
}
|
|
T node = roots.get(0);
|
Comparator<T> comparator = (Comparator<T>)node.createComparator();
|
roots.sortList(comparator);
|
}
|
|
public void onAfterLoad() {
|
initRelation();
|
}
|
|
public void initRelation() {
|
for (T item: items) {
|
String id = item.getId();
|
String parentId = item.getParentId();
|
|
if (parentId == null) {
|
roots.add(id, item);
|
continue;
|
}
|
|
T parent = items.get(parentId);
|
|
if (parent == null) {
|
continue;
|
}
|
|
item.parent = parent;
|
parent.addOneChild(item);
|
}
|
}
|
|
@Override
|
public void writeJSON(IJSONWriter writer) {
|
writer.beginArray();
|
|
for (Node item: roots) {
|
writer.beginObject();
|
item.writeJSONBody(writer);
|
writer.endObject();
|
}
|
|
writer.endArray();
|
}
|
|
public MapList<String, T> getRoots() {
|
return roots;
|
}
|
|
public void setRoots(MapList<String, T> roots) {
|
this.roots = roots;
|
}
|
|
}
|