cjl
2023-11-07 54beb665319b66742cdec3dffb7e298701d61582
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
package com.moral.api.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.api.entity.*;
import com.moral.api.mapper.*;
import com.moral.api.pojo.bo.UserBO;
import com.moral.api.pojo.enums.AllocationApproveEnum;
import com.moral.api.pojo.enums.FileTableEnum;
import com.moral.api.pojo.enums.StateEnum;
import com.moral.api.pojo.enums.SysDictTypeEnum;
import com.moral.api.pojo.query.app.AppAllocationPushUserCond;
import com.moral.api.pojo.vo.file.FileVo;
import com.moral.api.service.FileTableService;
import com.moral.api.service.ResponsibilityUnitService;
import com.moral.api.service.UserService;
import com.moral.api.utils.OperationLogUtils;
import com.moral.api.utils.WechatUtils;
import com.moral.api.vo.WxMssVo;
import com.moral.constant.Constants;
import com.moral.constant.ResponseCodeEnum;
import com.moral.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author moral
 * @since 2021-03-09
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
 
    @Autowired
    private UserMapper userMapper;
 
    @Autowired
    private MenuMapper menuMapper;
 
    @Autowired
    private UserGroupMapper userGroupMapper;
 
    @Autowired
    private UserLogMapper userLogMapper;
 
    @Autowired
    private FileTableService fileTableService;
 
    @Autowired
    private OperationLogUtils operationLogUtils;
 
    @Autowired
    private ResponsibilityUnitMapper responsibilityUnitMapper;
 
 
    @Value("${AES.KEY}")
    private String AESKey;
 
    @Override
    public UserBO selectUserInfo(Map<String, Object> parameters) {
        return userMapper.selectUserInfo(parameters);
    }
 
    /**
     * 小程序登陆
     * @param parameters
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> loginSmallRoutine(Map<String, Object> parameters) {
        UserBO userBo = selectUserInfo(parameters);
        String openId = parameters.get("openId").toString();
        Map<String, Object> result = new HashMap<>();
        //校验账户
        if (userBo == null) {
            result.put("code", ResponseCodeEnum.ACCOUNT_NOT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return result;
        }
        //校验是否删除
        if (Constants.DELETE.equals(userBo.getIsDelete())) {
            result.put("code", ResponseCodeEnum.ACCOUNT_IS_DELETE.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_IS_DELETE.getMsg());
            return result;
        }
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(userBo.getUnitId());
        List<Integer> list = responsibilityUnitMapper.selectCodeList(SysDictTypeEnum.SYS_DEVICE.value, userBo.getId());
        //封装用户信息
        Map<String, Object> userInfo = new LinkedHashMap<>();
        userInfo.put("userId", userBo.getId());
        userInfo.put("account", userBo.getAccount());
        userInfo.put("userName", userBo.getUserName());
        userInfo.put("email", userBo.getEmail());
        userInfo.put("mobile", userBo.getMobile());
        userInfo.put("unitId",userBo.getUnitId());
        userInfo.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getAreaName())?responsibilityUnit.getAreaName():"未选择责任单位");
        userInfo.put("wechat", userBo.getWechat());
        userInfo.put("expireTime", DateUtils.dateToDateString(userBo.getExpireTime()));
        userInfo.put("isAdmin", userBo.getIsAdmin());
        userInfo.put("organizationId",userBo.getOrganizationId());
        userInfo.put("openid", openId);
 
        try {
            //生成token,并存入redis
            String token = TokenUtils.getTokenApp(new StringBuffer("00").append(userBo.getId().toString()).toString(),userInfo);
            result.put("token", token);
            result.put("userName", userBo.getUserName());
            result.put("unitId",userBo.getUnitId());
            result.put("userId", userBo.getId());
            result.put("account", userBo.getAccount());
            List<FileVo> listFile =  fileTableService.list(userBo.getId(), FileTableEnum.APP_ALLOCATION.value);
            result.put("file", CollectionUtils.isNotEmpty(listFile)?listFile.get(0):new FileVo());
            result.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getUnitName())?responsibilityUnit.getUnitName():"管理员登陆");
            result.put("device",ObjectUtils.isEmpty(list)? StateEnum.NOT_EFFECTIVE.value :StateEnum.TAKE_EFFECT.value);
        } catch (Exception e) {
            log.error("token生成异常:" + e.getMessage());
            result.put("code", ResponseCodeEnum.TOKEN_CREATE_ERROR.getCode());
            result.put("msg", ResponseCodeEnum.TOKEN_CREATE_ERROR.getMsg());
            return result;
        }
        sysLog("登陆了用户:" + userBo.getAccount()+";openId:"+openId,userBo);
        //添加openId到user表中
        User user = userMapper.selectById(userBo.getId());
        user.setOpenId(openId);
        userMapper.updateById(user);
        return result;
    }
 
    @Override
    public Map<String, Object> wxLogin(String code) {
        Map<String, Object> result = new HashMap<>();
        // 用户非敏感信息:rawData
        // 签名:signature
//        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtils.getSessionKeyOrOpenId(code);
 
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
//        String sessionKey = SessionKeyOpenId.getString("session_key");
 
        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
//        if (!signature.equals(signature2)) {
//           return ResultMessage.ok().message("签名校验失败");
//            return ResultMessage.ok("签名校验失败");
//            throw new BusinessException("签名校验失败");
//        }
        // 5.根据返回的User实体类,判断用户是否是新用户,是的话,将用户信息存到数据库;
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getOpenId, openid);
        User user = userMapper.selectOne(lqw);
        if (user == null) {
            result.put("code", ResponseCodeEnum.USER_NOT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.USER_NOT_EXIST.getMsg());
            result.put("openId",openid);
            return result;
            // 用户信息入库
//            String nickName = rawDataJson.getString("nickName");
//            String avatarUrl = rawDataJson.getString("avatarUrl");
        }
 
        Map<String, Object> userInfo = new LinkedHashMap<>();
        userInfo.put("userId", user.getId());
        userInfo.put("account", user.getAccount());
        userInfo.put("userName", user.getUserName());
        userInfo.put("email", user.getEmail());
        userInfo.put("mobile", user.getMobile());
        userInfo.put("unitId",user.getUnitId());
//        userInfo.put("unName",user.getAreaName());
        userInfo.put("organizationId",user.getOrganizationId());
        userInfo.put("wechat", user.getWechat());
        userInfo.put("expireTime", DateUtils.dateToDateString(user.getExpireTime()));
        userInfo.put("isAdmin", user.getIsAdmin());
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(user.getUnitId());
        List<Integer> list = responsibilityUnitMapper.selectCodeList(SysDictTypeEnum.SYS_DEVICE.value, user.getId());
        try {
            //生成token,并存入redis
            String token = TokenUtils.getTokenApp(new StringBuffer("00").append(user.getId().toString()).toString(),userInfo);
            result.put("token", token);
            result.put("userName", user.getUserName());
            result.put("unitId",user.getUnitId());
            List<FileVo> listFile =  fileTableService.list(user.getId(), FileTableEnum.APP_ALLOCATION.value);
            result.put("file", CollectionUtils.isNotEmpty(listFile)?listFile.get(0):new FileVo());
            result.put("userId", user.getId());
            result.put("account", user.getAccount());
            result.put("device",ObjectUtils.isEmpty(list)? StateEnum.NOT_EFFECTIVE.value : StateEnum.TAKE_EFFECT.value);
            result.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getUnitName())?responsibilityUnit.getUnitName():"管理员登陆");
            result.put("openId",openid);
        } catch (Exception e) {
            log.error("token生成异常:" + e.getMessage());
            result.put("code", ResponseCodeEnum.TOKEN_CREATE_ERROR.getCode());
            result.put("msg", ResponseCodeEnum.TOKEN_CREATE_ERROR.getMsg());
            return result;
        }
        result.put("code", ResponseCodeEnum.SUCCESS.getCode());
        result.put("msg", ResponseCodeEnum.SUCCESS.getMsg());
        sysLog("登陆了用户:" + user.getAccount()+" ;openId:"+openid,user);
        return result;
    }
 
    @Override
    public boolean updateUserId(Integer userId) {
        User user = userMapper.selectById(userId);
        user.setOpenId("0");
        userMapper.updateById(user);
        sysLog(userId+"退出了小程序",user);
        return true;
    }
 
 
     @Autowired
     private ResponsibilityUnitService responsibilityUnitService;
    /**
     * 小程序推送
     * @param appAllocationPushUserCond
     */
    @Override
    @Async
    public void pushOneUser(AppAllocationPushUserCond appAllocationPushUserCond) {
 
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(appAllocationPushUserCond.getUnitId());
        Integer areaCode = responsibilityUnit.getAreaCode();
 
        List<ResponsibilityUnit> responsibilityUnits = responsibilityUnitService.selectAreaUnit(areaCode.toString().length()>6?responsibilityUnit.getParentCode():responsibilityUnit.getAreaCode());
        //获取unitid
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getIsDelete,Constants.NOT_DELETE);
        Integer state = appAllocationPushUserCond.getState();
        if (state==20){
            wrapper.eq(User::getUnitId,appAllocationPushUserCond.getUnitId());
        }else {
            wrapper.eq(User::getUnitId,ObjectUtils.isEmpty(responsibilityUnits)?0:responsibilityUnits.get(0).getUnitId());
        }
 
        List<User> users = userMapper.selectList(wrapper);
        if (ObjectUtils.isEmpty(users)){
            return;
        }
 
        String dateString = DateUtils.dateToDateString(appAllocationPushUserCond.getEscalationTime(),"MM月dd日");
        //这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
        //小程序订阅
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + WechatUtils.getAccessToken();
        //发送消息
        for (User user : users) {
            RestTemplate restTemplate = new RestTemplate();
            //拼接推送的模版
            WxMssVo wxMssVo = new WxMssVo();
            wxMssVo.setTouser(user.getOpenId());//用户的openid(要发送给那个用户,通常这里应该动态传进来的)
            wxMssVo.setTemplate_id("YNqUZ1MgMvwY3G-NENVbcmIBR5dUotSdnwcz96CWrho");//订阅消息模板id
            wxMssVo.setLang("zh_CN");
            wxMssVo.setMiniprogramState("formal");
//        wxMssVo.setPage("pages/index/index");
            Map<String, Object> m = new HashMap<>();
            HashMap<String, Object> map1 = new HashMap<>();
            HashMap<String, Object> map2 = new HashMap<>();
            HashMap<String, Object> map3 = new HashMap<>();
            HashMap<String, Object> map4 = new HashMap<>();
            map1.put("value",responsibilityUnit.getUnitName()+dateString+"的交办单");
            map2.put("value",appAllocationPushUserCond.getAllocationNum());
            map3.put("value",state==30? AllocationApproveEnum.IN_APPROVAL.name:AllocationApproveEnum.UNDER_RECTIFICATION.name);
            map4.put("value",DateUtils.dateToDateString(new Date(),"yyyy年MM月dd日"));
            m.put("thing18", map1);
            m.put("character_string1", map2);
            m.put("thing2", map3);
            m.put("date4", map4);
            wxMssVo.setData(JSON.toJSON(m));
            ResponseEntity<String> responseEntity =
                    restTemplate.postForEntity(url, wxMssVo, String.class);
            String body = responseEntity.getBody();
            log.info("信息:"+body+"账号:"+user.getUserName());
        }
    }
 
    private void sysLog(String cont,User user){
        //日志
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        UserLog userLog = new UserLog();
        userLog.setType(Constants.LOGIN_OPERTATE_APP);
        userLog.setIp(WebUtils.getIpAddr(request));
        userLog.setOperateId(user.getId());
        userLog.setOrganizationId(user.getOrganizationId());
        userLog.setContent(cont);
        userLogMapper.insert(userLog);
    }
 
    @Override
    public Map<String, Object> login(Map<String, Object> parameters) {
        UserBO userBo = selectUserInfo(parameters);
        Map<String, Object> result = new HashMap<>();
        //校验账户
        if (userBo == null) {
            result.put("code", ResponseCodeEnum.ACCOUNT_NOT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return result;
        }
        //校验密码
        String password = parameters.get("password").toString();
        //密码解密
        password = AESUtils.decrypt(password, AESKey);
        if (!MD5Utils.saltMD5Verify(password, userBo.getPassword())) {
            result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
            return result;
        }
        //校验是否删除
        if (Constants.DELETE.equals(userBo.getIsDelete())) {
            result.put("code", ResponseCodeEnum.ACCOUNT_IS_DELETE.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_IS_DELETE.getMsg());
            return result;
        }
        //校验是否过期
        if (userBo.getExpireTime() != null && userBo.getExpireTime().getTime() < System.currentTimeMillis()) {
            result.put("code", ResponseCodeEnum.ACCOUNT_IS_EXPIRE.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_IS_EXPIRE.getMsg());
            return result;
        }
 
        //封装用户信息
        Map<String, Object> userInfo = new LinkedHashMap<>();
        ResponsibilityUnit responsibilityUnit = responsibilityUnitMapper.selectById(userBo.getUnitId());
        //用户信息
        userInfo.put("userId", userBo.getId());
        userInfo.put("account", userBo.getAccount());
        userInfo.put("userName", userBo.getUserName());
        userInfo.put("email", userBo.getEmail());
        userInfo.put("mobile", userBo.getMobile());
        userInfo.put("unitId",userBo.getUnitId());
        userInfo.put("unName",Objects.nonNull(responsibilityUnit)&&Objects.nonNull(responsibilityUnit.getAreaName())?responsibilityUnit.getAreaName():"未选择责任单位");
        userInfo.put("wechat", userBo.getWechat());
        userInfo.put("expireTime", DateUtils.dateToDateString(userBo.getExpireTime()));
        userInfo.put("isAdmin", userBo.getIsAdmin());
 
        //用户组织信息
        Organization organization = userBo.getOrganization();
        Map<String, Object> orgInfo = new LinkedHashMap<>();
        orgInfo.put("id", userBo.getOrganizationId());
        orgInfo.put("name", organization.getName());
        orgInfo.put("locationLevelCode", organization.getLocationLevelCode());
        orgInfo.put("expireTime", DateUtils.dateToDateString(organization.getExpireTime()));
        userInfo.put("organization", orgInfo);
 
        //用户组信息
        Group group = userBo.getGroup();
        Map<String, Object> groupMap = new LinkedHashMap<>();
        userInfo.put("group", groupMap);
        if (group != null) {
            groupMap.put("id", group.getId());
            groupMap.put("groupName", group.getGroupName());
            userInfo.put("group", groupMap);
        }
 
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userBo.getId());
        //用户菜单信息
        userInfo.putAll(getMenus(map));
        try {
            //生成token,并存入redis
            String token = TokenUtils.getToken(userBo.getId().toString(), userInfo);
            result.put("token", token);
        } catch (Exception e) {
            log.error("token生成异常:" + e.getMessage());
            result.put("code", ResponseCodeEnum.TOKEN_CREATE_ERROR.getCode());
            result.put("msg", ResponseCodeEnum.TOKEN_CREATE_ERROR.getMsg());
            return result;
        }
        //日志
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        UserLog userLog = new UserLog();
        userLog.setType(Constants.LOGIN_OPERTATE_TYPE);
        userLog.setIp(WebUtils.getIpAddr(request));
        userLog.setOperateId(userBo.getId());
        userLog.setOrganizationId(userBo.getOrganizationId());
        userLog.setContent("登陆了用户:" + userBo.getAccount());
        userLogMapper.insert(userLog);
        return result;
    }
 
    @Override
    public Map<String, Object> getCurrentUserInfo() {
        Map<String, Object> userInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        return userInfo;
    }
 
    @Override
    public Map<String, Object> getMenus(Map<String, Object> parameters) {
        List<Menu> allMenus;
        if (parameters.containsKey("userId")) {
            allMenus = menuMapper.selectUserMenu(Integer.parseInt(parameters.get("userId").toString()));
        } else {
            allMenus = menuMapper.selectOrganizationMenu(Integer.parseInt(parameters.get("orgId").toString()));
            allMenus.removeIf(m -> "员工管理".equals(m.getName()));
        }
 
        Map<String, Object> resultMap = new LinkedHashMap<>();
        //第一级菜单
        List<Menu> oneMenu = allMenus.stream()
                .filter(o -> o.getParentId().equals(0))
                .sorted(Comparator.comparing(Menu::getOrder))
                .collect(Collectors.toList());
 
        List<Map<String, Object>> newList = new ArrayList<>();
        //遍历一级菜单
        oneMenu.forEach(o -> {
            Map<String, Object> menuMap = new LinkedHashMap<>();
            menuMap.put("id", o.getId());
            menuMap.put("label", o.getName());
            menuMap.put("url", o.getUrl());
            menuMap.put("icon", o.getIcon());
            menuMap.put("children", getMenusByRecursion(o, allMenus));
            newList.add(menuMap);
        });
        resultMap.put("menus", newList);
        return resultMap;
    }
 
    //获取用户层级菜单递归方法
    private List<Map<String, Object>> getMenusByRecursion(Menu menu, List<Menu> menus) {
        Menu newMenu = new Menu();
        newMenu.setParentId(menu.getId());
        //筛选出下一级菜单信息
        List<Menu> nextLevelMenus = menus.stream()
                .filter(o -> o.getParentId().equals(menu.getId()))
                .sorted(Comparator.comparing(Menu::getOrder))
                .collect(Collectors.toList());
        List<Map<String, Object>> list = new ArrayList<>();
        if (nextLevelMenus.size() > 0) {
            //遍历下一级菜单信息,并封装返回参数
            nextLevelMenus.forEach(o -> {
                Map<String, Object> menuMap = new LinkedHashMap<>();
                menuMap.put("id", o.getId());
                menuMap.put("label", o.getName());
                menuMap.put("url", o.getUrl());
                menuMap.put("icon", o.getIcon());
                //调用递归体
                menuMap.put("children", getMenusByRecursion(o, menus));
                list.add(menuMap);
            });
        }
        return list;
    }
 
    @Override
    @Transactional
    public Map<String, Object> addUser(User user) {
 
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfo();
 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount()).eq("is_delete", Constants.NOT_DELETE);
        //校验账户是否存在
        if (user.selectCount(queryWrapper) > 0) {
            result.put("code", ResponseCodeEnum.ACCOUNT_EXIST.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_EXIST.getMsg());
            return result;
        }
        //校验账户
        if (!RegexUtils.checkAccount(user.getAccount())) {
            result.put("code", ResponseCodeEnum.ACCOUNT_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.ACCOUNT_INVALID.getMsg());
            return result;
        }
 
        //校验邮箱
        if (!ObjectUtils.isEmpty(user.getEmail()) && !RegexUtils.checkEmail(user.getEmail())) {
            result.put("code", ResponseCodeEnum.EMAIL_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.EMAIL_INVALID.getMsg());
            return result;
        }
        //校验密码
        String password = user.getPassword();
        //密码解密
        password = AESUtils.decrypt(password, AESKey);
        if (!RegexUtils.checkPassword(password)) {
            result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
            return result;
        }
        //校验手机号
        if (!ObjectUtils.isEmpty(user.getMobile()) && !RegexUtils.checkMobile(user.getMobile())) {
            result.put("code", ResponseCodeEnum.MOBILE_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.MOBILE_INVALID.getMsg());
            return result;
        }
        //密码加密
        user.setPassword(MD5Utils.saltMD5(password));
        Map<String, Object> orgInfo = (Map<String, Object>) currentUserInfo.get("organization");
        Integer orgId = (Integer) orgInfo.get("id");
        user.setOrganizationId(orgId);
        user.setIsAdmin(false);
        //新增账户的过期时间
        Date userExpireTime = user.getExpireTime();
        //当前组织的过期时间
        Date orgExpireTime = DateUtils.getDate((String) orgInfo.get("expireTime"), DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        if (userExpireTime != null) {
            if (orgExpireTime != null && userExpireTime.getTime() > orgExpireTime.getTime()) {
                user.setExpireTime(orgExpireTime);
            } else {
                user.setExpireTime(userExpireTime);
            }
        } else {
            if (orgExpireTime != null) {
                user.setExpireTime(orgExpireTime);
            }
        }
        userMapper.insert(user);
        //日志
        String content = "添加了用户:" + user.getAccount();
        operationLogUtils.insertLog(content, Constants.INSERT_OPERATE_TYPE);
        return result;
    }
 
    @Override
    @Transactional
    public void deleteUser(Integer userId) {
        User user = userMapper.selectById(userId);
        //逻辑删除user
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId).set("is_delete", Constants.DELETE);
        userMapper.update(null, updateWrapper);
        //删除user_group
        UpdateWrapper<UserGroup> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("user_id", userId);
        userGroupMapper.delete(deleteWrapper);
        //清楚redis
        if (TokenUtils.hHasKey(userId.toString())) {
            String token = TokenUtils.hget(userId.toString()).toString();
            TokenUtils.destoryToken(userId.toString(), token);
        }
        //日志
        String content = "删除了用户:" + user.getAccount();
        operationLogUtils.insertLog(content, Constants.DELETE_OPERATE_TYPE);
    }
 
    @Override
    @Transactional
    public Map<String, Object> updateUser(User user) {
        Map<String, Object> result = new HashMap<>();
        //更新的属性
        Map<String, Object> update = JSONObject.parseObject(JSON.toJSONString(user), Map.class);
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        User beforeUser = userMapper.selectById(user.getId());
        Map<String, Object> before = JSONObject.parseObject(JSON.toJSONString(beforeUser), Map.class);
        /*String account = beforeUser.getAccount();
        //account不可修改
        user.setAccount(account);*/
        if (!ObjectUtils.isEmpty(user.getAccount())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", Constants.NOT_DELETE).eq("account", user.getAccount());
            if (userMapper.selectCount(queryWrapper) > 0) {
                result.put("code", ResponseCodeEnum.ACCOUNT_EXIST.getCode());
                result.put("msg", ResponseCodeEnum.ACCOUNT_EXIST.getMsg());
                return result;
            }
        }
 
        //邮箱校验
        if (!ObjectUtils.isEmpty(user.getEmail()) && !RegexUtils.checkEmail(user.getEmail())) {
            result.put("code", ResponseCodeEnum.EMAIL_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.EMAIL_INVALID.getMsg());
            return result;
        }
        //密码校验
        String password = user.getPassword();
        if (!ObjectUtils.isEmpty(password)) {
            //密码解密
            password = AESUtils.decrypt(password, AESKey);
            if (!RegexUtils.checkPassword(password)) {
                result.put("code", ResponseCodeEnum.PASSWORD_INVALID.getCode());
                result.put("msg", ResponseCodeEnum.PASSWORD_INVALID.getMsg());
                return result;
            }
        }
 
        //正则校验手机号
        if (!ObjectUtils.isEmpty(user.getMobile()) && !RegexUtils.checkMobile(user.getMobile())) {
            result.put("code", ResponseCodeEnum.MOBILE_INVALID.getCode());
            result.put("msg", ResponseCodeEnum.MOBILE_INVALID.getMsg());
            return result;
        }
        //密码MD5加密
        user.setPassword(MD5Utils.saltMD5(password));
        //组织信息
        Map<String, Object> orgInfo = (Map<String, Object>) currentUserInfo.get("organization");
        user.setOrganizationId((int) orgInfo.get("id"));
        user.setIsAdmin(false);
        //所修改账户的过期时间
        Date userExpireTime = user.getExpireTime();
        //当前组织的过期时间
        Date orgExpireTime = DateUtils.getDate((String) orgInfo.get("expireTime"), DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
        if (userExpireTime != null) {
            if (orgExpireTime != null && userExpireTime.getTime() > orgExpireTime.getTime()) {
                result.put("code", ResponseCodeEnum.EXPIRE_BEYOND_ADMIN.getCode());
                result.put("msg", ResponseCodeEnum.EXPIRE_BEYOND_ADMIN.getMsg());
                return result;
            }
        }
        //更新redis
        String userId = user.getId().toString();
        if (TokenUtils.hHasKey(userId)) {
            String deleteToken = TokenUtils.hget(userId).toString();
            TokenUtils.destoryToken(userId, deleteToken);
        }
        userMapper.updateById(user);
 
        //日志
        String account = userMapper.selectById(userId).getAccount();
        StringBuilder content = new StringBuilder("修改了用户:" + account + "->");
        for (String key : update.keySet()) {
            Object afterValue = update.get(key);
            if (!key.equals("id") && afterValue != null) {
                //修改前属性值
                Object beforeValue = before.get(key);
                content.append(key).append(":").append(beforeValue).append("=>").append(afterValue).append(";");
            }
        }
        operationLogUtils.insertLog(content.toString(), Constants.UPDATE_OPERATE_TYPE);
        return result;
    }
 
    @Override
    public Page<User> selectUsers(Map<String, Object> parameters) {
        Map<String, Object> currentUserInfo = (Map<String, Object>) TokenUtils.getUserInfo();
        Map<String, Object> orgInfo = (Map<String, Object>) currentUserInfo.get("organization");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organization_id", orgInfo.get("id"))
                .eq("is_delete", Constants.NOT_DELETE)
                .eq("is_admin", false);
        Object order = parameters.get("order");
        Object orderType = parameters.get("orderType");
        Object account = parameters.get("account");
        Object userName = parameters.get("userName");
        Object mobile = parameters.get("mobile");
        Object email = parameters.get("mobile");
        Object wechat = parameters.get("wechat");
        //模糊查询参数
        if (account != null) {
            queryWrapper.like("account", account);
        }
        if (userName != null) {
            queryWrapper.like("user_name", userName);
        }
        if (mobile != null) {
            queryWrapper.like("mobile", mobile);
        }
        if (email != null) {
            queryWrapper.like("email", email);
        }
        if (wechat != null) {
            queryWrapper.like("wechat", wechat);
        }
 
        int page = Integer.parseInt(parameters.get("page").toString());
        int size = Integer.parseInt(parameters.get("size").toString());
        Page<User> pageData = new Page<>(page, size);
        //排序参数,默认create_time降序
        if (order != null && orderType != null) {
            if (Constants.ORDER_ASC.equals(orderType)) {
                queryWrapper.orderByAsc(ConvertUtils.toLine(order.toString()));
            } else {
                queryWrapper.orderByDesc(ConvertUtils.toLine(order.toString()));
            }
        } else {
            queryWrapper.orderByDesc("create_time");
        }
        userMapper.selectPage(pageData, queryWrapper);
        return pageData;
    }
 
}