package com.ruoyi.interfaces.domain;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.utils.JsonUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

/**
 * entity:MdModelStepExecution
 *
 * @author lql
 * @date 2025-7-15
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName
public class MdModelStepExecution implements Serializable {

    // 步骤执行状态
    public enum StepStatus {
        PENDING,      // 待执行
        RUNNING,      // 执行中
        SUCCESS,      // 成功
        FAILED,       // 失败
        SKIPPED,      // 已跳过
        RETRYING      // 重试中
    }

    @TableId
    private Long id;
    private Long executionId;
    private Long stepId;
    @ApiModelProperty("步骤名称")
    private String stepName;
    @ApiModelProperty("步骤类型")
    private MdModelStep.StepType stepType;
    @ApiModelProperty("状态")
    private StepStatus status;
    @ApiModelProperty("步骤输入")
    private String input;
    @ApiModelProperty("步骤输出")
    private String output;
    @ApiModelProperty("错误信息")
    private String errorMsg;
    @ApiModelProperty("重试次数")
    private int retryCount = 0;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty("开始时间")
    private Date startTime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty("结束时间")
    private Date endTime;
    @ApiModelProperty("耗时(毫秒)")
    private long duration;

    // 标记步骤开始
    public void markStart() {
        this.status = StepStatus.RUNNING;
        this.startTime = new Date();
    }

    // 标记步骤成功
    public void markSuccess(Map<String, Object> output) {
        this.status = StepStatus.SUCCESS;
        this.output = JsonUtils.objectToJson(output);
        this.endTime = new Date();
        this.duration = endTime.getTime() - startTime.getTime();
    }

    // 标记步骤失败
    public void markFailed(String errorMsg) {
        this.status = StepStatus.FAILED;
        this.errorMsg = errorMsg;
        this.endTime = new Date();
        this.duration = endTime.getTime() - startTime.getTime();
    }

    // 标记步骤跳过
    public void markSkipped() {
        this.status = StepStatus.SKIPPED;
        this.endTime = new Date();
        if (startTime != null) {
            this.duration = endTime.getTime() - startTime.getTime();
        }
    }

    // 增加重试次数
    public void increaseRetryCount() {
        this.retryCount++;
        this.status = StepStatus.RETRYING;
    }

    // 是否成功
    public boolean isSuccess() {
        return StepStatus.SUCCESS.equals(status);
    }

    // 是否失败
    public boolean isFailed() {
        return StepStatus.FAILED.equals(status);
    }

}
