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
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.config.mybatis.wrapper.NullFilterWrapper;
import com.moral.api.entity.MonitorPoint;
import com.moral.api.entity.Organization;
import com.moral.api.entity.User;
import com.moral.api.mapper.MonitorPointMapper;
import com.moral.api.mapper.OrganizationMapper;
import com.moral.api.mapper.UserMapper;
import com.moral.api.pojo.dto.organization.OrganizationDTO;
import com.moral.api.pojo.dto.organization.OrganizationQueryDTO;
import com.moral.api.pojo.dto.organization.OrganizationQueryNamesDTO;
import com.moral.api.pojo.form.organization.*;
import com.moral.api.service.MonitorPointService;
import com.moral.api.service.OrganizationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.api.service.UserService;
import com.moral.api.util.LogUtils;
import com.moral.constant.Constants;
import com.moral.constant.ResponseCodeEnum;
import com.moral.util.ConvertUtils;
import com.moral.util.DateUtils;
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.*;
import java.util.function.Predicate;
 
/**
 * <p>
 * 组织表 服务实现类
 * </p>
 *
 * @author moral
 * @since 2021-04-06
 */
@Service
@ConfigurationProperties(prefix = "log-aspect")
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {
 
    @Autowired
    OrganizationMapper organizationMapper;
 
    @Autowired
    LogUtils logUtils;
 
    @Autowired
    UserService userService;
 
    @Autowired
    UserMapper userMapper;
 
    @Autowired
    MonitorPointService monitorPointService;
 
    Map<String, String> organizationFormMap;
 
    public void setOrganizationFormMap(Map<String, String> organizationFormMap) {
        this.organizationFormMap = organizationFormMap;
    }
 
    /**
     * @Description: 添加客户组织
     * @Param: [organizationInsertForm]
     * @return: void
     * @Author: 陈凯裕
     * @Date: 2021/3/22
     */
 
 
    @Override
    @Transactional
    public OrganizationDTO insertOrganization(OrganizationInsertForm organizationInsertForm) {
        OrganizationDTO organizationDTO = new OrganizationDTO();
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        //form转换entity
        Organization organization = organizationInsertForm.formConvertEntity();
        //查询组织名称是否已经存在
        Organization existOrganization = new Organization();
        existOrganization.setName(organization.getName());
        existOrganization.setIsDelete(Constants.NOT_DELETE);
        queryWrapper.setEntity(existOrganization);
        Organization existOrganizationResult = organizationMapper.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(existOrganizationResult)) {
            organizationDTO.setCode(ResponseCodeEnum.ORGANIZATION_EXIST.getCode());
            organizationDTO.setMsg(ResponseCodeEnum.ORGANIZATION_EXIST.getMsg());
            return organizationDTO;
        }
        //插入组织
        organizationMapper.insert(organization);
 
        //封装DTO信息
        organizationDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        organizationDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
 
        //操作插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("添加了组织:").append(organization.getName() + ";");
        logUtils.saveOperationForManage(request, content.toString(), Constants.INSERT_OPERATE_TYPE);
        return organizationDTO;
    }
 
    /**
     * @Description: 更新客户组织
     * @Param: [organizationUpdateForm]
     * @return: com.moral.api.pojo.dto.organization.OrganizationDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/24
     */
    @Override
    @Transactional
    public OrganizationDTO updateOrganization(OrganizationUpdateForm organizationUpdateForm) {
        OrganizationDTO organizationDTO = new OrganizationDTO();
        //form转entity
        Organization organization = organizationUpdateForm.formConvertEntity();
 
        //查找要更新的组织用于插入日志
        QueryWrapper<Organization> oldWrapper = new QueryWrapper<>();
        Organization oldOrganization = new Organization();
        oldOrganization.setId(organization.getId());
        oldOrganization.setIsDelete(Constants.NOT_DELETE);
        oldWrapper.setEntity(oldOrganization);
        oldOrganization = organizationMapper.selectOne(oldWrapper);
        if (ObjectUtils.isEmpty(oldOrganization)) {
            organizationDTO.setCode(ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getCode());
            organizationDTO.setMsg(ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getMsg());
            return organizationDTO;
        }
 
 
        //更新组织
        organizationMapper.updateById(organization);
 
        //获取更新后的组织
        organization = organizationMapper.selectById(organization.getId());
 
        //封装DTO信息
        organizationDTO.setCode(ResponseCodeEnum.SUCCESS.getCode());
        organizationDTO.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
 
        //操作插入日志
        insertUpdateLog(organizationUpdateForm, organization, oldOrganization);
 
        return organizationDTO;
    }
 
 
 
    /**
     * @Description: 删除客户组织
     * @Param: [organizationDeleteForm]
     * @return: com.moral.api.pojo.dto.organization.OrganizationDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/25
     */
    @Override
    @Transactional
    public OrganizationDTO deleteOrganization(OrganizationDeleteForm form) {
        OrganizationDTO dto = new OrganizationDTO();
        //取参
        Integer id = form.getOrganizationId();
 
        //判断组织是否含有站点
        List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsByOrganizationId(id);
        if(!ObjectUtils.isEmpty(monitorPoints)){
            dto.setCode(ResponseCodeEnum.ORGANIZATION_EXIST_MONITORPOINT.getCode());
            dto.setMsg(ResponseCodeEnum.ORGANIZATION_EXIST_MONITORPOINT.getMsg());
            return dto;
        }
 
        //查询要删除的组织用于插入日志
        Organization existOrganization = new Organization();
        existOrganization.setIsDelete(Constants.NOT_DELETE);
        existOrganization.setId(id);
        QueryWrapper queryExistWrapper = new QueryWrapper();
        queryExistWrapper.setEntity(existOrganization);
        existOrganization = organizationMapper.selectOne(queryExistWrapper);
        if (ObjectUtils.isEmpty(existOrganization)) {
            dto.setCode(ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getCode());
            dto.setMsg(ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getMsg());
            return dto;
        }
 
        //判断是否含有子组织
        List<Organization> children = getAllChildrenOrganization(existOrganization.getId());
        if (!ObjectUtils.isEmpty(children)) {
            //判断是否删除所有子组织,如果不删除子组织则所有子组织全部变为无父组织,孙子组织不变
            UpdateWrapper updateWrapper = new UpdateWrapper();
            if (form.getDeleteChildren().equals(Constants.DELETE_CHILDREN_ORG)) {//删除所有子组织
                //获取所有子组织的id封装为集合
                List<Integer> childrenId = new ArrayList<>();
                children.forEach(value -> {
                    childrenId.add(value.getId());
                });
                //判断子组织是否含有站点,有一个子组织含有站点则不能删除
                for (Integer childId : childrenId) {
                    List<MonitorPoint> childMonitorPoints = monitorPointService.getMonitorPointsByOrganizationId(childId);
                    if(!ObjectUtils.isEmpty(childMonitorPoints)){
                        dto.setCode(ResponseCodeEnum.CHILDREN_ORGANIZATION_EXIST_MONITORPOINT.getCode());
                        dto.setMsg(ResponseCodeEnum.CHILDREN_ORGANIZATION_EXIST_MONITORPOINT.getMsg());
                        return dto;
                    }
                }
                //进行删除
                updateWrapper.in("id", childrenId);
                updateWrapper.set("is_delete", Constants.DELETE);
                organizationMapper.update(null, updateWrapper);
                //删除所有子组织账号
                childrenId.forEach(value->userService.deleteUsersByOrganizationId(value));
 
            } else {//不删除
                //提取所有直属子组织id
                List<Integer> childrenId = new ArrayList<>();
                children.forEach(value -> {
                    if (value.getParentId().equals(id))
                        childrenId.add(value.getId());
                });
                //进行更新
                updateWrapper.in("id", childrenId);
                updateWrapper.set("parent_id", 0);
                organizationMapper.update(null, updateWrapper);
            }
        }
 
        //逻辑删除组织
        UpdateWrapper deleteWrapper = new UpdateWrapper();
        deleteWrapper.eq("id", id);
        deleteWrapper.set("is_delete", Constants.DELETE);
        organizationMapper.update(null, deleteWrapper);
 
        //删除组织账号
        userService.deleteUsersByOrganizationId(id);
 
        //封装返回结果
        dto.setCode(ResponseCodeEnum.SUCCESS.getCode());
        dto.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        //操作插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("删除了组织:").append(existOrganization.getName());
        if (form.getDeleteChildren().equals(Constants.DELETE_CHILDREN_ORG))
            content.append("以及所有子组织;");
        else
            content.append(";");
        logUtils.saveOperationForManage(request, content.toString(), Constants.DELETE_OPERATE_TYPE);
 
        return dto;
    }
 
    /**
     * @Description: 查询客户组织
     * @Param: [organizationQueryForm]
     * @return: com.moral.api.pojo.dto.organization.OrganizationQueryDTO
     * @Author: 陈凯裕
     * @Date: 2021/3/25
     */
    @Override
    public OrganizationQueryDTO queryOrganization(OrganizationQueryForm organizationQueryForm) {
        OrganizationQueryDTO dto = new OrganizationQueryDTO();
        //取参
        Integer pageCount = organizationQueryForm.getPage();
        Integer size = organizationQueryForm.getSize();
        Integer parentId = organizationQueryForm.getParentId();
        String name = organizationQueryForm.getName();
        Integer provinceCode = organizationQueryForm.getProvinceCode();
        Integer cityCode = organizationQueryForm.getCityCode();
        Integer areaCode = organizationQueryForm.getAreaCode();
        String phone = organizationQueryForm.getPhone();
        String email = organizationQueryForm.getEmail();
        String wechat = organizationQueryForm.getWechat();
        String isDelete = organizationQueryForm.getIsDelete();
        String order = organizationQueryForm.getOrder();
        String orderType = organizationQueryForm.getOrderType();
        Date createStartTime = organizationQueryForm.getCreateStartTime();
        Date createEndTime = DateUtils.getDateOfDay(organizationQueryForm.getCreateEndTime(), 1);
        Date expireStartTime = organizationQueryForm.getExpireStartTime();
        Date expireEndTime = DateUtils.getDateOfDay(organizationQueryForm.getExpireEndTime(), 1);
 
        //查询条件
        Page<Organization> page = new Page<>(pageCount, size);
        NullFilterWrapper<Organization> queryWrapper = new NullFilterWrapper<>();
 
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.like("name", name);
        queryWrapper.eq("province_code", provinceCode);
        queryWrapper.eq("city_code", cityCode);
        queryWrapper.eq("area_code", areaCode);
        queryWrapper.like("phone", phone);
        queryWrapper.like("email", email);
        queryWrapper.like("wechat", wechat);
        queryWrapper.between("create_time", createStartTime, createEndTime);
        queryWrapper.between("expire_time", expireStartTime, expireEndTime);
 
        if (!ObjectUtils.isEmpty(isDelete)) {
            queryWrapper.eq("is_delete", isDelete);
        } else {
            queryWrapper.eq("is_delete", Constants.NOT_DELETE);
        }
 
        //排序顺序
        if (!ObjectUtils.isEmpty(order)) {
            if (!ObjectUtils.isEmpty(orderType)) {
                if (orderType.equals(Constants.ORDER_ASC))
                    queryWrapper.orderByAsc(ConvertUtils.toLine(order));
                else
                    queryWrapper.orderByDesc(ConvertUtils.toLine(order));
            }
        }
 
        //查询结果
        Page<Organization> resultPage = organizationMapper.selectPage(page, queryWrapper);
        List<Organization> organizations = resultPage.getRecords();
        List<OrganizationDTO> organizationDTOS = new ArrayList<>();
        //查找所有组织的父组织和admin账号并且封装organization到DTO中
        for (Organization organization : organizations) {
            OrganizationDTO resultDto = new OrganizationDTO();
            //查找父组织
            Organization parent = organizationMapper.selectById(organization.getParentId());
            resultDto.setOrganization(organization);
            resultDto.setParentOrganization(parent);
            //查找admin账号
            QueryWrapper userWrapper = new QueryWrapper();
            User adminUser = new User();
            adminUser.setIsAdmin(true);
            adminUser.setOrganizationId(organization.getId());
            adminUser.setIsDelete(Constants.NOT_DELETE);
            userWrapper.setEntity(adminUser);
            adminUser = userMapper.selectOne(userWrapper);
            resultDto.setAdminUser(adminUser);
            organizationDTOS.add(resultDto);
        }
 
        dto.setCode(ResponseCodeEnum.SUCCESS.getCode());
        dto.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        dto.setOrganizationDTOS(organizationDTOS);
        dto.setCurrent(page.getCurrent());
        dto.setPages(page.getPages());
        dto.setSize(page.getSize());
        dto.setTotal(page.getTotal());
        return dto;
    }
 
    /**
    * @Description: 如果form中id为空,则查询所有的组织
     *              如果id不为空,则查询该id和该id所有子组织之外的所有组织
            * @Param: [from]
            * @return: com.moral.api.pojo.dto.organization.OrganizationQueryNamesDTO
            * @Author: 陈凯裕
            * @Date: 2021/5/7
            */
    @Override
    public OrganizationQueryNamesDTO queryNames(OrganizationQueryNamesForm form) {
        OrganizationQueryNamesDTO dto = new OrganizationQueryNamesDTO();
        //取参
        Integer id = form.getId();
        //构造查询条件
        QueryWrapper<Organization> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", Constants.NOT_DELETE);
        //查询所有组织
        List<Organization> organizations = organizationMapper.selectList(queryWrapper);
        //判断form是否含有id,如果有则对其所有子组织进行过滤
        if(!ObjectUtils.isEmpty(id)){
            List<Organization> children = getAllChildrenOrganization(id);
            List<Integer> thisAndchildrenIds = new ArrayList<>();//该id以及其所有子组织的id集合
            thisAndchildrenIds.add(id);
            for (Organization child : children) {
                thisAndchildrenIds.add(child.getId());
            }
            organizations.removeIf(new Predicate<Organization>() {//过滤
                @Override
                public boolean test(Organization organization) {
                    if(thisAndchildrenIds.contains(organization.getId()))
                        return true;
                    return false;
                }
            });
        }
        //封装返回对象
        dto.setCode(ResponseCodeEnum.SUCCESS.getCode());
        dto.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        dto.setOrganizations(organizations);
        return dto;
    }
 
 
    /**
     * @Description: 将更新操作插入日志
     * @Param: [updateForm, newOrganization, oldOrganization]
     * @return: void
     * @Author: 陈凯裕
     * @Date: 2021/4/8
     */
    private void insertUpdateLog(OrganizationUpdateForm updateForm, Organization newOrganization, Organization oldOrganization) {
        //操作插入日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        StringBuilder content = new StringBuilder();
        content.append("修改了组织:").append(oldOrganization.getName()).append(";");
        //对象转为Map,获取对象更新前后的属性
        Map<String, Object> newParameters = JSONObject.parseObject(JSON.toJSONString(updateForm), Map.class);
        Map<String, Object> oldParameters = JSONObject.parseObject(JSON.toJSONString(oldOrganization), Map.class);
        //遍历配置文件中的Map,将属性转化为汉字
        Set<String> keys = organizationFormMap.keySet();
        for (String key : keys) {
            String value = organizationFormMap.get(key);//属性对应的汉字
            if ("parentName".equals(key)) {//更新父组织特殊处理
                if (updateForm.getParentId() != null) {//判断父组织是否进行了更新
                    String oldParentName = "空";
                    String newParentName = "空";
                    if (!oldOrganization.getParentId().equals(0)) {
                        oldParentName = organizationMapper.selectById(oldOrganization.getParentId()).getName();
                    }
                    if (!newOrganization.getParentId().equals(0)) {
                        newParentName = organizationMapper.selectById(newOrganization.getParentId()).getName();
                    }
                    content.append(value + ":" + oldParentName + "->" + newParentName + ";");
                }
            } else if ("expireTime".equals(key)) {//expireTime时间格式特殊处理
                if (updateForm.getExpireTime() != null) {
                    Date oldExpireTime = oldOrganization.getExpireTime();
                    Date newExpireTime = newOrganization.getExpireTime();
                    String oldExpireTimeStr = DateUtils.dateToDateString(oldExpireTime, "yyyy-MM-dd");
                    String newExpireTimeStr = DateUtils.dateToDateString(newExpireTime, "yyyy-MM-dd");
                    content.append(value + ":" + oldExpireTimeStr + "->" + newExpireTimeStr + ";");
                }
            } 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);
    }
 
    /**
     * @Description: 根据父组织获取所有子组织
     * @Param: []
     * @return: java.util.List<com.moral.api.entity.Organization>
     * @Author: 陈凯裕
     * @Date: 2021/4/14
     */
    private List<Organization> getAllChildrenOrganization(Integer parentId) {
        List<Organization> children = new ArrayList<>();
        recursionQueryChildren(parentId, children);
        return children;
    }
 
    /**
     * @Description: 通过父组织查询下面所有的子组织放到children中
     * @Param: [parent, children]
     * @return: void
     * @Author: 陈凯裕
     * @Date: 2021/4/14
     */
    private void recursionQueryChildren(Integer parentId, List<Organization> children) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", Constants.NOT_DELETE);
        queryWrapper.eq("parent_id", parentId);
        List<Organization> organizations = organizationMapper.selectList(queryWrapper);
        if (!ObjectUtils.isEmpty(organizations)) {
            children.addAll(organizations);
            for (Organization organization : organizations) {
                recursionQueryChildren(organization.getId(), children);
            }
        } else {
            return;
        }
    }
 
 
}