package com.cool.store.vo.region;

import com.cool.store.constants.CommonConstants;
import com.cool.store.entity.RegionDO;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @author zhangchenbiao
 * @FileName: RegionBaseInfoVO
 * @Description:
 * @date 2023-06-12 16:08
 */
@Data
public class RegionBaseInfoVO {

    @ApiModelProperty("区域id")
    private String regionId;

    @ApiModelProperty("区域名称")
    private String name;

    @ApiModelProperty("子区域")
    private List<RegionBaseInfoVO> subRegionList;

    public RegionBaseInfoVO(String regionId, String name) {
        this.regionId = regionId;
        this.name = name;
    }

    /**
     * 转换成树
     * @param regionList
     * @return
     */
    public static RegionBaseInfoVO convertTree(List<RegionDO> regionList){
        Map<String, List<RegionDO>> parentMap = regionList.stream().collect(Collectors.groupingBy(k -> k.getParentId()));
        RegionDO rootRegion = regionList.stream().filter(o -> CommonConstants.ZERO_STR.equals(o.getParentId())).findFirst().get();
        RegionBaseInfoVO result = new RegionBaseInfoVO(rootRegion.getRegionId(), rootRegion.getName());
        result.setSubRegionList(getSubRegion(rootRegion.getRegionId(), parentMap));
        return result;
    }

    /**
     * 获取子区域
     * @param regionId
     * @param parentMap
     * @return
     */
    public static List<RegionBaseInfoVO> getSubRegion(String regionId, Map<String, List<RegionDO>> parentMap){
        List<RegionBaseInfoVO> resultList = new ArrayList<>();
        if(Objects.isNull(parentMap) || StringUtils.isBlank(regionId)){
            return resultList;
        }
        List<RegionDO> subRegion = parentMap.get(regionId);
        if(CollectionUtils.isNotEmpty(subRegion)){
            for (RegionDO region : subRegion) {
                RegionBaseInfoVO regionBaseInfo = new RegionBaseInfoVO(region.getRegionId(), region.getName());
                regionBaseInfo.setSubRegionList(getSubRegion(region.getRegionId(), parentMap));
                resultList.add(regionBaseInfo);
            }
        }
        return resultList;
    }

}
