liuxiaolong
2019-05-06 f99bc8c6a1d10610373738edd7d0aa0181c81d99
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package com.cloud.user.controller;
 
//import com.cloud.common.utils.AppUserUtil;
import com.cloud.model.common.Result;
import com.cloud.model.sys.LoginAppUser;
import com.cloud.model.sys.SysMenu;
import com.cloud.model.sys.SysRole;
import com.cloud.user.service.SysMenuService;
import com.cloud.user.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
 
@RestController
@RequestMapping("/data/api-u/sysmenus")
@Api(value = "SysMenuController", description = "菜单控制层")
public class SysMenuController {
 
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private TokenService tokenService;
    /**
     * 当前登录用户的菜单
     */
    @GetMapping("/me")
    @ApiOperation(value = "查询用户菜单", notes = "当前登录用户的菜单", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result findMyMenu(@RequestParam Map<String,Object> params) {
        LoginAppUser loginAppUser = tokenService.currentUser();
        if(loginAppUser ==null){//redis中token过期
            return Result.custom("登录过期,请重新登录!", 401, false, "登录过期,请重新登录!");
        }
        Set<SysRole> roles = loginAppUser.getSysRoles();
        if (CollectionUtils.isEmpty(roles)) {
            return Result.ok("查询成功", Collections.emptyList());
//            return Collections.emptyList();
        }
 
        Set<Long> roleIds = roles.parallelStream().map(SysRole::getId).collect(Collectors.toSet());
        params.put("roleIds",roleIds);
        Set<SysMenu> menusSet = sysMenuService
                .findByRoles(params);
 
        List<SysMenu> menus = new ArrayList<SysMenu>(menusSet);
        Collections.sort(menus, new Comparator<SysMenu>() {
            @Override
            public int compare(SysMenu o1, SysMenu o2) {
                return o1.getSort()<o2.getSort() ? -1 :1;
            }
        });
 
        //判断是否选择模块
        List<SysMenu> firstLevelMenus = null;
        if(params.containsKey("module")&&params.get("module")!=null&&!params.get("module").toString().equals("")){
            String module = params.get("module").toString();
            for(SysMenu menu: menus){
                if(menu.getType()==0&&menu.getModule().equals(module)){
                    final Object parentId = menu.getId();
                    firstLevelMenus = menus.stream().filter(m -> m.getParentId().equals(parentId))
                            .collect(Collectors.toList());
                }
            }
        }
        if(firstLevelMenus == null){
            firstLevelMenus = menus.stream().filter(m -> m.getParentId().equals(0L))
                    .collect(Collectors.toList());
        }
        firstLevelMenus.forEach(m -> {
            setChild(m, menus);
        });
//        return firstLevelMenus;
        return Result.ok("查询成功", firstLevelMenus);
    }
 
    private void setChild(SysMenu menu, List<SysMenu> menus) {
        List<SysMenu> child = menus.stream().filter(m -> m.getParentId().equals(menu.getId()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(child)) {
            menu.setChild(child);
            child.forEach(m -> {
                setChild(m, menus);
            });
        }
    }
 
    /**
     * 菜单树ztree
     */
    @GetMapping("/tree")
    @ApiOperation(value = "菜单树", notes = "用作修改权限时菜单树的查询", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<SysMenu> findMenuTree() {
        LoginAppUser loginAppUser = tokenService.currentUser();
        List<SysMenu> list = new ArrayList<>();
        //判断当前用户类型是超级管理员查全部菜单  0代表超级管理员
        if(loginAppUser.getUserType()!=null && loginAppUser.getUserType().equals("0")){
            List<SysMenu> all = sysMenuService.findAll();
            setMenuTree(0L, all, list);
        }else{
//            list = findMyMenu(new HashMap<>());
            Result result = findMyMenu(new HashMap<>());
            if(result.isSuccess())
                list = (List)result.getData();
        }
        return list;
    }
 
    /**
     * 菜单树
     */
    private void setMenuTree(Long parentId, List<SysMenu> all, List<SysMenu> list) {
        all.forEach(menu -> {
            if (parentId.equals(menu.getParentId())) {
                list.add(menu);
 
                List<SysMenu> child = new ArrayList<>();
                menu.setChild(child);
                setMenuTree(menu.getId(), all, child);
            }
        });
    }
 
    /**
     * 获取角色的菜单
     */
    @GetMapping("menusByRole")
    @ApiOperation(value = "获取角色菜单", notes = "获取角色的菜单,用户修改用户权限时候的回显", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织ID", required = true, dataType = "Long", paramType = "query"),
    })
    public Set<Long> findMenuIdsByRoleId(@RequestParam Map<String,Object> params) {
        return sysMenuService.findMenuIdsByRoleId(params);
    }
 
    /**
     * 根据用户id获取角色的菜单
     */
    @GetMapping("findMenuIdsByUserId")
    @ApiOperation(value = "根据用户id获取角色的菜单", notes = "根据用户id获取角色的菜单,用户组织管理赋权限回显", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织ID", required = true, dataType = "Long", paramType = "query"),
    })
    public Set<Long> findMenuIdsByUserId(@RequestParam Map<String,Object> params) {
        return sysMenuService.findMenuIdsByUserId(params);
    }
 
    /**
     * 添加菜单
     */
    @PostMapping
    @ApiOperation(value = "添加菜单", notes = "添加菜单模块", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menu", value = "SysMenu实例", required = true, dataType = "SysMenu", paramType = "body")
    })
    public SysMenu save(@RequestBody SysMenu menu) {
 
        menu.setOrgId(tokenService.currentUser().getOrgId());
        sysMenuService.save(menu);
        return menu;
    }
 
