package com.ruoyi.system.service.impl;
|
|
|
import cn.hutool.core.bean.BeanUtil;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.ruoyi.common.redis.service.RedisService;
|
import com.ruoyi.system.mapper.TbRegionMapper;
|
import com.ruoyi.system.model.TbRegion;
|
import com.ruoyi.system.service.TbRegionService;
|
import com.ruoyi.system.vo.RegionVo;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Service;
|
|
import java.util.Collections;
|
import java.util.List;
|
import java.util.Objects;
|
import java.util.stream.Collectors;
|
|
/**
|
* <p>
|
* 省市区三级联动 服务实现类
|
* </p>
|
*
|
* @author administrator
|
* @since 2025-05-26
|
*/
|
@Service
|
public class TbRegionServiceImpl extends ServiceImpl<TbRegionMapper, TbRegion> implements TbRegionService {
|
|
@Autowired
|
private RedisService redisService;
|
|
@Override
|
public List<RegionVo> listCityVo() {
|
// 缓存
|
List<Object> regionList = redisService.getCacheList("region_list");
|
if (regionList!=null && !regionList.isEmpty()) {
|
List<RegionVo> regionVoList = BeanUtil.copyToList(redisService.getCacheList("region_list"), RegionVo.class);
|
return regionVoList;
|
} else {
|
// 省级
|
List<TbRegion> provinceList = this.baseMapper.selectList(
|
new LambdaQueryWrapper<TbRegion>().eq(TbRegion::getParentId, 0));
|
List<TbRegion> childrenList = this.baseMapper.selectList(
|
new LambdaQueryWrapper<TbRegion>().ne(TbRegion::getParentId, 0));
|
List<RegionVo> provinceVoList = BeanUtil.copyToList(provinceList, RegionVo.class);
|
provinceVoList = provinceVoList.stream().peek(province -> {
|
province.setLevel(1);
|
List<RegionVo> cityVOList = getChildrenRegionVoList(province,
|
childrenList);
|
if (cityVOList!=null && !cityVOList.isEmpty()) {
|
cityVOList = cityVOList.stream().peek(city -> {
|
city.setLevel(2);
|
List<RegionVo> countyVoList = getChildrenRegionVoList(city,
|
childrenList);
|
if (countyVoList!=null && !countyVoList.isEmpty()) {
|
countyVoList = countyVoList.stream().peek(county -> county.setLevel(3))
|
.collect(Collectors.toList());
|
city.setChildren(countyVoList);
|
}
|
}).collect(Collectors.toList());
|
province.setChildren(cityVOList);
|
}
|
}).collect(Collectors.toList());
|
// 缓存
|
redisService.setCacheList("region_list", provinceVoList);
|
return provinceVoList;
|
}
|
}
|
|
private static List<RegionVo> getChildrenRegionVoList(RegionVo province,
|
List<TbRegion> childrenList) {
|
List<RegionVo> cityVOList = childrenList.stream()
|
.filter(city -> city.getParentId().equals(province.getId()))
|
.map(item -> BeanUtil.copyProperties(item, RegionVo.class))
|
.filter(Objects::nonNull)
|
.collect(Collectors.toList());
|
// 将符合条件的元素从childrenList中移除
|
childrenList.removeIf(item -> item.getParentId().equals(province.getId()));
|
return cityVOList;
|
}
|
}
|