package cc.smtweb.system.bpm.web.engine.model.common;

import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.mvc.service.SwListData;
import cc.smtweb.framework.core.util.DateUtil;
import cc.smtweb.system.bpm.web.engine.dynPage.DynRetBean;
import cc.smtweb.system.bpm.web.engine.flow.FlowHelper;
import cc.smtweb.system.bpm.web.engine.flow.FlowInstance;
import cc.smtweb.system.bpm.web.engine.flow.FlowListener;

/**
 * Created by Akmm at 2022-08-26 16:47
 * 带流程的简单卡片之保存
 */
public class FlowModelSaveHandler<T extends DefaultEntity> extends ModelSaveHandler<T> implements FlowListener {
    public FlowModelSaveHandler() {
    }

    public FlowModelSaveHandler(String cardDsName) {
        super(cardDsName);
    }

    protected FlowInstance flowInstance;
    @Override
    protected void readFromPage(SwMap pageData, SwMap filter) {
        super.readFromPage(pageData, filter);

        long id = params.readLong("id");
        long taskId = params.readLong("taskId");

        SwMap data = pageData.readMap(FlowHelper.DATASET_NAME_FLOW);
        if (data == null) throw new BizException("没有找到待保存的流程数据！");
        data = data.readMap("form");
        if (data == null) throw new BizException("没有找到待保存的流程数据！");

        if (bean.isNew()) {
            flowInstance = FlowInstance.createByBillType(us, this, form.getBillType());
        } else {
            flowInstance = FlowInstance.createById(us, this, id, taskId);
        }
        flowInstance.readFromPage(data);
        flowInstance.getProcInst().setIsNew(bean.isNew());
        if (bean.isNew()) {
            flowInstance.getProcInst().setBillCode(getBillCode());
            flowInstance.getProcInst().setUrl(getBillUrl());
        }
        flowInstance.getProcInst().setBillInfo(getBillInfo());
    }

    @Override
    protected void doSave() {
        super.doSave();
        flowInstance.save();
    }

    @Override
    protected void afterSave(SwMap ret) {
        super.afterSave(ret);
        flowInstance.setPageRetExtra(ret);
        ret.put(FlowHelper.DATASET_NAME_FLOW, DynRetBean.createBean(flowInstance.getProcInst()));
        ret.put(FlowHelper.DATASET_NAME_COMMENT, DynRetBean.createList(SwListData.EMPTY));
    }

    //单据编号，新增保存时调用
    protected String getBillCode() {
        return flowInstance.getProcInst().getBillCode();
    }

    //单据信息，在待办中显示，每次保存均计算
    protected String getBillInfo() {
        return flowInstance.getProcInst().getBillCode() + "-" + DateUtil.nowDate();
    }

    //单据url，待办中跳链
    protected String getBillUrl() {
        return "";
    }
}
