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

import cc.smtweb.framework.core.cache.AbstractCache;
import cc.smtweb.framework.core.cache.CacheManager;
import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityDao;
import cc.smtweb.framework.core.db.EntityHelper;
import cc.smtweb.framework.core.db.cache.ModelTableCache;
import cc.smtweb.framework.core.db.jdbc.IDbWorker;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.system.bpm.web.design.form.define.PageDataset;
import cc.smtweb.system.bpm.web.engine.dynPage.AbstractDynPageHandler;

/**
 * Created by Akmm at 2022/4/21 17:53
 * 模型删除handler
 */
public class ModelDelHandler extends AbstractDynPageHandler {
    private String cardDsName = ModelHelper.DATASET_NAME_CARD;

    public ModelDelHandler() {
    }

    public ModelDelHandler(String cardDsName) {
        this.cardDsName = cardDsName;
    }

    /**
     * 删除指定数据集，入参{pageId, dataset, id}
     *
     * @return
     */
    public R del() {
        long id = params.readLong("id");
        if (id == 0L) throw new BizException("没有收到待删除记录Id(" + id + ")！");
        //数据集
        PageDataset pageDataSet = findCardDataset(cardDsName);
        checkDel(pageDataSet,id);

        DbEngine.getInstance().doTrans(new IDbWorker() {
            @Override
            public void work() {
                ModelTable table = ModelTableCache.getInstance().get(pageDataSet.masterTable);
                if (table == null) throw new BizException("没有找到指定的的表定义：" + pageDataSet.name + "！");
                EntityDao dao = DbEngine.getInstance().findDao(table.getName());
                dao.deleteEntity(id);
                localDel(id, table);
            }

            @Override
            public void doAfterDbCommit() {
                ModelTable table = ModelTableCache.getInstance().get(pageDataSet.masterTable);
                if (table.isNeedCache()) {
                    AbstractCache cache = CacheManager.getIntance().getCache(table.getName());
                    cache.remove(id);
                }
                afterCommit(id, table);
            }

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

    //回调：：：删除之后
    protected void localDel(long id, ModelTable table) {
    }

    //回调：：：提交成功后
    protected void afterCommit(long id, ModelTable table) {
    }

    //回调：：：提交失败，事务回滚后
    protected void afterRollback(long id) {

    }

    /**
     * 删除校验
     *
     * @param pageDataSet
     * @param id
     */
    protected void checkDel(PageDataset pageDataSet, long id) {
        //校验外键引用关系
        EntityHelper.checkExists(pageDataSet.masterTable, id);
    }
}
