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

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.ModelFormCache;
import cc.smtweb.system.bpm.web.design.form.ModelFormHelper;
import cc.smtweb.system.bpm.web.design.form.model.BaseModelWorker;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tanghp
 * @Date: 2022-08-26 9:48
 * @Desc: 普通列表（含编辑卡片、工作流）
 */
public class FlowSingleWorker extends BaseModelWorker {
    private final static String listTmpl = "model_list_flow";
    private final static String cardTmpl = "model_card_flow";

    @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 listFormName = ModelFormHelper.getPageName(bean) + StringUtil.upFirst(SwEnum.PageType.LIST.value);
        cfgPage.put(SwEnum.PageType.LIST.value, listFormName);
        // 添加卡片页面名称
        String cardFormName = ModelFormHelper.getPageName(bean) + StringUtil.upFirst(SwEnum.PageType.CARD.value);
        cfgPage.put(SwEnum.PageType.CARD.value, cardFormName);
        bean.setOption(JsonUtil.encodeString(opts));

        if (bean.isNew()) {//新增
            List<ModelForm> insertList = new ArrayList<>();

            ModelForm listPage = createPage(bean, SwEnum.PageType.LIST.value);
            listFormChild.add(listPage);
            insertList.add(listPage);

            ModelForm cardPage = createPage(bean, SwEnum.PageType.CARD.value);
            listFormChild.add(cardPage);
            insertList.add(cardPage);

            dao.batchInsertEntity(insertList);
        } else {//修改，先不考虑修改模型的情况 todo

        }
    }

    @Override
    public void buildSaveModel(ModelForm bean) {
        ModelForm parent = ModelFormCache.getInstance().get(bean.getParent());
        if (parent == null) {
            return;
        }
        String listFormName = parent.getName() + StringUtil.upFirst(SwEnum.PageType.LIST.value);
        String cardFormName = parent.getName() + StringUtil.upFirst(SwEnum.PageType.CARD.value);
        if (listFormName.equals(bean.getName())) {
            ModelFormHelper.buildSaveModelByTmpl(bean, listTmpl);
        } else if (cardFormName.equals(bean.getName())) {
            ModelFormHelper.buildSaveModelByTmpl(bean, cardTmpl);
        }
    }

}
