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.common.SwConsts;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityDao;
import cc.smtweb.framework.core.db.vo.ModelCatalog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Akmm at 2022/1/12 18:34
 */
@SwCache(ident = "ASP_MODEL_CATALOG", title = "目录")
public class ModelCatalogCache extends AbstractCache<ModelCatalog> {
    public final static String CACHE_KEY = "prj";

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

    public ModelCatalogCache() {
        regList(SwConsts.KEY_PARENT_ID, k -> String.valueOf(k.getParentId()));
        regList(CACHE_KEY, k -> k.getPrjId() + SwConsts.SPLIT_CHAR + k.getParentId());
    }

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

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

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

    public String getFullName(long id) {
        ModelCatalog bean = get(id);
        if (bean == null) return null;
        StringBuilder sret = new StringBuilder();
        while (bean != null) {
            sret.insert(0, "." + bean.getCode());
            bean = get(bean.getParentId());
        }
        return sret.substring(1);
    }

    public List<Long> getAllParent(long value) {
        List<Long> list = new ArrayList<>();
        list.add(value);
        getAllParent(value, list);
        return list;
    }

    private void getAllParent(long value, List<Long> ids) {
        Long parent_id = getParentId(value);
        if (parent_id == null) return;
        ids.add(parent_id);
        getAllParent(parent_id, ids);
    }

    public Long getParentId(long id) {
        ModelCatalog bean = get(id);
        if (bean == null || bean.isEmpty()) return null;
        return bean.getParentId();
    }
}
