package cc.smtweb.system.bpm.web.sys.oneTimeService;


import cc.smtweb.framework.core.common.SwConsts;
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.jdbc.IDbWorker;

import java.util.List;

/**
 * Created by zhenggm at 2021-12-02 18:12:57
 * 实体【[系统一次性任务](TB_SYS_ONETIME_TASKS)】的数据库读写Dao类
 */
public final class OnetimeTaskHelper {
    //服务器编号
    private int runServer = SwConsts.SysParam.machineId;
    private EntityDao<OnetimeTask> dao;

    public OnetimeTaskHelper(int runServer, EntityDao<OnetimeTask> dao) {
        this.runServer = runServer;
        this.dao = dao;
    }

    //获取所有等待中的任务，服务启动时执行一次
    public List<OnetimeTask> findWaiting() {
        return dao.queryWhere(" sot_run_server=? and sot_statu < ?", runServer, OneTimeStatu.FAILED.value);
    }

    public OnetimeTask findOneByTk(String type, String key) {
        return dao.queryEntityWhere(" sot_type=? and sot_code=?", type, key);
    }

    public boolean isExistByKey(String type, String key) {
        return DbEngine.getInstance().isExists("select sot_id from " + EntityHelper.getSchemaTableName(OnetimeTask.ENTITY_NAME) + " where sot_type=? and sot_code=?", type, key);
    }

    public void updateTask(OnetimeTask task) {
        if (task.isNew()) {
            task.setEntityId(DbEngine.getInstance().nextId());
            task.setRunServer(runServer);
            DbEngine.getInstance().doTrans(new IDbWorker() {
                @Override
                public void work() {
                    dao.insertEntity(task);
                }

                @Override
                public void doAfterDbRollback() {
                    task.setEntityId(0L);
                }
            });
        } else {
            DbEngine.getInstance().doTrans(new IDbWorker() {
                @Override
                public void work() {
                    task.setRunServer(runServer);
                    dao.updateEntity(task, "sot_begin_time,sot_end_time,sot_statu,sot_info,sot_process,sot_run_server");
                }
            });
        }
    }

    public void updatProcess(OnetimeTask task) {
        dao.updateEntity(task, "sot_process");
    }
}