package com.gkhy.testFourierSpecialGasMonitor.service.impl; import com.gkhy.testFourierSpecialGasMonitor.commons.domain.Result; import com.gkhy.testFourierSpecialGasMonitor.commons.domain.SearchResult; import com.gkhy.testFourierSpecialGasMonitor.commons.enums.ResultCode; import com.gkhy.testFourierSpecialGasMonitor.commons.enums.SystemCacheKeyEnum; import com.gkhy.testFourierSpecialGasMonitor.commons.exception.BusinessException; import com.gkhy.testFourierSpecialGasMonitor.commons.model.PageQuery; import com.gkhy.testFourierSpecialGasMonitor.domain.account.entity.User; import com.gkhy.testFourierSpecialGasMonitor.domain.account.enums.UserStatusEnum; import com.gkhy.testFourierSpecialGasMonitor.domain.account.repository.jpa.UserRepository; import com.gkhy.testFourierSpecialGasMonitor.entity.GasCategory; import com.gkhy.testFourierSpecialGasMonitor.entity.GasCategoryConfiguration; import com.gkhy.testFourierSpecialGasMonitor.entity.query.FindGasCategoryPageQuery; import com.gkhy.testFourierSpecialGasMonitor.entity.req.CreateGasCategoryReqDTO; import com.gkhy.testFourierSpecialGasMonitor.entity.req.UpdateGasCategoryReqDTO; import com.gkhy.testFourierSpecialGasMonitor.entity.resp.*; import com.gkhy.testFourierSpecialGasMonitor.repository.GasCategoryConfigurationRepository; import com.gkhy.testFourierSpecialGasMonitor.repository.GasCategoryRepository; import com.gkhy.testFourierSpecialGasMonitor.service.GasCategoryService; import com.gkhy.testFourierSpecialGasMonitor.utils.ThreadLocalUtil; import io.micrometer.core.instrument.util.StringUtils; import org.redisson.api.RBucket; import org.redisson.api.RedissonClient; 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.util.CollectionUtils; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; 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; @Autowired private GasCategoryConfigurationRepository gasCategoryConfigurationRepository; 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> 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 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> 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 optionalGasCategory = gasCategoryRepository.findById(id); //根据气体id查询气体参数配置 List byGascategoryId = gasCategoryConfigurationRepository.findByGasCategoryId(id); List configurationRespDTOS = byGascategoryId.stream() .map(gasCategoryConfiguration -> { GasCategoryConfigurationRespDTO gasCategoryConfigurationRespDTO = new GasCategoryConfigurationRespDTO(); BeanUtils.copyProperties(gasCategoryConfiguration, gasCategoryConfigurationRespDTO); return gasCategoryConfigurationRespDTO; }) .distinct() // 根据equals和hashCode去重 .collect(Collectors.toList()); if (optionalGasCategory.isPresent()){ FindGasCategoryByIdRespDTO resp = new FindGasCategoryByIdRespDTO(); GasCategory gasCategory = optionalGasCategory.get(); BeanUtils.copyProperties(gasCategory,resp); resp.setGasCategoryConfigurations(configurationRespDTOS); success.setData(resp); } return success; } public GasCategory findById(Integer id) { if (id == null) throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"参数不能为空"); Optional optionalGasCategory = gasCategoryRepository.findById(id); return optionalGasCategory.get(); } @Override public List findGasCategoryForReport() { return gasCategoryRepository.findGasCategoryForReport(); } @Override public Result gasCategoryList() { Result success = Result.success(); RBucket> bucket = redissonClient.getBucket(SystemCacheKeyEnum.KEY_GAS_CATEGORY.getKey()); List categories = bucket.get(); if (CollectionUtils.isEmpty(categories)){ categories = gasCategoryRepository.findAll(); bucket.set(categories); } if (!CollectionUtils.isEmpty(categories)){ List 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 list() { return gasCategoryRepository.findAll(); } @Override public Result findGasCategoryPage(PageQuery 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 specification = new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { Set 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> searchResult = new SearchResult<>(); searchResult.setPageIndex(pageQuery.getPageIndex()); searchResult.setPageSize(pageQuery.getPageSize()); searchResult.setSuccess(); Page pageResult = gasCategoryRepository.findAll(specification,pageable); searchResult.setTotal(pageResult.getTotalElements()); searchResult.setPages(pageResult.getTotalPages()); if (!CollectionUtils.isEmpty(pageResult.getContent())){ List respDTOS = pageResult.getContent().stream().map(gasCategory -> { FindGasCategoryPageRespDTO dto = new FindGasCategoryPageRespDTO(); BeanUtils.copyProperties(gasCategory,dto); //根据气体id查询气体参数配置 List byGascategoryId = gasCategoryConfigurationRepository.findByGasCategoryId(gasCategory.getId()); List configurationRespDTOS = byGascategoryId.stream() .map(gasCategoryConfiguration -> { GasCategoryConfigurationRespDTO gasCategoryConfigurationRespDTO = new GasCategoryConfigurationRespDTO(); BeanUtils.copyProperties(gasCategoryConfiguration, gasCategoryConfigurationRespDTO); return gasCategoryConfigurationRespDTO; }) .distinct() // 根据equals和hashCode去重 .collect(Collectors.toList()); dto.setGasCategoryConfigurations(configurationRespDTOS); return dto; }).collect(Collectors.toList()); searchResult.setData(respDTOS); } return searchResult; } }