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

import cc.smtweb.framework.core.common.AbstractEnum;
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.db.EntityDao;
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.springframework.util.Assert;

import java.util.List;

/**
 * @Author:lip
 * @Date : 2022/9/14 11:27
 * 自定义模型-生成一个空白页面
 */
public class EmptyWorker extends BaseModelWorker{
    private final static String template = "model_empty";

    @Override
    protected void saveModule(ModelForm bean, List<ModelForm> listFormChild) {
        EntityDao<ModelForm> dao = DbEngine.getInstance().findDao(ModelForm.class);

        SwMap opts = bean.getOpts();
        SwMap cfg = opts.readMap(ModelFormHelper.OPT_CONFIG);
        //
        String pageType = cfg.readMap("props").readString("pageType");
        AbstractEnum.StrEnumBean type = SwEnum.PageType.instance.getByValue(pageType);
        Assert.notNull(type, "无效页面类型: " + pageType);
        String pageName = ModelFormHelper.getPageName(bean) + StringUtil.upFirst(pageType);
        //
        SwMap cfgPage = new SwMap();
        cfg.put(ModelFormHelper.OPT_PAGE, cfgPage);
        //
        cfgPage.put(pageType, pageName);
        bean.setOption(JsonUtil.encodeString(opts));
        //
        ModelForm page;
        if (bean.isNew()) {
            //新增
            page = createPage(bean, pageType);
            listFormChild.add(page);
            dao.insertEntity(page);
        } else {
            //修改，先不考虑修改模型的情况 todo
            page = ModelFormHelper.getFromCache(pageName);
            Assert.isTrue(page != null, "获取页面失败");
            listFormChild.add(page);
            boolean modified = false;
            //服务名发生变化
            if (!StringUtil.isStrEquals(page.getService(), bean.getService())) {
                page.setService(bean.getService());
                modified = true;
            }
            if (modified) {
                dao.updateEntity(page, "mf_content,mf_dataset,mf_tmpl");
            }
        }
    }

    @Override
    protected String getTmplId(ModelForm bean) {
        return template;
    }
}
