package com.kingtom.shengtai.api.model;

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

import com.kingtom.kirin.core.common.CommonConst;
import com.kingtom.kirin.core.common.utils.CollectionUtils;
import com.kingtom.shengtai.api.mapper.ProductDirMapper;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.apache.commons.lang3.StringUtils;

/**
 * 应用模块名称</p>
 * 代码描述</p>
 * Copyright: Copyright (C) 2024 , Inc. All rights reserved. <p>
 * Company: 成都诚唐科技有限责任公司</p>
 *
 * @author wany
 * @since 2024/1/17
 */

@Data
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "产品目录树")
public class ProductDirTreeDTO extends ProductDirDTO{

    @Schema(description = "父目录名称")
    private String parentName;

    @Schema(description = "子目录集合")
    private List<ProductDirTreeDTO> children;

    /**
     * 根据集合构建出多棵树.
     *
     * @param list the list
     * @return the list
     */
    public static List<ProductDirTreeDTO> build(List<ProductDirDTO> list){
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        list = new ArrayList<>(list);
        list.sort(Comparator.comparing(e -> StringUtils.join(e.getPath(), CommonConst.EMPTY_STRING)));
        Map<String, List<ProductDirDTO>> map = list.stream().collect(Collectors.groupingBy(ProductDirDTO::getParentId));
        return buildChildren(map, list.get(0).getSysId(), CommonConst.EMPTY_STRING);
    }

    private static List<ProductDirTreeDTO> buildChildren(Map<String, List<ProductDirDTO>> map, String key,
            String parentName){
        List<ProductDirDTO> dirs = map.remove(key);
        if(CollectionUtils.isEmpty(dirs)){
            return null;
        }
        return dirs.stream().map(dir -> {
            ProductDirTreeDTO dto = ProductDirMapper.INSTANCE.convertDTOToTree(dir);
            dto.setChildren(buildChildren(map, dir.getId(), dir.getName()));
            dto.setParentName(parentName);
            return dto;
        }).sorted(Comparator.comparing(ProductDirTreeDTO::getGmtCreate)).collect(Collectors.toList());
    }

}
