package com.friday.distributor.queue;

import com.alibaba.fastjson.JSON;
import com.friday.distributor.constant.SysCode;
import com.friday.distributor.exception.DistributorRuntimeException;
import com.friday.distributor.mapper.JobInvokeMapper;
import com.friday.distributor.mapper.TaskInvokeMapper;
import com.friday.distributor.bean.Job;
import com.friday.distributor.bean.JobInvokeFilter;
import com.friday.distributor.bean.Task;
import com.friday.distributor.bean.TaskInvokeFilter;
import com.friday.distributor.po.JobInvoke;
import com.friday.distributor.po.TaskInvoke;
import com.friday.operation.api.distributor.dto.TaieJobDto;
import com.friday.operation.api.distributor.dto.TaieTaskDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author YaoYao
 * @Date Created In 10:47 2023/03/07
 * @Description 任务信息持久化相关
 * @Modified By
 */

@Service
@Slf4j
public class TaskPersistHelper {
    @Autowired
    private TaskInvokeMapper taskInvokeMapper;
    @Autowired
    private JobInvokeMapper jobInvokeMapper;

    public void insertOrUpdateTaskRecord(Task task){
        try {
            if (Objects.isNull(taskInvokeMapper.selectTaskByTaskId(task.getTaskId()))) {
                taskInvokeMapper.insertTaskInvoke(TaskInvoke.builder()
                        .taieTenant(task.getTaieTenant())
                        .taskType(task.getTaskType())
                        .bizType(task.getBizType())
                        .taskId(task.getTaskId())
                        .taskVersion(task.getTaskVersion())
                        .taskInput(task.getTaskInput())
                        .taskState(task.getState())
                        .operator(task.getOperator())
                        .sysCode(StringUtils.isEmpty(task.getSysCode()) ? SysCode.TASK_DISTRIBUTOR.getSysCode() : task.getSysCode())
                        .build());
            } else {
                taskInvokeMapper.updateTaskInvoke(TaskInvoke.builder()
                        .taskId(task.getTaskId())
                        .taskState(task.getState())
                        .build());
            }
        } catch (Exception e){
            log.error("任务数据落库失败:taskId={}", task.getTaskId(), e);
        }
    }

    public void insertOrUpdateJobRecord(Job job){
        try {
            if (Objects.isNull(job.getInvokeId())) {
                JobInvoke invoke = JobInvoke.builder()
                        .taieTenant(job.getTaieTenant())
                        .taskType(job.getTaskType())
                        .bizType(job.getBizType())
                        .taskId(job.getTaskId())
                        .jobInput(JSON.toJSONString(job.getJobInput()))
                        .jobOutput(job.getJobOutput())
                        .jobState(job.getState())
                        .failMsg(job.getFailMsg())
                        .remark(job.getRemark())
                        .build();
                jobInvokeMapper.insertJobInvoke(invoke);
                job.setInvokeId(invoke.getId());
            } else {
                String execRobotName = null;
                if(Objects.nonNull(job.getExecRobot()) && StringUtils.isNotEmpty(job.getExecRobot().getMachineName())){
                    execRobotName = job.getExecRobot().getMachineName();
                }
                jobInvokeMapper.updateJobInvoke(JobInvoke.builder()
                        .id(job.getInvokeId())
                        .startTime(job.getJobStartTime())
                        .endTime(job.getJobEndTime())
                        .execJobId(job.getExecJobId())
                        .execTaieRobot(execRobotName)
                        .jobInput(JSON.toJSONString(job.getJobInput()))
                        .jobOutput(job.getJobOutput())
                        .jobState(job.getState())
                        .failMsg(job.getFailMsg())
                        .remark(job.getRemark())
                        .build());
            }
        } catch (Exception e){
            log.error("子任务数据落库失败:taskId={},invokeId={}", job.getTaskId(), job.getInvokeId(), e);
        }
    }

    public void updateTaskInvoke(TaskInvoke invoke){
        taskInvokeMapper.updateTaskInvoke(invoke);
    }

    public void updateJobInvoke(JobInvoke invoke){
        jobInvokeMapper.updateJobInvoke(invoke);
    }

    public TaieTaskDto getTaskFrameData(String taskId){
        TaskInvoke invoke = taskInvokeMapper.selectTaskByTaskId(taskId);
        if(Objects.isNull(invoke)){
            throw new DistributorRuntimeException("查询任务详情为空,taskId = ", taskId);
        }
        return invoke.transferToTaieTaskDto();
    }

    public TaieJobDto getJobFrameData(Integer invokeId){
        JobInvoke invoke = jobInvokeMapper.selectJobById(invokeId);
        if(Objects.isNull(invoke)){
            throw new DistributorRuntimeException("查询子任务详情为空,invokeId = " + invokeId);
        }
        return invoke.transferToTaieJobDto();
    }

    public List<TaieJobDto> getJobFrameDataList(String taskId){
        List<JobInvoke> invokes = jobInvokeMapper.selectJobByTaskId(taskId);
        return invokes.stream().map(JobInvoke::transferToTaieJobDto).collect(Collectors.toList());
    }

    public List<JobInvoke> getJobsByTaskId(String taskId){
        return jobInvokeMapper.selectJobByTaskId(taskId);
    }

    public TaskInvoke getTaskInvokeByTaskId(String taskId) {
        return taskInvokeMapper.selectTaskByTaskId(taskId);
    }

    public List<TaskInvoke> selectTaskInvokes(TaskInvokeFilter filter) {
        return taskInvokeMapper.selectTasks(filter);
    }

    public List<JobInvoke> selectJobInvokes(JobInvokeFilter filter){
        return jobInvokeMapper.selectJobs(filter);
    }

}
