package com.czg.service.system.service.impl;

import com.czg.service.system.mapper.SysRegionMapper;
import com.czg.system.entity.SysRegion;
import com.czg.system.service.SysRegionService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 行政区表 服务层实现。
 *
 * @author ww
 * @since 2026-01-06
 */
@Service
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements SysRegionService {


    @Cacheable(value = "common:region", key = "'all'")
    @Override
    public List<SysRegion> regionList() {
        // 1. 单次查询获取所有数据
        List<SysRegion> allRegions = list(query().ne(SysRegion::getRegionLevel, 1));
        // 2. 一次性按层级分组，减少流遍历次数
        Map<Integer, List<SysRegion>> regionByLevel = allRegions.stream()
                .collect(Collectors.groupingBy(SysRegion::getRegionLevel));

        // 3. 获取各层级数据，默认空列表避免空指针
        List<SysRegion> parents = regionByLevel.getOrDefault(2, List.of());
        List<SysRegion> level3Regions = regionByLevel.getOrDefault(3, List.of());
        List<SysRegion> level4Regions = regionByLevel.getOrDefault(4, List.of());

        // 4. 构建3级地区的子节点映射（4级），使用HashMap保证性能
        Map<String, List<SysRegion>> level4ByParentId = level4Regions.stream()
                .collect(Collectors.groupingBy(SysRegion::getParentRegionId, Collectors.toList()));

        level3Regions.forEach(level3 -> {
            List<SysRegion> children = level4ByParentId.getOrDefault(level3.getRegionId(), List.of());
            level3.setChildren(children);
        });

        Map<String, List<SysRegion>> level3ByParentId = level3Regions.stream()
                .collect(Collectors.groupingBy(SysRegion::getParentRegionId));

        parents.forEach(parent -> {
            List<SysRegion> children = level3ByParentId.getOrDefault(parent.getRegionId(), List.of());
            parent.setChildren(children);
        });
        return parents;
    }
}
