package cc.smtweb.system.bpm.web.sys.user.party;

import cc.smtweb.framework.core.annotation.SwCache;
import cc.smtweb.framework.core.cache.AbstractEntityCache;
import cc.smtweb.framework.core.cache.CacheManager;
import cc.smtweb.framework.core.util.CommUtil;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by 1 at 2022-07-26 17:52:21
 * 实体【[机构表](SYS_PARTY)】的缓存类
 */
@SwCache(ident = "SYS_PARTY", title = "机构表")
public class PartyCache extends AbstractEntityCache<Party> {
    //缓存key：按父ID
    public final static String mk_pr = "pr";
    //缓存key：按编码
    public final static String mk_code = "code";

    public static PartyCache getInstance() {
        return CacheManager.getIntance().getCache(PartyCache.class);
    }

    public PartyCache() {
        //缓存key：按父ID
        regList(mk_pr, "pt_parent_id");
    }

    //获取儿子
    public final Set<Party> getChildren(Long key) {
        return getListByKey(mk_pr, String.valueOf(key));
    }

    public final Set<Party> getAllChildren(Long key) {
        Set<Party> set = new HashSet<>();
        buildChildren(key, set);
        return set;
    }

    private final void buildChildren(Long key, Set<Party> set) {
        Set<Party> child = getChildren(key);
        if (CommUtil.isEmpty(child)) return;
        set.addAll(child);
        for (Party party : child) {
            buildChildren(party.getId(), set);
        }
    }

    //获取顶级集合
    public final Set<Party> getTopSet() {
        return getChildren(-1L);
    }

    //是否顶级
    public final boolean isTop(Long key) {
        Party party = get(key);
        return party != null && party.getParentId() <= 0;
    }

    //是否末级
    public final boolean isLeaf(Long key) {
        Set<Party> children = getChildren(key);
        return CommUtil.isEmpty(children);
    }

    public final String getNameById(Long id) {
        Party party = get(id);
        if (party == null) return "";
        return party.getName();
    }
}
