package cc.smtweb.system.bpm.web.design.db;

import cc.smtweb.framework.core.annotation.SwCache;
import cc.smtweb.framework.core.cache.AbstractCache;
import cc.smtweb.framework.core.cache.CacheManager;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityDao;
import cc.smtweb.framework.core.db.vo.ModelProject;
import cc.smtweb.framework.core.util.NumberUtil;
import org.apache.commons.lang3.StringUtils;

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

/**
 * Created by Akmm at 2022/1/12 18:34
 */
@SwCache(ident = "ASP_MODEL_PROJECT", title = "项目定义")
public class ModelProjectCache extends AbstractCache<ModelProject> {
    private final static String mm = "m";

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

    public ModelProjectCache() {
        regMap(mm, k -> String.valueOf(k.getModule()));
    }

    @Override
    protected String getId(ModelProject bean) {
        return String.valueOf(bean.getId());
    }

    @Override
    protected List<ModelProject> loadAll() {
        EntityDao<ModelProject> dao = DbEngine.getInstance().findDao(ModelProject.class);
        return dao.query();
    }

    public String getModule(long id) {
        ModelProject bean = get(id);
        return bean != null ? bean.getModule(): "";
    }

    public ModelProject getByModule(String module) {
        return getByKey(mm, module);
    }

    public String getIdByModule(String module) {
        ModelProject bean = getByModule(module);
        return bean != null ? String.valueOf(bean.getId()): "";
    }

    //找当前项目及其依赖项目的id集合，递归
    public Set<Long> getDependsPrjIds(long id) {
        Set<Long> set = new HashSet<>();
        addPrjId(set, id);
        return set;
    }

    //递归增加
    private void addPrjId(Set<Long> set, long id) {
        if (set.contains(id)) return;
        ModelProject bean = get(id);
        if (bean == null) return;
        set.add(id);
        if (StringUtils.isEmpty(bean.getDepends())) return;
        String[] dps = bean.getDepends().split(",");
        for (String s : dps) {
            s = s.trim();
            if (StringUtils.isEmpty(s)) return;
            addPrjId(set, NumberUtil.getLongIgnoreErr(s));
        }
    }
}
