kaiyu
2021-05-21 66ab6b7d3ac3e7a50a8a0c1506ea5448ea8d8eee
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
package com.moral.api.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moral.api.entity.ManageAccount;
import com.moral.api.entity.ManageAccountRole;
import com.moral.api.entity.ManageMenu;
import com.moral.api.entity.ManageRole;
import com.moral.api.mapper.ManageAccountMapper;
import com.moral.api.mapper.ManageAccountRoleMapper;
import com.moral.api.mapper.ManageMenuMapper;
import com.moral.api.mapper.ManageRoleMapper;
import com.moral.api.pojo.dto.account.*;
import com.moral.api.pojo.dto.login.AccountInfoDTO;
import com.moral.api.pojo.dto.login.LoginDTO;
import com.moral.api.pojo.form.account.AccountDeleteForm;
import com.moral.api.pojo.form.account.AccountInsertForm;
import com.moral.api.pojo.form.account.AccountQueryForm;
import com.moral.api.pojo.form.account.AccountUpdateForm;
import com.moral.api.pojo.form.login.LoginForm;
import com.moral.api.pojo.form.login.LogoutForm;
import com.moral.api.service.ManageAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.api.config.mybatis.wrapper.NullFilterWrapper;
import com.moral.api.service.ManageMenuService;
import com.moral.api.util.LogUtils;
import com.moral.constant.Constants;
import com.moral.constant.ResponseCodeEnum;
import com.moral.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.servlet.http.HttpServletRequest;
import java.util.*;
 
/**
 * <p>
 * 后台账户表 服务实现类
 * </p>
 *
 * @author moral
 * @since 2021-03-09
 */
@Service
@ConfigurationProperties(prefix = "log-aspect")
public class ManageAccountServiceImpl extends ServiceImpl<ManageAccountMapper, ManageAccount> implements ManageAccountService {
 
 
    @Autowired
    ManageAccountMapper manageAccountMapper;
    @Autowired
    ManageRoleMapper manageRoleMapper;
    @Autowired
    ManageMenuService manageMenuService;
    @Autowired
    ManageAccountRoleMapper manageAccountRoleMapper;
    @Autowired
    LogUtils logUtils;
 
    Map<String, String> manageAccountFormMap;
 
    public void setManageAccountFormMap(Map<String, String> manageAccountFormMap) {
        this.manageAccountFormMap = manageAccountFormMap;
    }
 
