package com.scpyun.base.core.utils;

import com.scpyun.platform.jilinsscgsdp.pojo.Area;
import com.scpyun.platform.jilinsscgsdp.pojo.SimpleAreaNode;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class SameTypeFlatTreeBuilder {

    // 虚拟节点名称后缀
    private static final String PROVINCE_LEVEL = "省本级";
    private static final String CITY_LEVEL = "市本级";
    private static final String DISTRICT_LEVEL = "区本级";
    private static final String STREET_LEVEL = "街道本级";
    private static final String COMMUNITY_LEVEL = "社区本级";

    /**
     * 构建平级且同type的树形结构（使用isValue字段）
     * @param allAreas 原始区域数据
     * @return 平级结构节点列表
     */
    public List<SimpleAreaNode> buildSameTypeFlatTree(List<Area> allAreas) {
        List<SimpleAreaNode> result = new ArrayList<>();
        try {
            // 筛选顶级节点（无父节点：null/空串/0）
            List<Area> topAreas = allAreas.stream()
                    .filter(area -> area.getParentId() == null || area.getParentId().isEmpty() || "0".equals(area.getParentId()))
                    .collect(Collectors.toList());
            for (Area topArea : topAreas) {
                result.add(buildNode(topArea, allAreas));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 递归构建节点：包含本级虚拟节点 + 下一层实际节点（平级同type）
     */
    private SimpleAreaNode buildNode(Area currentArea, List<Area> allAreas) {
        // 创建当前实际节点（isValue=0）
        SimpleAreaNode currentNode = new SimpleAreaNode(
                currentArea.getId(),
                currentArea.getName(),
                currentArea.getType(),
                0
        );

        // 获取下一层实际子节点
        List<Area> nextLevelAreas = findChildren(currentArea.getId(), allAreas);

        if (!nextLevelAreas.isEmpty()) {
            String nextLevelType = nextLevelAreas.get(0).getType();
            // 添加本级虚拟节点（isValue=1，type与下一层一致）
            currentNode.getChildren().add(createVirtualNode(currentArea, nextLevelType));
            // 添加下一层实际节点（递归构建）
            nextLevelAreas.forEach(nextArea -> currentNode.getChildren().add(buildNode(nextArea, allAreas)));
            // 排序：虚拟节点在前，实际节点按sort排序
            sortChildren(currentNode.getChildren());
        }

        return currentNode;
    }

    /**
     * 创建本级虚拟节点
     */
    private SimpleAreaNode createVirtualNode(Area parentArea, String nextLevelType) {
        String suffix = getVirtualSuffixByType(nextLevelType);
        return new SimpleAreaNode(
                parentArea.getId() + "_virtual_" + nextLevelType,
                parentArea.getName() + suffix,
                nextLevelType,
                1
        );
    }

    /**
     * 根据type匹配虚拟节点后缀
     */
    private String getVirtualSuffixByType(String nextLevelType) {
        switch (nextLevelType) {
            case "1": return PROVINCE_LEVEL;
            case "2": return CITY_LEVEL;
            case "3": return DISTRICT_LEVEL;
            case "4": return STREET_LEVEL;
            case "5": return COMMUNITY_LEVEL;
            default: return "本级";
        }
    }

    /**
     * 查找下一层实际子节点
     */
    private List<Area> findChildren(String parentId, List<Area> allAreas) {
        return allAreas.stream()
                .filter(area -> parentId.equals(area.getParentId()))
                // null排最后，非null按sort升序
                .sorted(Comparator.comparingInt(area -> area.getSort() == null ? Integer.MAX_VALUE : area.getSort()))
                .collect(Collectors.toList());
    }

    /**
     * 子节点排序：虚拟节点（isValue=1）在前，实际节点（isValue=0）在后
     */
    private void sortChildren(List<SimpleAreaNode> children) {
        children.sort(Comparator.comparingInt(SimpleAreaNode::getIsValue).reversed());
    }
}