package cc.smtweb.framework.core.mvc.service;

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.jdbc.IDbWorker;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Akmm at 2022/3/2 19:44
 * 保存
 */
@Slf4j
@Deprecated
public abstract class AbstractSaveHandler<T> extends AbstractHandler {
    protected T bean;
    protected boolean isNew;

    public R save() {
        long id = readId();

        isNew = id <= 0L;
        if (isNew) {
            bean = createComp();
        } else {
            bean = loadComp(id);
        }
        readFromPage();
        if (isNew) {
            setNewId();
        }
        checkValid();
        DbEngine.getInstance().doTrans(new IDbWorker() {
            @Override
            public void work() {
                saveDb();
            }

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

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

    /**
     * 读取页面传回来的id
     *
     * @return
     */
    protected long readId() {
        return params.readLong("id", 0L);
    }

    protected abstract void setNewId();

    //从页面读取数据
    protected abstract void readFromPage();

    //保存前的校验
    protected abstract void checkValid();

    //保存到数据库
    protected abstract void saveDb();

    //保存成功之后
    protected void saveSuccess() {
    }

    //保存失败之后
    protected void saveFailed() {
    }

    //构建一个新对象
    protected abstract T createComp();

    //从数据库读取
    protected abstract T loadComp(long id);

    //树，改变父亲
    public abstract R changeParent();
}
