P15GEN2\59518
2024-05-29 d4210c7c4b04abde20037ea8aa0f54ef8a2649aa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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;
    }
    
}