package com.ssyf.common.core.helper;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.ssyf.common.core.util.AssertUtil;
import com.ssyf.common.core.domain.DataPedigree;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.common.web.apicode.ApiCodeUser;

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

    /**
     * 初始化级联信息
     * @param source
     * @param parentId
     * @param parentGetter
     * @param lastChildGetter
     */
    public static void initCascadeField(DataPedigree source , String parentId , ParentGetter parentGetter , LastChildGetter lastChildGetter){ ;
        if(StrUtil.isNotBlank(parentId)){
            DataPedigree parent = parentGetter.get(parentId);
            AssertUtil.isNotNull(parent , ServiceRuntimeException.instance(ApiCodeUser.PARAMETER_ERROR));
            DataPedigree lastChild = lastChildGetter.get(parentId);
            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));
        }else{
            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());
    }

    @FunctionalInterface
    public interface ParentGetter{
        /**
         * 获取父级信息
         * @param parentId 父级id
         * @return
         */
        DataPedigree get(String parentId);
    }

    @FunctionalInterface
    public interface LastChildGetter{
        /**
         * 获取孩子数量
         * @param parentId 父级id
         * @return
         */
        DataPedigree get(String parentId);
    }
}
