package com.zy.acs.manager.manager.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zy.acs.framework.common.Cools; import com.zy.acs.framework.exception.CoolException; import com.zy.acs.manager.core.service.MapService; import com.zy.acs.manager.manager.entity.Code; import com.zy.acs.manager.manager.entity.CodeGap; import com.zy.acs.manager.manager.mapper.CodeGapMapper; import com.zy.acs.manager.manager.service.CodeGapService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.Date; import java.util.HashMap; import java.util.Map; @Slf4j @Service("codeGapService") public class CodeGapServiceImpl extends ServiceImpl implements CodeGapService { public static final Map GAP_DISTANCE_CACHE = new HashMap<>(); @Autowired private MapService mapService; @PostConstruct public void init() { for (CodeGap codeGap : this.list()) { String gapKey = generateGapKey(codeGap.getCode0(), codeGap.getCode1()); if (!Cools.isEmpty(gapKey)) { GAP_DISTANCE_CACHE.put(gapKey, codeGap); } } log.info("The gap cache was initialized..."); } @Override public CodeGap createCodeGapByCode(Code code0, Code code1, Long userId) { if (code0.getData().equals(code1.getData())) { return null; } CodeGap codeGap = findByCodeOfBoth(code0.getId(), code1.getId()); if (null == codeGap) { Date now = new Date(); codeGap = new CodeGap(); codeGap.setCode0(code0.getId()); codeGap.setCode1(code1.getId()); double distance = mapService.calculateDistance(code0.getX(), code0.getY(), code1.getX(), code1.getY()); codeGap.setDistance(distance); codeGap.setStatus(1); codeGap.setCreateBy(userId); codeGap.setCreateTime(now); codeGap.setUpdateBy(userId); codeGap.setUpdateTime(now); if (!this.save(codeGap)) { throw new CoolException(code0.getData() + "-" + code1.getData() + " save fail![Route]"); } } return codeGap; } @Override public CodeGap findByCodeOfBoth(Long code0, Long code1) { CodeGap codeGap = null; String gapKey = generateGapKey(code0, code1); if (!Cools.isEmpty(gapKey)) { codeGap = GAP_DISTANCE_CACHE.get(gapKey); } if (null == codeGap) { codeGap = getOne(new LambdaQueryWrapper().eq(CodeGap::getCode0, code0).eq(CodeGap::getCode1, code1)); if (codeGap == null) { codeGap = getOne(new LambdaQueryWrapper().eq(CodeGap::getCode1, code0).eq(CodeGap::getCode0, code1)); } } return codeGap; } @Override public Double findDistanceByCode(Long code0, Long code1) { return 0.0; } private static String generateGapKey(Long code0, Long code1) { if (Cools.isEmpty(code0, code1)) { return null; } if (code1 < code0) { return code1 + "-" + code0; } return code0 + "-" + code1; } }