16639036659
2024-04-10 b15ad90d858e5b6745f76921054b5d5a62b59627
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
package com.gkhy.fourierSpecialGasMonitor.service.impl;
 
import com.gkhy.fourierSpecialGasMonitor.commons.domain.Result;
import com.gkhy.fourierSpecialGasMonitor.commons.domain.SearchResult;
import com.gkhy.fourierSpecialGasMonitor.commons.enums.ResultCode;
import com.gkhy.fourierSpecialGasMonitor.commons.enums.SystemCacheKeyEnum;
import com.gkhy.fourierSpecialGasMonitor.commons.exception.BusinessException;
import com.gkhy.fourierSpecialGasMonitor.commons.model.PageQuery;
import com.gkhy.fourierSpecialGasMonitor.domain.account.entity.User;
import com.gkhy.fourierSpecialGasMonitor.domain.account.enums.UserStatusEnum;
import com.gkhy.fourierSpecialGasMonitor.domain.account.repository.jpa.UserRepository;
import com.gkhy.fourierSpecialGasMonitor.entity.GasCategory;
import com.gkhy.fourierSpecialGasMonitor.entity.Region;
import com.gkhy.fourierSpecialGasMonitor.entity.query.FindGasCategoryPageQuery;
import com.gkhy.fourierSpecialGasMonitor.entity.query.FindRegionPageQuery;
import com.gkhy.fourierSpecialGasMonitor.entity.req.CreateGasCategoryReqDTO;
import com.gkhy.fourierSpecialGasMonitor.entity.req.UpdateGasCategoryReqDTO;
import com.gkhy.fourierSpecialGasMonitor.entity.resp.*;
import com.gkhy.fourierSpecialGasMonitor.enums.DeleteStatusEnum;
import com.gkhy.fourierSpecialGasMonitor.repository.GasCategoryRepository;
import com.gkhy.fourierSpecialGasMonitor.service.GasCategoryService;
import com.gkhy.fourierSpecialGasMonitor.utils.ThreadLocalUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
 
@Service
public class GasCategoryServiceImpl implements GasCategoryService {
 
    @Autowired
    private UserRepository userRepository;
 
    @Autowired
    private RedissonClient redissonClient;
 
    @Autowired
    private GasCategoryRepository gasCategoryRepository;
 
