“djh”
2024-12-04 d1549b8445c65a6775cf1ba093f5040ace0f87e7
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
package com.gkhy.huataiFourierSpecialGasMonitor.service.impl;
 
import com.gkhy.huataiFourierSpecialGasMonitor.commons.domain.Result;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.domain.SearchResult;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.enums.ResultCode;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.exception.BusinessException;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.model.PageQuery;
import com.gkhy.huataiFourierSpecialGasMonitor.domain.account.entity.User;
import com.gkhy.huataiFourierSpecialGasMonitor.domain.account.enums.UserStatusEnum;
import com.gkhy.huataiFourierSpecialGasMonitor.domain.account.repository.jpa.UserRepository;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.Region;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.RegionLngLat;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.query.FindRegionPageQuery;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.req.*;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.resp.FindRegionByIdLngLatRespDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.resp.FindRegionByIdRespDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.resp.FindRegionLngLatPageRespDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.resp.FindRegionPageRespDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.enums.DeleteStatusEnum;
import com.gkhy.huataiFourierSpecialGasMonitor.repository.RegionLngLatRepository;
import com.gkhy.huataiFourierSpecialGasMonitor.repository.RegionRepository;
import com.gkhy.huataiFourierSpecialGasMonitor.service.RegionService;
import com.gkhy.huataiFourierSpecialGasMonitor.utils.ThreadLocalUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
 
import javax.persistence.criteria.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
 
/**
 * @author Mr.huang
 * @decription
 * @date 2023/8/9 10:46
 */
@Service
public class RegionServiceImpl implements RegionService {
 
    @Autowired
    private UserRepository userRepository;
 
    @Autowired
    private RegionRepository regionRepository;
 
    @Autowired
    private RegionLngLatRepository regionLngLatRepository;
 
    private static final ReentrantLock regionNamelock = new ReentrantLock();
 
    private User getCurrentUser(){
        Long userId = ThreadLocalUtil.get().getId();
        User user = userRepository.findUserByIdAndStatus(userId, UserStatusEnum.STATUS_ACTIVE.getStatus());
        if (user == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"未成功获取用户信息");
        return user;
    }
 
    @Override
    public Result createRegion(CreateRegionReqDTO reqDto) {
        User currentUser = getCurrentUser();
        if (reqDto == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        if (StringUtils.isBlank(reqDto.getName()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"区域名称为空");
        if (StringUtils.isBlank(reqDto.getColor()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"区域颜色不能为空");
        if (CollectionUtils.isEmpty(reqDto.getRegionLngLats()) || reqDto.getRegionLngLats().size() < 3)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"经纬度数据不能为空或个数少于3");
        regionNamelock.lock();
        try {
            Region regionold = findByNameAndStatus(reqDto.getName());
            if (regionold != null)
                throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"区域名称已存在");
            Region region = new Region();
            BeanUtils.copyProperties(reqDto,region);
            region.setCreatedby(currentUser.getRealName());
            region.setLastmodifiedby(currentUser.getRealName());
            region.setStatus(DeleteStatusEnum.DELECT_NO.getStatus());
            region.setGmtCreate(LocalDateTime.now());
            region.setGmtModified(LocalDateTime.now());
            Region save = regionRepository.save(region);
            if (save == null)
                throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(),"区域保存失败");
            List<CreateRegionLngLatReqDTO> regionLngLats = reqDto.getRegionLngLats();
            List<RegionLngLat> collect = regionLngLats.stream().map(regionLngLat -> {
                RegionLngLat lngLat = new RegionLngLat();
                BeanUtils.copyProperties(regionLngLat, lngLat);
                lngLat.setRegionId(save.getId());
                return lngLat;
            }).collect(Collectors.toList());
            List<RegionLngLat> lats = regionLngLatRepository.saveAll(collect);
            if (CollectionUtils.isEmpty(lats))
                throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(),"区域相关经纬度保存失败");
        }finally {
            regionNamelock.unlock();
        }
 
