package cc.smtweb.system.bpm.web.engine.model.flow.listcard.lcms;

import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.system.bpm.web.design.form.define.PageDataset;
import cc.smtweb.system.bpm.web.engine.model.common.FlowModelSaveHandler;
import cc.smtweb.system.bpm.web.engine.model.common.ModelDetail;
import cc.smtweb.system.bpm.web.engine.model.listcard.lcms.LCMsConfig;

import java.util.function.BiConsumer;

/**
 * @Author:lip
 * @Date : 2022/9/16 19:25
 * 主子表模型保存处理类
 */
public class FlowLcMsSaveHandler extends FlowModelSaveHandler {

    // 子表明细
    protected ModelDetail subDetail;

    @Override
    public void readFromPage(SwMap pageData, SwMap filter) {
        super.readFromPage(pageData, filter);
        LCMsConfig.Config config = new LCMsConfig.Config(form);
        // 读取子表
        subDetail = readDetailFromPage(LCMsConfig.dsSList,pageData,filter,(isNew,item) -> {
            if(isNew){
                item.setEntityId(DbEngine.getInstance().nextId());
                item.put(config.getSubFKField(),bean.getEntityId());
            }
        });
    }

    @Override
    protected void checkValid() {
        super.checkValid();
        // 校验子表明细
    }

    @Override
    public void doSave() {
        super.doSave();
        // 保存子表
        saveDetail(LCMsConfig.dsSList,subDetail);
    }

    /**
     * 读取明细 供子类调用
     * @param dsName 数据集名称
     * @param pageData 数据对象
     * @param filter 数据集的filter参数
     * @param afterReadBean 读取明细之后的接口
     * @return
     * @param <E>
     */
    protected <E extends DefaultEntity> ModelDetail<E> readDetailFromPage(String dsName, SwMap pageData, SwMap filter, BiConsumer<Boolean,E> afterReadBean) {
        ModelDetail<E> modelDetail = new ModelDetail<>();
        PageDataset pageDataset = findDataset(dsName);
        modelDetail.readFromMap(pageDataset,pageData,afterReadBean);
        return modelDetail;
    }

    /**
     * 保存明细 供子类调用
     * @param dsName
     * @param modelDetail
     * @param <E>
     */
    protected <E extends DefaultEntity> void saveDetail(String dsName, ModelDetail<E> modelDetail){
        PageDataset pageDataset = findDataset(dsName);
        modelDetail.batchSave(pageDataset);
    }
}
