public ResponseDTO<UnitLevelVo> listUnits() {
List<UnitManagementsEntity> unitList = unitManagementDao.countDistinctUnitTree();
UnitLevelVo root = buildUnitTree(unitList, 0); // 传入根节点的父级ID
return ResponseDTO.succData(root);
}
public UnitLevelVo buildUnitTree(List<UnitManagementsEntity> unitList, int id) {
// 创建一个 UnitLevelVo 对象作为当前节点
UnitLevelVo node = new UnitLevelVo();
if (id == 0) {
node.setName("根节点");
}
for (UnitManagementsEntity unit : unitList) {
// 检查当前单位的父级 ID 是否等于指定的 parentId
if (unit.getParentId() == id) {
// 递归调用 buildUnitTree 方法构建子节点
UnitLevelVo childNode = buildUnitTree(unitList, unit.getId());
// 使用映射来设置更易于理解的名称
String readableName = UNIT_NAME_MAP.getOrDefault(unit.getId(), unit.getUnitLevel().toString());
childNode.setName(readableName);
// 将子节点添加到当前节点的子节点列表中
node.getChildren().add(childNode);
}
}
// 返回当前节点
return node;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UnitLevelVo {
@ApiModelProperty("父级单位id")
private Long id;
@ApiModelProperty("单位名称")
private String name;
@ApiModelProperty("子级单位名称")
private List<UnitLevelVo> children = new ArrayList<>();
}