package cn.axzo.msg.center.message.domain.dto;

import cn.axzo.msg.center.service.dto.GroupTreeNodeDTO;
import com.alibaba.fastjson.JSON;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author cold_blade
 * @date 2023/10/14
 * @version 1.0
 */
@Setter
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class GroupTreeNodePathDTO implements Serializable {

    private static final long serialVersionUID = -6325338437781927201L;

    private static final String NODE_NAME_PATH_SPLITER = "/";
    private static final String NODE_CODE_PATH_SPLITER = ":";

    /**
     * 结点编码
     */
    private String nodeCode;
    /**
     * 结点名称
     */
    private String nodeName;
    /**
     * 结点名称格式的路径
     */
    private String nodeNamePath;
    /**
     * 结点编码格式的路径
     */
    private String nodeCodePath;

    public static String parseLeafNodeCode(String nodeCodePath) {
        if (StringUtils.isBlank(nodeCodePath)) {
            return null;
        }
        String[] nodeCodes = nodeCodePath.split(NODE_CODE_PATH_SPLITER);
        // 最后一个为叶节点的结点编码
        return nodeCodes[nodeCodes.length - 1];
    }

    public static GroupTreeNodePathDTO of(GroupTreeNodeDTO node, Collection<GroupTreeNodeDTO> nodes) {
        String nodeNamePath = formatPath(GroupTreeNodeDTO::getNodeName, nodes, NODE_NAME_PATH_SPLITER);
        String nodeCodePath = formatPath(GroupTreeNodeDTO::getNodeCode, nodes, NODE_CODE_PATH_SPLITER);
        return new GroupTreeNodePathDTO(node.getNodeCode(), node.getNodeName(), nodeNamePath, nodeCodePath);
    }

    private static String formatPath(Function<GroupTreeNodeDTO, String> pathFunc, Collection<GroupTreeNodeDTO> nodes,
                                     String spliter) {
        return nodes.stream().map(pathFunc).collect(Collectors.joining(spliter));
    }

    public boolean equals(GroupTreeNodePathDTO treeNodePath) {
        return Objects.nonNull(treeNodePath)
                && Objects.equals(nodeCode, treeNodePath.getNodeCode())
                && Objects.equals(nodeCodePath, treeNodePath.getNodeCodePath());
    }

    public boolean equals(String nodeCodePath) {
        return Objects.equals(nodeCodePath, this.nodeCodePath);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
