package cc.smtweb.system.bpm.web.design.form.model;

import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.framework.core.util.JsonUtil;
import cc.smtweb.framework.core.util.StringUtil;
import cc.smtweb.system.bpm.web.design.form.ModelForm;
import cc.smtweb.system.bpm.web.design.form.ModelFormHelper;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Created by Akmm at 2022-08-14 10:37
 * 抽象类的页面保存，供各模板继承使用
 */
public class BaseModelWorker {
    /**
     * 模块/页面保存：opts根据模型做些个性化处理，如果是模块，需要添加子页面
     *
     * @param bean
     * @param listFormChild
     */
    public void saveForm(ModelForm bean, List<ModelForm> listFormChild) {
        SwMap opts = bean.getOpts();
        if (opts != null) {
            opts.remove(ModelFormHelper.KEY_EVENT_PATH);
            opts.remove(ModelFormHelper.KEY_BILL_TYPE + SwConsts.TEXT_SUFFIX);
            bean.setOption(JsonUtil.encodeString(opts));
        }
        if (bean.getType() == SwEnum.FormType.MODULE.value) {
            saveModule(bean, listFormChild);
        } else {
            savePage(bean);
        }
    }

    //保存模块
    protected void saveModule(ModelForm bean, List<ModelForm> listFormChild) {

    }

    //保存页面，备用
    protected void savePage(ModelForm bean) {

    }

    //构建一个子页面
    protected ModelForm createPage(ModelForm bean, String type) {
        ModelForm page = new ModelForm();
        page.getData().putAll(bean.getData());
        page.setId(DbEngine.getInstance().nextId());
        page.setName(bean.getName() + StringUtil.upFirst(type));

        page.setDataset(null);
        page.setContent(null);
        page.setTmpl(null);
        page.setType(SwEnum.FormType.PAGE.value);
        page.setParent(bean.getId());
        page.setTitle(bean.getTitle() + SwEnum.PageType.instance.getName(type));

        SwMap opts = new SwMap();
        opts.putAll(bean.getOpts());
        opts.put("pageType", type);
        page.setOption(JsonUtil.encodeString(opts));

        return page;
    }

    /**
     * 根据模型生成页面
     *
     * @param bean
     */
    public void buildSaveModel(ModelForm bean) {
        String tmplId = getTmplId(bean);
        if (StringUtils.isEmpty(tmplId)) throw new SwException("此类型页面没有找到对应的模板文件！");
        ModelFormHelper.buildSaveModelByTmpl(bean, tmplId);
    }

    //获取模板名
    protected String getTmplId(ModelForm bean) {
        return null;
    }
}
