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

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 java.util.List;

/**
 * Created by Akmm at 2022-08-14 12:17
 * 简单列表（含编辑弹窗）
 */
public class LcSingleWorker extends BaseModelWorker {
    private final static String tmpl = "model_list_card";

    @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);
        SwMap cfgPage = new SwMap();
        cfg.put(ModelFormHelper.OPT_PAGE, cfgPage);
        String formName = ModelFormHelper.getPageName(bean) + StringUtil.upFirst(SwEnum.PageType.LIST.value);
        cfgPage.put(SwEnum.PageType.LIST.value, formName);
        bean.setOption(JsonUtil.encodeString(opts));

        ModelForm page;
        if (bean.isNew()) {//新增
            page = createPage(bean, SwEnum.PageType.LIST.value);
            listFormChild.add(page);
            dao.insertEntity(page);
        } else {//修改，先不考虑修改模型的情况 todo
            page = ModelFormHelper.getFromCache(formName);
            boolean modified = false;
            //服务名发生变化
            if (!StringUtil.isStrEquals(page.getService(), bean.getService())) {
                page.setService(bean.getService());
                modified = true;
            }
            if (modified) {
                dao.updateEntityEx(bean, "mf_content", "mf_dataset", "mf_tmpl");
                listFormChild.add(page);
            }
        }
    }

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