package com.friday.distributor.bean;

import com.alibaba.fastjson.annotation.JSONField;
import com.friday.blank.api.dto.taskType.TaskTypeDetailDto;
import com.friday.distributor.constant.Events;
import com.friday.distributor.constant.States;
import com.friday.operation.api.distributor.bean.BaseTask;
import com.friday.operation.api.distributor.dto.StandardJobConfigParam;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.statemachine.StateMachine;

import java.util.List;
import java.util.Objects;

/**
 * @Author YaoYao
 * @Date Created In 19:28 2022/2/23
 * @Description Task类
 * @Modified By
 */
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Task extends BaseTask {
    //TAIE租户
    private String taieTenant;
    //任务类型
    private String bizType;
    //队列key
    private String queueKey;
    //任务ID
    private String taskVersion;
    //任务描述
    private String description;
    //任务状态
    private String state;
    //管理端任务运行参数
    private TaskTypeDetailDto taskExecConfig;
    //子任务
    private List<Job> jobs;
    //启动信息
    private String taskInput;
    //是否异步实时启动
    private boolean direct;
    //平台配置入参
    private StandardJobConfigParam configParam;

    //状态机
    @JSONField(serialize = false)
    private StateMachine<States.TaskState, Events.TaskEvent> stateMachine;

    public String getUniqueKey() {
        return String.join("-", taieTenant, taskType, super.getTaskId());
    }

    public boolean done(){
        return stateMachine.getState().getId().equals(States.TaskState.EXECUTED);
    }

    public boolean undone(){
        return stateMachine.getState().getId().equals(States.TaskState.UNEXECUTED) ||
                stateMachine.getState().getId().equals(States.TaskState.EXECUTING);
    }

    public boolean syncStart(){
        return Objects.nonNull(taskExecConfig) && taskExecConfig.getSchedule().getIsSync();
    }

    public boolean defaultExec(){
        return Objects.nonNull(taskExecConfig) && Objects.isNull(taskExecConfig.getRelatedProcess());
    }

    public BaseTask transferToBaseTask(){
        return BaseTask.builder()
                .taskType(taskType)
                .taskId(taskId)
                .bizParam(bizParam)
                .operator(operator)
                .sysCode(sysCode)
                .build();
    }
}