        return Result.success();
    }
 
    @Override
    public Result delRegionById(DelRegionByIdReqDTO reqDto) {
        User currentUser = getCurrentUser();
        if (reqDto == null || reqDto.getId() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        Region region = regionRepository.findByIdAndStatus(reqDto.getId(), DeleteStatusEnum.DELECT_NO.getStatus());
        if (region == null){
            return Result.success();
        }
        region.setStatus(DeleteStatusEnum.DELECT_YES.getStatus());
        region.setLastmodifiedby(currentUser.getRealName());
        region.setGmtModified(LocalDateTime.now());
        Region save = regionRepository.save(region);
        if (save == null)
            throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(),"区域删除失败");
        return Result.success();
    }
 
    @Override
    public Result findRegionById(Integer id) {
        Result success = Result.success();
        if (id == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        Region region = regionRepository.findByIdAndStatus(id, DeleteStatusEnum.DELECT_NO.getStatus());
        if (region != null){
            FindRegionByIdRespDTO findRegionByIdRespDTO = new FindRegionByIdRespDTO();
            BeanUtils.copyProperties(region,findRegionByIdRespDTO);
            List<RegionLngLat> regionLngLats = region.getRegionLngLats();
            if (!CollectionUtils.isEmpty(regionLngLats)){
                List<FindRegionByIdLngLatRespDTO> collect = regionLngLats.stream().map(regionLngLat -> {
                    FindRegionByIdLngLatRespDTO findRegionByIdLngLatRespDTO = new FindRegionByIdLngLatRespDTO();
                    BeanUtils.copyProperties(regionLngLat, findRegionByIdLngLatRespDTO);
                    return findRegionByIdLngLatRespDTO;
                }).collect(Collectors.toList());
                findRegionByIdRespDTO.setLngLatRespDTOS(collect);
            }
            success.setData(findRegionByIdRespDTO);
        }
        return success;
    }
 
    @Override
    public Result findRegionPage(PageQuery<FindRegionPageQuery> pageQuery) {
        if (pageQuery == null || pageQuery.getPageIndex() == null || pageQuery.getPageSize() == null){
            throw new BusinessException(this.getClass(),ResultCode.PARAM_ERROR_NULL,"分页参数不能为空");
        }
        Pageable pageable = PageRequest.of(pageQuery.getPageIndex()-1, pageQuery.getPageSize());
        Specification<Region> specification = new Specification<Region>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Set<Predicate> predicateList = new HashSet<>();
                FindRegionPageQuery searchParams = pageQuery.getSearchParams();
                if (searchParams != null && !StringUtils.isBlank(searchParams.getName())){
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class),"%"+searchParams.getName()+"%"));
                }
                predicateList.add(criteriaBuilder.equal(root.get("status").as(Byte.class), DeleteStatusEnum.DELECT_NO.getStatus()));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        SearchResult<List<FindRegionPageRespDTO>> searchResult = new SearchResult<>();
        searchResult.setPageIndex(pageQuery.getPageIndex());
        searchResult.setPageSize(pageQuery.getPageSize());
        searchResult.setSuccess();
        Page<Region> pageResult = regionRepository.findAll(specification,pageable);
        searchResult.setTotal(pageResult.getTotalElements());
        searchResult.setPages(pageResult.getTotalPages());
        if (!CollectionUtils.isEmpty(pageResult.getContent())){
            List<FindRegionPageRespDTO> dtos = pageResult.getContent().stream().map(region -> {
                FindRegionPageRespDTO dto = new FindRegionPageRespDTO();
                BeanUtils.copyProperties(region, dto);
                if (!CollectionUtils.isEmpty(region.getRegionLngLats())) {
                    List<FindRegionLngLatPageRespDTO> collect = region.getRegionLngLats().stream().map(regionLngLat -> {
                        FindRegionLngLatPageRespDTO findRegionLngLatPageRespDTO = new FindRegionLngLatPageRespDTO();
                        BeanUtils.copyProperties(regionLngLat, findRegionLngLatPageRespDTO);
                        return findRegionLngLatPageRespDTO;
                    }).collect(Collectors.toList());
                    dto.setRegionLngLats(collect);
                }
                return dto;
            }).collect(Collectors.toList());
            searchResult.setData(dtos);
        }
        return searchResult;
    }
 
    @Override
    @Transactional
    public Result updateRegion(UpdateRegionReqDTO reqDto) {
        User currentUser = getCurrentUser();
        if (reqDto == null || reqDto.getId() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        Region region = regionRepository.findByIdAndStatus(reqDto.getId(), DeleteStatusEnum.DELECT_NO.getStatus());
        if (region == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"区域不存在");
        if (StringUtils.isBlank(reqDto.getName()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"区域名称为空");
        if (StringUtils.isBlank(reqDto.getColor()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"区域颜色不能为空");
        if (CollectionUtils.isEmpty(reqDto.getRegionLngLats()) || reqDto.getRegionLngLats().size() < 3)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"经纬度数据不能为空或个数少于3");
        regionNamelock.lock();
        try {
            Region regionold = findByNameAndStatus(reqDto.getName());
            if (regionold != null && !regionold.getId().equals(reqDto.getId()))
                throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(), "区域名称已存在");
            region.setName(reqDto.getName());
            region.setColor(reqDto.getColor());
            region.setLastmodifiedby(currentUser.getRealName());
            region.setGmtModified(LocalDateTime.now());
            if (regionRepository.save(region) == null)
                throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(),"区域保存失败");
            regionLngLatRepository.deleteAllByRegionId(reqDto.getId());
            List<UpdateRegionLngLatReqDTO> regionLngLats = reqDto.getRegionLngLats();
            List<RegionLngLat> collect = regionLngLats.stream().map(regionLngLat -> {
                RegionLngLat lngLat = new RegionLngLat();
                BeanUtils.copyProperties(regionLngLat, lngLat);
                lngLat.setRegionId(reqDto.getId());
                return lngLat;
            }).collect(Collectors.toList());
            List<RegionLngLat> lats = regionLngLatRepository.saveAll(collect);
            if (CollectionUtils.isEmpty(lats))
                throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(), "区域相关经纬度保存失败");
        }finally {
            regionNamelock.unlock();
        }
        return Result.success();
    }
 
    @Override
    public List<Region> findAll() {
        List<Region> regions = regionRepository.findAllByStatus(DeleteStatusEnum.DELECT_NO.getStatus());
        return regions;
    }
 
    private Region findByNameAndStatus(String name){
        return regionRepository.findByNameAndStatus(name, DeleteStatusEnum.DELECT_NO.getStatus());
    }
}