    private static ReentrantLock gasCategoryMolecularFormulaRepeatlock = 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 synchronized Result createGasCategory(CreateGasCategoryReqDTO reqDto) {
        if (reqDto == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        if (StringUtils.isBlank(reqDto.getMolecularFormula()))
            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.getUnit()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"气体单位不能为空");
        if (reqDto.getThreshold() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"气体浓度阈值不能为空");
        gasCategoryMolecularFormulaRepeatlock.lock();
        try{
            GasCategory byMolecularFormula = gasCategoryRepository.findByMolecularFormula(reqDto.getMolecularFormula());
            if (byMolecularFormula != null){
                throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"气体分子式已存在");
            }
            User user = getCurrentUser();
            GasCategory gasCategory = new GasCategory();
            BeanUtils.copyProperties(reqDto,gasCategory);
            gasCategory.setGmtCreate(LocalDateTime.now());
            gasCategory.setGmtModified(LocalDateTime.now());
            gasCategory.setCreatedby(user.getRealName());
            gasCategory.setLastmodifiedby(user.getRealName());
            GasCategory save = gasCategoryRepository.save(gasCategory);
            if (save == null)
                throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(), "气体新增失败");
        }finally {
            gasCategoryMolecularFormulaRepeatlock.unlock();
        }
        //清除redis缓存
        RBucket<List<GasCategory>> bucket = redissonClient.getBucket(SystemCacheKeyEnum.KEY_GAS_CATEGORY.getKey());
        if (bucket.isExists()) {
            bucket.delete();
        }
        return Result.success();
    }
 
    @Override
    public Result updateGasCategory(UpdateGasCategoryReqDTO reqDto) {
        if (reqDto == null || reqDto.getId() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        if (StringUtils.isBlank(reqDto.getMolecularFormula()))
            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.getUnit()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"气体单位不能为空");
        if (reqDto.getThreshold() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"气体浓度阈值不能为空");
        gasCategoryMolecularFormulaRepeatlock.lock();
        try {
            GasCategory byMolecularFormula = gasCategoryRepository.findByMolecularFormula(reqDto.getMolecularFormula());
            if (byMolecularFormula != null && byMolecularFormula.getId() != reqDto.getId()){
                throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"气体分子式已存在");
            }
            User user = getCurrentUser();
            Optional<GasCategory> category = gasCategoryRepository.findById(reqDto.getId());
            if (category.isPresent()){
                GasCategory gasCategory = category.get();
                BeanUtils.copyProperties(reqDto,gasCategory);
                gasCategory.setGmtModified(LocalDateTime.now());
                gasCategory.setLastmodifiedby(user.getRealName());
                GasCategory save = gasCategoryRepository.save(gasCategory);
                if (save == null)
                    throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(), "气体更新失败");
            }
        }finally {
            gasCategoryMolecularFormulaRepeatlock.unlock();
        }
        //清除redis缓存
        RBucket<List<GasCategory>> bucket = redissonClient.getBucket(SystemCacheKeyEnum.KEY_GAS_CATEGORY.getKey());
        if (bucket.isExists()) {
            bucket.delete();
        }
        return Result.success();
    }
 
    @Override
    public Result findGasCategoryById(Integer id) {
        Result success = Result.success();
        if (id == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        Optional<GasCategory> optionalGasCategory = gasCategoryRepository.findById(id);
        if (optionalGasCategory.isPresent()){
            FindGasCategoryByIdRespDTO resp = new FindGasCategoryByIdRespDTO();
            GasCategory gasCategory = optionalGasCategory.get();
            BeanUtils.copyProperties(gasCategory,resp);
            success.setData(resp);
        }
        return success;
    }
 
    public GasCategory findById(Integer id) {
        if (id == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空");
        Optional<GasCategory> optionalGasCategory = gasCategoryRepository.findById(id);
        return optionalGasCategory.get();
    }
 
    @Override
    public List<GasCategory> findGasCategoryForReport() {
        return gasCategoryRepository.findGasCategoryForReport();
    }
 
    @Override
    public Result gasCategoryList() {
        Result success = Result.success();
        RBucket<List<GasCategory>> bucket = redissonClient.getBucket(SystemCacheKeyEnum.KEY_GAS_CATEGORY.getKey());
        List<GasCategory> categories = bucket.get();
        if (CollectionUtils.isEmpty(categories)){
            categories = gasCategoryRepository.findAll();
            bucket.set(categories);
        }
        if (!CollectionUtils.isEmpty(categories)){
            List<GasCategoryListRespDTO> resps = categories.stream().map(categorie -> {
                GasCategoryListRespDTO resp = new GasCategoryListRespDTO();
                BeanUtils.copyProperties(categorie, resp);
                return resp;
            }).collect(Collectors.toList());
            success.setData(resps);
        }
        return success;
    }
 
    @Override
    public List<GasCategory> list() {
        return gasCategoryRepository.findAll();
    }
 
    @Override
    public Result findGasCategoryPage(PageQuery<FindGasCategoryPageQuery> 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<GasCategory> specification = new Specification<GasCategory>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Set<Predicate> predicateList = new HashSet<>();
                FindGasCategoryPageQuery searchParams = pageQuery.getSearchParams();
                if (searchParams != null && !StringUtils.isBlank(searchParams.getName())){
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class),"%"+searchParams.getName()+"%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        SearchResult<List<FindGasCategoryPageRespDTO>> searchResult = new SearchResult<>();
        searchResult.setPageIndex(pageQuery.getPageIndex());
        searchResult.setPageSize(pageQuery.getPageSize());
        searchResult.setSuccess();
        Page<GasCategory> pageResult = gasCategoryRepository.findAll(specification,pageable);
        searchResult.setTotal(pageResult.getTotalElements());
        searchResult.setPages(pageResult.getTotalPages());
        if (!CollectionUtils.isEmpty(pageResult.getContent())){
            List<FindGasCategoryPageRespDTO> respDTOS = pageResult.getContent().stream().map(gasCategory -> {
                FindGasCategoryPageRespDTO dto = new FindGasCategoryPageRespDTO();
                BeanUtils.copyProperties(gasCategory,dto);
                return dto;
            }).collect(Collectors.toList());
            searchResult.setData(respDTOS);
        }
        return searchResult;
    }
}