    /**
     * @Description: 登陆接口
     * @Param: [loginForm]
     * @return: com.moral.api.pojo.dto.login.LoginDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/30
     */
    @Override
    public LoginDTO login(LoginForm loginForm) {
        LoginDTO loginDTO = new LoginDTO();
        //取参
        String account = loginForm.getAccount();
        String AESPassword = loginForm.getPassword();
        //解密
        String password = AESUtils.decrypt(AESPassword);
        //查询是否存在
        QueryWrapper<ManageAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        List<ManageAccount> manageAccounts = manageAccountMapper.selectList(wrapper);
        if (ObjectUtils.isEmpty(manageAccounts)) {
            loginDTO.setCode(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getCode());
            loginDTO.setMsg(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return loginDTO;
        }
        //查询是否逻辑删除
        ManageAccount manageAccount = null;
        for (ManageAccount value : manageAccounts) {
            if (Constants.NOT_DELETE.equals(value.getIsDelete()))
                manageAccount = value;
        }
 
        if (ObjectUtils.isEmpty(manageAccount)) {
            loginDTO.setCode(ResponseCodeEnum.ACCOUNT_IS_DELETE.getCode());
            loginDTO.setMsg(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return loginDTO;
        }
        //校验密码
        if (!MD5Utils.saltMD5Verify(password, manageAccount.getPassword())) {
            loginDTO.setCode(ResponseCodeEnum.PASSWORD_ERROR.getCode());
            loginDTO.setMsg(ResponseCodeEnum.PASSWORD_ERROR.getMsg());
            return loginDTO;
        }
 
        //查询角色
        List<ManageRole> roles = manageRoleMapper.getManageRoleByAccountId(manageAccount.getId());
 
        //查询菜单
        List<ManageMenu> menus = null;
        if (!ObjectUtils.isEmpty(roles)) {
            menus = manageMenuService.getParentChildrenMenusByRoles(roles);
        }
 
        //封装用户信息
        AccountInfoDTO accountInfoDTO = new AccountInfoDTO();
        accountInfoDTO.setAccount(manageAccount);
        accountInfoDTO.setMenus(menus);
        accountInfoDTO.setRoles(roles);
 
        //获取token 并且存入缓存
        String token = TokenUtils.getToken(String.valueOf(manageAccount.getId()), accountInfoDTO);
 
        //封装返回结果
        loginDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        loginDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        loginDTO.setAccountInfoDTO(accountInfoDTO);
        loginDTO.setToken(token);
 
        //登陆插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append(manageAccount.getUserName()).append("登陆了后台系统;");
        logUtils.saveLoginForManage(request, content.toString(), manageAccount, manageAccount.getUserName());
 
        return loginDTO;
    }
 
    /**
     * @Description: 注销
     * @Param: [parameters]
     * @return:
     * @Author: 陈凯裕
     * @Date: 2021/3/11
     */
    @Override
    public boolean logout(LogoutForm logoutForm) {
        String accountId = logoutForm.getAccountId();
        String token = logoutForm.getToken();
        TokenUtils.destoryToken(accountId, token);
        return true;
    }
 
    /**
     * @Description: 添加后台账号
     * @Param: [accountAddRequest]
     * @return: com.moral.api.pojo.dto.AccountDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/13
     */
    @Override
    @Transactional
    public AccountDTO insertAccount(AccountInsertForm accountInsertForm) {
        AccountDTO accountDTO = new AccountDTO();
        //取参
        ManageAccount manageAccount = accountInsertForm.formConvertEntity();
        List<Integer> roleIds = accountInsertForm.getRoleIds();
 
        /*判断账号是否存在*/
        ManageAccount existAccount = new ManageAccount();
        existAccount.setAccount(manageAccount.getAccount());
        existAccount.setIsDelete(Constants.NOT_DELETE);
        QueryWrapper<ManageAccount> wrapper = new QueryWrapper<>();
        wrapper.setEntity(existAccount);
        ManageAccount exitAccountResult = manageAccountMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(exitAccountResult)) {
            accountDTO.setCode(ResponseCodeEnum.ACCOUNT_EXIST.getCode());
            accountDTO.setMsg(ResponseCodeEnum.ACCOUNT_EXIST.getMsg());
            return accountDTO;
        }
 
        //插入
        manageAccountMapper.insert(manageAccount);
 
        //如果新建账号没有分配角色则不进行操作
        if (!ObjectUtils.isEmpty(roleIds)) {
            Integer accountId = manageAccount.getId();
            roleIds.forEach(
                    value -> {
                        ManageAccountRole manageAccountRole = new ManageAccountRole();
                        manageAccountRole.setAccountId(accountId);
                        manageAccountRole.setRoleId(value);
                        manageAccountRoleMapper.insert(manageAccountRole);
                    }
            );
        }
        //封装返回结果
        accountDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        accountDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
 
        //操作插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("添加了用户:").append(manageAccount.getUserName() + ";")
                .append("account:" + manageAccount.getAccount() + ";");
        logUtils.saveOperationForManage(request, content.toString(), Constants.INSERT_OPERATE_TYPE);
 
        return accountDTO;
    }
 
    /**
     * @Description: 查询后台账号
     * @Param: [accountQueryRequest]
     * @return: com.moral.api.pojo.dto.AccountDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/15
     */
    @Override
    public AccountQueryDTO queryAccount(AccountQueryForm accountQueryForm) {
        AccountQueryDTO accountQueryDTO = new AccountQueryDTO();
 
        //取参
        Integer page = accountQueryForm.getPage();
        Integer size = accountQueryForm.getSize();
        String userName = accountQueryForm.getUserName();
        String email = accountQueryForm.getEmail();
        String mobile = accountQueryForm.getMobile();
        String wechat = accountQueryForm.getWechat();
        String isDelete = accountQueryForm.getIsDelete();
        String order = accountQueryForm.getOrder();
        String orderType = accountQueryForm.getOrderType();
        Date createStartTime = accountQueryForm.getCreateStartTime();
        Date createEndTime = accountQueryForm.getCreateEndTime();
 
        //组装查询条件
        Page<ManageAccount> queryPage = new Page<>(page, size);
        NullFilterWrapper<ManageAccount> wrapper = new NullFilterWrapper<>();
 
        wrapper.like("user_name", userName);
        wrapper.like("email", email);
        wrapper.like("mobile", mobile);
        wrapper.like("wechat", wechat);
        wrapper.between("create_time", createStartTime, createEndTime);
 
        if (!ObjectUtils.isEmpty(order) && !ObjectUtils.isEmpty(orderType)) { //排序顺序条件构造
            if (orderType.equals(Constants.ORDER_ASC))
                wrapper.orderByAsc(ConvertUtils.toLine(order));
            else
                wrapper.orderByDesc(ConvertUtils.toLine(order));
        }
 
        if (!ObjectUtils.isEmpty(isDelete))//逻辑删除条件构造
            wrapper.eq("is_delete", isDelete);
        else
            wrapper.eq("is_delete", Constants.NOT_DELETE);
 
        //查询结果
        Page resultPage = manageAccountMapper.selectPage(queryPage, wrapper);
 
        //查询用户对应的角色
        List<ManageAccount> accounts = resultPage.getRecords();
        List<AccountDTO> accountDTOS = new ArrayList<>();
        for (ManageAccount manageAccount : accounts) {
            AccountDTO accountDTO = new AccountDTO();
            List<ManageRole> roles = manageRoleMapper.getManageRoleByAccountId(manageAccount.getId());
            accountDTO.setRoles(roles);
            accountDTO.setAccount(manageAccount);
            accountDTOS.add(accountDTO);
        }
 
 
        //封装返回结果
        accountQueryDTO.setAccountDTOS(accountDTOS);
        accountQueryDTO.setCurrent(resultPage.getCurrent());
        accountQueryDTO.setPages(resultPage.getPages());
        accountQueryDTO.setSize(resultPage.getSize());
        accountQueryDTO.setTotal(resultPage.getTotal());
        accountQueryDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        accountQueryDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
 
        return accountQueryDTO;
    }
 
    /**
     * @Description: 删除后台账号
     * @Param: [accountDeleteRequest]
     * @return: com.moral.api.pojo.dto.account.AccountDeleteDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/16
     */
    @Override
    @Transactional
    public AccountDTO deleteAccount(AccountDeleteForm accountDeleteForm) {
        AccountDTO accountDTO = new AccountDTO();
        //取参
        Integer accountId = accountDeleteForm.getAccountId();
        //查询要删除的账号,用于插入日志
        ManageAccount manageAccount = new ManageAccount();
        manageAccount.setIsDelete(Constants.NOT_DELETE);
        manageAccount.setId(accountId);
        QueryWrapper<ManageAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(manageAccount);
        ManageAccount existManageAccount = manageAccountMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(existManageAccount)) {
            accountDTO.setCode(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getCode());
            accountDTO.setMsg(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return accountDTO;
        }
        //逻辑删除账号
        UpdateWrapper<ManageAccount> deleteAccountWrapper = new UpdateWrapper<>();
        deleteAccountWrapper.eq("id", accountId);
        deleteAccountWrapper.set("is_delete", Constants.DELETE);
        manageAccountMapper.update(null, deleteAccountWrapper);
        //逻辑删除账号相关角色
        UpdateWrapper<ManageAccountRole> deleteManageAccountRoleWrapper = new UpdateWrapper<>();
        deleteManageAccountRoleWrapper.set("is_delete", Constants.DELETE).eq("account_id", manageAccount.getId());
        manageAccountRoleMapper.update(null, deleteManageAccountRoleWrapper);
        //销毁token
        TokenUtils.destoryToken(accountId);
        //封装返回结果
        accountDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        accountDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        //操作插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("删除了用户:").append(existManageAccount.getUserName() + ";")
                .append("账号:" + existManageAccount.getAccount() + ";");
        logUtils.saveOperationForManage(request, content.toString(), Constants.DELETE_OPERATE_TYPE);
 
        return accountDTO;
    }
 
    /**
     * @Description: 更新后台账号
     * @Param: [accountUpdateRequest]
     * @return: com.moral.api.pojo.dto.account.AccountUpdateDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/16
     */
    @Override
    @Transactional
    public AccountDTO updateAccount(AccountUpdateForm accountUpdateForm) {
        AccountDTO accountDTO = new AccountDTO();
        //取参
        ManageAccount manageAccount = accountUpdateForm.formConvertEntity();
        List<Integer> roleIds = accountUpdateForm.getRoleIds();
 
        //查找要更新的用户用于插入日志
        QueryWrapper<ManageAccount> oldAccountWrapper = new QueryWrapper<>();
        ManageAccount oldManageAccount = new ManageAccount();
        oldManageAccount.setId(manageAccount.getId());
        oldManageAccount.setIsDelete(Constants.NOT_DELETE);
        oldAccountWrapper.setEntity(oldManageAccount);
        oldManageAccount = manageAccountMapper.selectOne(oldAccountWrapper);
        if (ObjectUtils.isEmpty(oldManageAccount)) {
            accountDTO.setCode(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getCode());
            accountDTO.setMsg(ResponseCodeEnum.ACCOUNT_NOT_EXIST.getMsg());
            return accountDTO;
        }
 
        //更新ManageAccount表
        Map manageAccountMap = JSONObject.parseObject(JSON.toJSONString(manageAccount), Map.class);//转换为Map判断属性是否有更新
        if (manageAccountMap.size() > 1) {//判断如果没有除了id以外的任何属性则不更新
            manageAccountMapper.updateById(manageAccount);
        }
 
        //获取账号更新前的角色
        List<ManageRole> oldRoles = manageRoleMapper.getManageRoleByAccountId(manageAccount.getId());
 
        //如果角色有变动,则更新ManageAccountRole表
        /*
         * 如果roleIds为null,则是该账号角色没有发生改变
         * 如果roleIds为空,则是该账号所有的角色都被移除
         * 如果roleIds有元素,则是该账号的角色有更新
         * */
        if (roleIds != null) {
            //删除原有角色
            UpdateWrapper<ManageAccountRole> deleteWrapper = new UpdateWrapper<>();
            deleteWrapper.eq("account_id", manageAccount.getId()).set("is_delete", Constants.DELETE);
            manageAccountRoleMapper.update(null, deleteWrapper);
            /*重新添加角色*/
            for (Integer roleId : roleIds) {
                ManageAccountRole manageAccountRole = new ManageAccountRole();
                manageAccountRole.setAccountId(manageAccount.getId());
                manageAccountRole.setRoleId(roleId);
                manageAccountRoleMapper.insert(manageAccountRole);
            }
        }
        //销毁token
        TokenUtils.destoryToken(manageAccount.getId());
        //封装返回结果
        accountDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        accountDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        //操作插入日志
        insertUpdateLog(accountUpdateForm, oldManageAccount, oldRoles);
        return accountDTO;
    }
 
    /**
     * @Description: 将更新操作插入日志
     * @Param: [form, newAccount, oldAccount]
     * @return: void
     * @Author: 陈凯裕
     * @Date: 2021/4/8
     */
    private void insertUpdateLog(AccountUpdateForm updateForm, ManageAccount oldAccount, List<ManageRole> oldRoles) {
        //操作插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("修改了用户:").append(oldAccount.getUserName() + ";")
                .append("账号:" + oldAccount.getAccount() + ";");
        //对象转为Map,获取对象更新前后的属性
        Map<String, Object> newParameters = JSONObject.parseObject(JSON.toJSONString(updateForm), Map.class);
        Map<String, Object> oldParameters = JSONObject.parseObject(JSON.toJSONString(oldAccount), Map.class);
        //遍历配置文件中的Map,将属性转化为汉字
        Set<String> keys = manageAccountFormMap.keySet();
        for (String key : keys) {
            String value = manageAccountFormMap.get(key);//属性对应的汉字
            if ("password".equals(key)) {//密码特殊处理,不显示在日志上
                if (!ObjectUtils.isEmpty(updateForm.getPassword())) {//判断密码是否进行了更新
                    content.append("修改了密码;");
                }
            } else if ("roleIds".equals(key)) {//角色特殊处理,将Id转化为角色名称
                List<Integer> newRoleIds = updateForm.getRoleIds();
 
                if (newRoleIds != null && 0 == newRoleIds.size()) {//如果新的角色集合为空,则是删除了所有的角色
                    content.append("角色:删除了所有角色;");
                }
                if ((newRoleIds != null) && (newRoleIds.size() != 0)) {//如果新的角色集合不为空,且不为null,则角色进行了更新
                    StringBuilder oldRolesName = new StringBuilder("空");
                    StringBuilder newRolesName = new StringBuilder("空");
 
                    List<ManageRole> newRoles = null;
                    if (!ObjectUtils.isEmpty(updateForm.getRoleIds())) {
                        newRoles = manageRoleMapper.selectBatchIds(updateForm.getRoleIds());
                    }
 
                    if (!ObjectUtils.isEmpty(oldRoles)) {
                        oldRolesName.deleteCharAt(oldRolesName.length() - 1);//删除 "空"
                        oldRolesName.append("[");
                        for (ManageRole role : oldRoles) {
                            oldRolesName.append(role.getName() + ",");
                        }
                        oldRolesName.deleteCharAt(oldRolesName.length() - 1);//移除最后一个逗号
                        oldRolesName.append("]");
                    }
 
                    if (!ObjectUtils.isEmpty(newRoles)) {
                        newRolesName.deleteCharAt(newRolesName.length() - 1);//删除 "空"
                        newRolesName.append("[");
                        for (ManageRole role : newRoles) {
                            newRolesName.append(role.getName() + ",");
                        }
                        newRolesName.deleteCharAt(newRolesName.length() - 1);//移除最后一个逗号
                        newRolesName.append("]");
                    }
                    //拼接完整content
                    content.append(value + ":" + oldRolesName + "->" + newRolesName + ";");
                }
            } else {//其他属性处理
                if (newParameters.get(key) != null) {
                    String newValue = "空";
                    String oldValue = "空";
                    if (newParameters.get(key) != null && !newParameters.get(key).equals(" ")) {
                        newValue = String.valueOf(newParameters.get(key));
                    }
                    if (oldParameters.get(key) != null && !oldParameters.get(key).equals(" ")) {
                        oldValue = String.valueOf(oldParameters.get(key));
                    }
                    content.append(value + ":" + oldValue + "->" + newValue + ";");
                }
            }
        }
        logUtils.saveOperationForManage(request, content.toString(), Constants.UPDATE_OPERATE_TYPE);
    }
 
 
}