package cc.smtweb.framework.core.db.cache;

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.ModelDatabase;
import cc.smtweb.framework.core.db.vo.ModelProject;
import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.framework.core.util.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Created by Akmm at 2022/1/12 18:34
 */
@SwCache(ident = "ASP_MODEL_DATABASE", title = "数据库")
public class ModelDatabaseCache extends AbstractCache<ModelDatabase> {
    private final static String mk = "k";

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

    public ModelDatabaseCache() {
        regMap(mk, ModelDatabase::getName);
    }

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

    @Override
    protected List<ModelDatabase> loadAll() {
        EntityDao<ModelDatabase> dao = DbEngine.getInstance().findDao(ModelDatabase.class);
        if (StringUtils.isEmpty(SwConsts.SysParam.RUN_PROJECTS))
            return dao.query();
        return dao.queryEx(" inner join " + ModelProject.ENTITY_NAME + " on db_prj_id=prj_id where prj_module in (" + CommUtil.getSqlInStr(SwConsts.SysParam.RUN_PROJECTS.split(",")) + ")");
    }

    public final ModelDatabase getByName(String key) {
        return getByKey(mk, key);
    }

    public final String getName(long id) {
        ModelDatabase db = get(id);
        return db != null ? db.getName() : "";
    }
}
