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

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 cc.smtweb.system.bpm.web.design.form.model.ModelFactory;
import org.apache.commons.lang3.StringUtils;

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

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

    public ModelFormSaveHandler() {
        super(ModelForm.ENTITY_NAME);
    }

    @Override
    protected void updateBean(EntityDao<ModelForm> dao) {
        listFormChild = new ArrayList<>();
        ModelFactory.getInstance().saveForm(bean, listFormChild);
        dao.updateEntityEx(bean, "mf_content", "mf_dataset", "mf_tmpl");
    }

    @Override
    protected void insertBean(EntityDao<ModelForm> dao) {
        listFormChild = new ArrayList<>();
        ModelFactory.getInstance().saveForm(bean, listFormChild);
        super.insertBean(dao);
    }

    @Override
    protected void checkValid() {
        super.checkValid();
        DbEngine.getInstance().findDao(ModelForm.class).checkUnique(bean, "mf_prj_id", "mf_name");
    }

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

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

    public R saveDataset() {
        long id = params.readLong("id");
        String data = params.readString("data");
        bean = ModelFormCache.getInstance().get(id);
        if (StringUtils.isEmpty(data)) {
            throw new BizException("没有待保存的数据！");
        }
        bean.setDataset(ModelFormHelper.buildSaveDataset(data));
        DbEngine.getInstance().doTrans(new IDbWorker() {
            @Override
            public void work() {
                EntityDao<ModelForm> 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());
                dao.updateEntity(bean, "mf_dataset");
            }

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

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

    public R saveModel() {
        long id = params.readLong("id");
        String data = params.readString("data");
        bean = ModelFormCache.getInstance().get(id);
        if (StringUtils.isEmpty(data)) {
            throw new BizException("没有待保存的数据！");
        }
        bean.setContent(ModelFormHelper.buildSaveModel(bean, data));
        DbEngine.getInstance().doTrans(new IDbWorker() {
            @Override
            public void work() {
                EntityDao<ModelForm> 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());
                dao.updateEntity(bean, "mf_content");
            }

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

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

    public R saveModelByTmpl() {
        String id = params.readString("pageId");
        String data = params.readString("data");
        bean = ModelFormHelper.getFromCache(id);
        if (StringUtils.isEmpty(data)) {
            throw new BizException("没有待保存的数据！");
        }
        bean.setTmpl(data);
        ModelFactory.getInstance().buildSaveModel(bean);
        //先构建一次，防止有错
        String ret = ModelFormHelper.buildReqModel(bean);
//        ModelFormHelper.buildSaveModelByTmpl(bean, templateId);
        DbEngine.getInstance().doTrans(new IDbWorker() {
            @Override
            public void work() {
                EntityDao<ModelForm> 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());
                dao.updateEntity(bean, "mf_content,mf_tmpl");
            }

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

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