package com.ssyf.common.web.helper;

import cn.hutool.core.util.IdUtil;

/**
 * 数据族谱帮助类
 * @author huwei
 * @date 2023/2/1 11:25
 */
public class DataPedigreeHelper {

    /**
     * 初始化级联信息
     * @param source
     * @param parentId
     * @param parent
     * @param lastChild
     */
    public static void initCascadeField(DataPedigree source ,String parentId, DataPedigree parent ,DataPedigree lastChild){ ;
        if(parent == null){
            initCascadeField(source);
        }else{
            int childNumber = -1;
            if(lastChild != null){
                childNumber = DataPathHelper.parseLastNodeNumber(lastChild.getPedigree());
            }
            source.setFamilyId(parent.getFamilyId()).setParentId(parentId);
            source.setGeneration(parent.getGeneration() + 1);
            source.setPedigree(DataPathHelper.createPath(parent.getPedigree(),childNumber + 1));
        }
    }

    public static void initCascadeField(DataPedigree source){
        source.setFamilyId(IdUtil.simpleUUID()).setParentId("");
        source.setGeneration(1);
        source.setPedigree(DataPathHelper.createPath(null ,1));
    }

    /**
     * 是否为祖先
     * @param ancestor
     * @param dataPedigree
     * @return
     */
    public static boolean isAncestor(DataPedigree ancestor ,DataPedigree dataPedigree){
        if(!ancestor.getFamilyId().equals(dataPedigree.getFamilyId())){
            return false;
        }
        return dataPedigree.getPedigree().startsWith(ancestor.getPedigree());
    }
}
