package com.njzscloud.common.sichen.support;

import cn.hutool.core.util.IdUtil;
import com.njzscloud.common.core.tuple.Tuple2;
import com.njzscloud.common.sichen.contant.TaskStatus;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

@Getter
@Setter
@Slf4j
@Accessors(chain = true)
public class TaskHandle implements Runnable {
    private Long taskId;
    private Long scheduleId;
    private String memo;

    private String fname;
    private Tuple2<Object, Method> fn;
    private TaskStatus status;
    private Long startTime;
    private Long endTime;

    public TaskHandle(TaskInfo taskInfo) {
        this.taskId = taskInfo.getId();
        this.scheduleId = IdUtil.getSnowflakeNextId();
        this.memo = taskInfo.getMemo();
        this.status = TaskStatus.Waiting;
        this.fname = taskInfo.getFn();
        this.fn = Cable.getFn(this.fname);
    }

    @Override
    public void run() {
        if (status != TaskStatus.Pending) {
            return;
        }
        status = TaskStatus.Running;
        startTime = System.currentTimeMillis();
        try {
            if (fn == null) {
                status = TaskStatus.Error;
                log.error("任务执行失败：{}，任务处理函数不存在：{}", memo, fname);
            }
            fn.get_1().invoke(fn.get_0());
            status = TaskStatus.Completed;
        } catch (Throwable e) {
            status = TaskStatus.Error;
            log.error("任务执行失败：{}", memo, e);
        } finally {
            endTime = System.currentTimeMillis();
            Cable.report(this);
        }
    }

    @Override
    public String toString() {
        return "TaskHandle{" +
                "taskId=" + taskId +
                ", scheduleId=" + scheduleId +
                ", taskName='" + memo + '\'' +
                ", fname='" + fname + '\'' +
                ", status=" + status +
                ", startTime=" + startTime +
                ", endTime=" + endTime +
                '}';
    }
}
