package cc.smtweb.system.bpm.web.engine.model.common;

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityDao;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.system.bpm.web.design.form.define.PageDataset;
import cc.smtweb.system.bpm.web.engine.dynPage.AbstractDynPageHandler;
import cc.smtweb.system.bpm.web.engine.dynPage.DynRetBean;

/**
 * Created by Akmm at 2022-08-16 15:43
 * 模型卡片加载handler
 */
public class ModelLoadHandler<T extends DefaultEntity> extends AbstractDynPageHandler {
    protected T bean;
    private String cardDsName = ModelHelper.DATASET_NAME_CARD;

    public ModelLoadHandler() {
    }

    public ModelLoadHandler(String cardDsName) {
        this.cardDsName = cardDsName;
    }

    //新增卡片操作，初始化定义的数据集
    public R add() {
        SwMap ret = new SwMap();
        bean = addBean(ret, cardDsName);
        afterAdd(ret);
        return R.success(ret);
    }

    //创建一个bean，并加到返回对象中
    protected <E extends DefaultEntity> E addBean(SwMap ret, String dsName) {
        //返回的数据，以dataset.name为key，查出的结果（bean或list）为value
        PageDataset cardDataset = findCardDataset(dsName);
        ModelTable table = cardDataset._getModelTable();
        if (table == null) throw new SwException("卡片主表未找到！");
        final EntityDao<E> dao = DbEngine.getInstance().findDao(table.getName());

        E entity = dao.createBean(us.getUserId());
        entity.setEntityId(DbEngine.getInstance().nextId());

        ret.put(dsName, DynRetBean.createBean(entity));
        return entity;
    }


    //新增初始化 - bean
    protected void afterAdd(SwMap ret) {
    }

    public R load() {
        SwMap ret = new SwMap();
        //过滤条件
        SwMap filter = params.readMap("filter");
        load(ret, filter);
        return R.success(ret);
    }

    //从数据库加载bean，并设到返回值
    protected void load(SwMap ret, SwMap filter) {
        PageDataset cardDataset = findCardDataset(cardDsName);
        long id = params.readLong(SwConsts.NAME_ID);
        if (id <= 0) id = filter.readLong(SwConsts.NAME_ID);
        bean = provider.loadBean(cardDataset, id);
        ret.put(cardDsName, DynRetBean.createBean(bean));
    }

    //给子类使用的工具方法：根据数据集配置，读取bean，并加到返回值
    protected <E extends DefaultEntity> E loadBean(SwMap ret, String dsName, SwMap filter) {
        PageDataset cardDataset = findCardDataset(dsName);
        E bean = provider.loadBean(cardDataset, filter);
        ret.put(dsName, DynRetBean.createBean(bean));
        return bean;
    }
}
