puzhibing
2023-06-30 f58cca364b731eac2d60a440ffaa804be3cd43fd
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
package com.stylefeng.guns.modular.system.service.impl;
 
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.system.model.TRegion;
import com.stylefeng.guns.modular.system.dao.TRegionMapper;
import com.stylefeng.guns.modular.system.service.ITRegionService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 省市区三级联动 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2023-02-20
 */
@Service
public class TRegionServiceImpl extends ServiceImpl<TRegionMapper, TRegion> implements ITRegionService {
 
    @Autowired
    private TRegionMapper tRegionMapper;
 
    @Override
    public List<TRegion> getAreaList() {
        // 查询所有区域
        List<TRegion> tRegions = tRegionMapper.selectList(new EntityWrapper<TRegion>());
        if (CollectionUtils.isEmpty(tRegions)){
            return Lists.newArrayList();
        }
        // 过滤顶级
        List<TRegion> parent = tRegions.stream().filter(region -> region.getParentId().equals(0)).collect(Collectors.toList());
        // 再进行递归组装
        getChildren(tRegions, parent);
        return parent;
    }
 
    /**
     * 递归封装层级
     * @param tRegions
     * @param parentList
     */
    private void getChildren(List<TRegion> tRegions, List<TRegion> parentList) {
        parentList.stream().forEach(parent -> {
            List<TRegion> children = tRegions.stream().
                    filter(salesTierVO -> salesTierVO.getParentId().equals(parent.getId()))
                    .collect(Collectors.toList());
            parent.setChildren(children);
            if (!CollectionUtils.isEmpty(children)) {
                getChildren(tRegions, children);
            }
        });
    }
}