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

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityDao;
import cc.smtweb.framework.core.db.cache.ModelTableCache;
import cc.smtweb.framework.core.db.jdbc.IDbWorker;
import cc.smtweb.framework.core.db.vo.ModelField;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.mvc.service.DefaultSaveHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Created by Akmm at 2022/5/9 17:05
 * 页面定义保存，注意不要覆盖content和dataset
 */
public class ModelProcSaveHandler extends DefaultSaveHandler<ModelProc> {
    //自动生成的模块子页面，暂存，便于维护缓存
    private List<ModelProc> listFormChild;

    public ModelProcSaveHandler() {
        super(ModelProc.ENTITY_NAME);
    }

    @Override
    protected void updateBean(EntityDao<ModelProc> dao) {
        dao.updateEntityEx(bean, "prc_content");
    }

    @Override
    protected void insertBean(EntityDao<ModelProc> dao) {
        super.insertBean(dao);
    }


    @Override
    protected void saveSuccess() {
        ModelProcCache.getInstance().put(bean);
        if (listFormChild != null) {
            for (ModelProc page : listFormChild) {
                ModelProcCache.getInstance().put(page);
            }
        }
    }

    @Override
    protected void saveFailed() {
        ModelProcCache.getInstance().reset(bean);
        if (listFormChild != null) {
            for (ModelProc page : listFormChild) {
                ModelProcCache.getInstance().reset(page);
            }
        }
    }

    public R saveModel() {
        long id = params.readLong("id");
        String data = params.readString("data");
        bean = ModelProcCache.getInstance().get(id);
        if (StringUtils.isEmpty(data)) {
            throw new BizException("没有待保存的数据！");
        }
        bean.setContent(data);
        DbEngine.getInstance().doTrans(new IDbWorker() {
            @Override
            public void work() {
                EntityDao<ModelProc> dao = DbEngine.getInstance().findDao(tableName);

                ModelTable table = ModelTableCache.getInstance().getByName(tableName);
                ModelField field = table.findFieldByType(SwEnum.FieldType.UPDATE_USER.value);
                if (field != null) bean.put(field.getName(), us.getUserId());
                bean.clear();
                dao.updateEntity(bean, "prc_content");
            }

            @Override
            public void doAfterDbCommit() {
                saveSuccess();
            }

            @Override
            public void doAfterDbRollback() {
                saveFailed();
            }
        });
        return R.success();
    }
}
