public int compare(Resource r1, Resource r2) { int l1 = r1.getStructure().length(); int l2 = r2.getStructure().length(); if (l1 == l2) { return r1.getSortNo().compareTo(r2.getSortNo()); } return l1 > l2 ? 1 : -1; }
@Override public String getResourceTree(Integer roleId) { Set<Integer> setResource = new HashSet<Integer>(); if (roleId != null) { List<Resource> tempResourceList = resourceMapper.getResourceListByRoleId(roleId); if (tempResourceList != null && tempResourceList.size() > 0) { for (Resource r : tempResourceList) { setResource.add(r.getId()); } } } List<Module> moduleList = moduleMapper.getModuleList(); List<Resource> resourceList = resourceMapper.getResourceList(); Collections.sort(moduleList, new ComparatorModule()); Collections.sort(resourceList, new ComparatorResource()); Set<Integer> setParent = new HashSet<Integer>(); for (Resource r : resourceList) { setParent.add(r.getParentId()); } StringBuilder sb = new StringBuilder(); Map<String, Integer> mapModule = new HashMap<String, Integer>(); sb.append("["); int i = 0; for (Module m : moduleList) { mapModule.put(m.getFlag(), m.getId()); if (i != 0) { sb.append(","); } i++; sb.append("{") .append("\"id\":\"") .append("m_") .append(m.getId()) .append("\"") .append(",\"parent\":\"") .append("#\"") .append(",\"text\":\"") .append(m.getName()) .append("\"") .append(",\"li_attr\":{\"flag\":\"") .append(m.getFlag()) .append("\"}"); // 前两个级别默认打开 sb.append(",\"state\":{"); sb.append("\"opened\":true"); sb.append("}"); sb.append("}"); } i = 0; for (Resource r : resourceList) { int level = r.getStructure().split("-").length; sb.append(","); i++; sb.append("{") .append("\"id\":\"") .append(r.getId()) .append("\"") .append(",\"parent\":\"") .append( r.getParentId() == 0 ? ("m_" + mapModule.get(r.getModuleFlag())) : r.getParentId()) .append("\"") .append(",\"text\":\"") .append(r.getName()) .append("\"") .append(",\"li_attr\":{\"flag\":\"") .append(r.getModuleFlag()) .append("\",\"sortNo\":") .append(r.getSortNo()) .append("}"); // 前两个级别默认打开 if (level <= 2) { sb.append(",\"state\":{\"opened\":true"); if (setResource.contains(r.getId())) { sb.append(",\"selected\":true"); } sb.append("}"); } else { if (setResource.contains(r.getId())) { sb.append(",\"state\":{\"opened\":true}"); } } // 最后一个级别换个绿色图标 if (!setParent.contains(r.getId())) { sb.append(", \"icon\": \"fa fa-briefcase icon-success\""); } sb.append("}"); } sb.append("]"); return sb.toString(); }