package com.xiaoniu.system.platformsettings.region.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoniu.system.platformsettings.region.domain.TbRegion;
import com.xiaoniu.system.platformsettings.region.mapper.TbRegionMapper;
import com.xiaoniu.system.platformsettings.region.service.ITbRegionService;
import com.xiaoniu.system.platformsettings.region.vo.RegionTreeVO;
import com.xiaoniu.system.platformsettings.region.vo.RegionVO;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 省市区 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-11-01 02:12:51
 */
@Service
public class TbRegionServiceImpl extends ServiceImpl<TbRegionMapper, TbRegion> implements ITbRegionService {

    @Override
    public List<RegionTreeVO> selectRegionTreeList() {
        List<RegionVO> regionList = baseMapper.getRegionList();
        List<RegionVO> menuTrees = buildMenuTree(regionList);
        return menuTrees.stream().map(RegionTreeVO::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param regionList 省市列表·
     * @return 树结构列表
     */
    public List<RegionVO> buildMenuTree(List<RegionVO> regionList) {
        List<RegionVO> returnList = new ArrayList<RegionVO>();
        List<Integer> tempList = regionList.stream().map(RegionVO::getId).toList();
        for (RegionVO regionVO : regionList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(regionVO.getPid())) {
                recursionFn(regionList, regionVO);
                returnList.add(regionVO);
            }
        }
        if (returnList.isEmpty()) {
            returnList = regionList;
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<RegionVO> list, RegionVO t) {
        // 得到子节点列表
        List<RegionVO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (RegionVO tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<RegionVO> getChildList(List<RegionVO> list, RegionVO t) {
        List<RegionVO> tList = new ArrayList<RegionVO>();
        for (RegionVO n : list) {
            if (n.getPid().equals(t.getId())) {
                tList.add(n);
            }
        }
        return tList;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<RegionVO> list, RegionVO t) {
        return !getChildList(list, t).isEmpty();
    }
}
