package cc.smtweb.system.bpm.web.engine.dynPage;

import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.framework.core.mvc.service.AbstractHandler;
import cc.smtweb.framework.core.session.UserSession;
import cc.smtweb.system.bpm.web.design.form.ModelForm;
import cc.smtweb.system.bpm.web.design.form.ModelFormHelper;
import cc.smtweb.system.bpm.web.design.form.define.PageDataset;
import cc.smtweb.system.bpm.web.design.form.define.PageDatasets;

/**
 * Created by Akmm at 2022/4/21 17:53
 */
public abstract class AbstractDynPageHandler extends AbstractHandler {
    //页面定义id或页面pageName
    protected String pageId;
    protected ModelForm form;
    protected PageDatasets datasets;

    protected DynPageProvider provider = getProvider();

    public DynPageProvider getProvider() {
        return new DynPageProvider();
    }

    @Override
    public void init(SwMap params, UserSession us) {
        super.init(params, us);
        pageId = params.readString("pageId");
        form = ModelFormHelper.getFromCache(pageId);
        if (form == null) throw new BizException("没有找到页面定义数据(" + pageId + ")！");
        datasets = form.getDatasets();
        if (datasets == null || datasets.list == null) throw new BizException("没有找到页面定义的数据集数据(" + pageId + ")！");

        provider.pageId = form.getId();
        provider.datasets = datasets;
        provider.us = us;
    }

    protected PageDataset findDataset(String name) {
        return datasets.findByName(name);
    }

    //找可编辑卡片数据集
    protected PageDataset findCardDataset(String dsName) {
        PageDataset cardDataset = datasets.findByName(dsName);
        if (cardDataset == null) throw new SwException("没有找到卡片数据集(" + dsName + ")！");
        if (!SwEnum.DatasetType.FORM.value.equals(cardDataset.type)) {//单表
            throw new SwException("卡片数据集定义错误(" + dsName + ")！");
        }
        return cardDataset;
    }

    //找列表数据集
    protected PageDataset findListDataset(String dsName) {
        PageDataset listDataset = datasets.findByName(dsName);
        if (listDataset == null) throw new SwException("没有找到列表数据集(" + dsName + ")！");
        if (!SwEnum.DatasetType.LIST.value.equals(listDataset.type)) {//列表
            throw new SwException("列表数据集定义错误(" + dsName + ")！");
        }
        return listDataset;
    }

    //获取第一个，主数据集
    protected PageDataset findMasterDataset() {
        return datasets.findMasterDataset();
    }

    //从参数读取数据集定义
    protected PageDataset readParamDs() {
        //数据集
        String dbName = params.readString("dataset");
        //对应的数据集定义
        PageDataset pageDataSet = findDataset(dbName);
        if (pageDataSet == null) throw new BizException("没有找到指定的的数据集定义：" + dbName + "！");
        return pageDataSet;
    }
}
