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

import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.jdbc.IDbWorker;
import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.framework.core.util.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Akmm at 2018/11/27 23:46
 * 系统任务基类
 */
@Slf4j
public class OneTimeSysService implements Runnable {
    private OnetimeTask task;

    public OneTimeSysService(OnetimeTask task) {
        this.task = task;
    }


    @Override
    public void run() {
        long time = System.currentTimeMillis();
        try {
            log.debug(task.getName() + ":::开始执行.........");
            BaseOneTimeHandler handler = OneTimeServiceFactory.getInstance().getHandle(task.getType());
            handler.setParams(task.getInparams());
            handler.setService(this);

            task.setBeginTime(DateUtil.nowDateTimeLong());
            task.setStatu(OneTimeStatu.RUNNING.value);
            task.setInfo(null);
            task.setProcess(0);
            OneTimeServiceFactory.getInstance().getTasksHelper().updateTask(task);

            handler.work();

            task.setEndTime(DateUtil.nowDateTimeLong());
            task.setStatu(OneTimeStatu.SUCCESS.value);
            task.setProcess(100);
            OneTimeServiceFactory.getInstance().getTasksHelper().updateTask(task);

            log.debug(task.getName() + ":::执行完成，耗时：" + (System.currentTimeMillis() - time) + "毫秒.........");
        } catch (Exception e) {
            task.setEndTime(DateUtil.nowDateTimeLong());
            task.setStatu(OneTimeStatu.FAILED.value);
            task.setInfo(CommUtil.getOrigMsg(e));

            try {
                OneTimeServiceFactory.getInstance().getTasksHelper().updateTask(task);
            } catch (Exception exception) {
                log.error("更新任务状态失败", e);
            }
            log.error(task.getName() + ":::执行失败", e);
        }
    }

    //回写进度，百分比
    protected void setProcess(int process) throws Exception {
        if (task.getProcess() != process) {
            task.setProcess(process);
            DbEngine.getInstance().doTransSingle(new IDbWorker() {
                @Override
                public void work() {
                    OneTimeServiceFactory.getInstance().getTasksHelper().updatProcess(task);
                }
            });

        }
    }
}