    /**
     * 修改菜单
     */
    @PutMapping
    @ApiOperation(value = "修改菜单", notes = "修改菜单模块", httpMethod = "PUT", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menu", value = "SysMenu实例", required = true, dataType = "SysMenu", paramType = "body")
    })
    public SysMenu update(@RequestBody SysMenu menu) {
 
        menu.setOrgId(tokenService.currentUser().getOrgId());
        sysMenuService.update(menu);
        return menu;
    }
 
    /**
     * 删除菜单
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除菜单", notes = "删除菜单模块", httpMethod = "DELETE", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单id", required = true, dataType = "Long", paramType = "path")
    })
    public Integer delete(@PathVariable Long id) {
 
       return sysMenuService.delete(id,tokenService.currentUser().getOrgId());
    }
 
    /**
     * 查询所有菜单
     *
     * @return
     */
    @GetMapping("/all")
    @ApiOperation(value = "查询所有菜单", notes = "查询所有菜单模块", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<SysMenu> findAll() {
 
        List<SysMenu> all = sysMenuService.findAll();
        List<SysMenu> list = new ArrayList<>();
        setSortTable(0L, all, list);
        return list;
    }
 
    /**
     * 菜单table
     */
    private void setSortTable(Long parentId, List<SysMenu> all, List<SysMenu> list) {
        all.forEach(a -> {
            if (a.getParentId().equals(parentId)) {
                list.add(a);
                setSortTable(a.getId(), all, list);
            }
        });
    }
 
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个菜单", notes = "根据id查询单个菜单", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单id", required = true, dataType = "Long", paramType = "path")
    })
    public SysMenu findById(@PathVariable Long id) {
 
        return sysMenuService.findById(id,tokenService.currentUser().getOrgId());
    }
 
    @GetMapping("/findMenuByUser")
    @ApiOperation(value = "查询当前登录人可以访问是模块名称",response = Map.class, responseContainer = "Map", notes = "查询当前登录人可以访问是模块名称", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "机构id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前登录人id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "tags", value = "查询的模块device or map", required = true, dataType = "Long", paramType = "query"),
    })
    public List<Map<String, Object>> findMenuByUser(@RequestParam Map<String, Object> map) {
        return sysMenuService.findMenuByUser(map);
    }
 
    @GetMapping("/findMenuByUserHome")
    @ApiOperation(value = "查询当前登录人可以访问是模块名称(包含首页)",response = Map.class, responseContainer = "Map", notes = "查询当前登录人可以访问是模块名称(包含首页)", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "机构id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前登录人id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "tags", value = "查询的模块device or map", required = true, dataType = "Long", paramType = "query"),
    })
    public List<Map<String, Object>> findMenuByUserHome(@RequestParam Map<String, Object> map) {
 
        return sysMenuService.findMenuByUserHome(map);
    }
 
    @GetMapping("/findAllMenuByUser")
    @ApiOperation(value = "查询所有模块名称",response = Map.class, responseContainer = "Map", notes = "查询所有模块名称", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "机构id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前登录人id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "tags", value = "查询的模块device or map", required = true, dataType = "Long", paramType = "query"),
    })
    public List<Map<String, Object>> findAllMenuByUser(@RequestParam Map<String, Object> map) {
 
        return sysMenuService.findAllMenuByUser(map);
    }
 
 
    @Log4j
    @RestControllerAdvice
    public static class ExceptionHandlerAdvice {
 
        @ExceptionHandler({ IllegalArgumentException.class })
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        public Map<String, Object> badRequestException(IllegalArgumentException exception) {
            Map<String, Object> data = new HashMap<>();
            data.put("code", HttpStatus.BAD_REQUEST.value());
            data.put("message", exception.getMessage());
 
            return data;
        }
 
 
        @ExceptionHandler({Exception.class, Throwable.class})
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public Map<String, Object> serverException(Throwable throwable) {
            ExceptionHandlerAdvice.log.error("服务端异常", throwable);
            Map<String, Object> data = new HashMap<>();
            data.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            data.put("message", "服务端异常,请联系管理员 ,错误信息:"+throwable.getLocalizedMessage());
 
            return data;
        }
 
        @ExceptionHandler({ SecurityException.class })
        @ResponseStatus(HttpStatus.UNAUTHORIZED)
        public Map<String, Object> badRequestException(SecurityException exception) {
            Map<String, Object> data = new HashMap<>();
            data.put("code", HttpStatus.UNAUTHORIZED.value());
            data.put("message", exception.getMessage());
 
            return data;
        }
    }
}