package com.chushang.task.remote;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chushang.common.core.web.Result;
import com.chushang.common.mq.produce.MqProduceService;
import com.chushang.task.entity.TaskInfo;
import com.chushang.task.entity.dto.CreateTaskDTO;
import com.chushang.task.entity.dto.UpdateTaskDTO;
import com.chushang.task.enums.TaskStatusEnum;
import com.chushang.task.feign.RemoteTaskService;
import com.chushang.task.service.TaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @auther: zhao
 * @date: 2024/6/11 10:28
 */
@Slf4j
@RestController
@RequestMapping(value = "/remote")
public class RemoteTaskController implements RemoteTaskService {

    @Resource
    TaskInfoService taskInfoService;
    /**
     * 创建 后台任务
     */
    @Override
    @PostMapping("/create")
    public Result<Long> createTask(@RequestBody CreateTaskDTO task, String source) {
        TaskInfo taskInfo = TaskInfo.builder()
                .applicationName(task.getApplicationName().getServiceName())
                .className(task.getClassName())
                .methodName(task.getMethodName())
                .params(task.getParams())
                .taskStatus(TaskStatusEnum.CREATE.getCode())
                .deptId(task.getDeptId())
                .taskType(task.getTaskType().getCode())
                .taskName(task.getTaskName())
                .build();
        taskInfo.setCreateBy(task.getCreateBy());
        boolean save = taskInfoService.save(taskInfo);
        // 如果 入库成功, 则将其发送到消息队列中
        if (save){
            log.info("消息发送队列 {}", taskInfo.getTaskId());
            taskInfoService.joinQueue(taskInfo);
        }
        return Result.ok(save ? taskInfo.getTaskId() : null);
    }

    @Override
    @PostMapping(value = "/{taskId}")
    public Result<Boolean> updateTask(@PathVariable Long taskId,
                                      @RequestBody UpdateTaskDTO task, String source)
    {
        TaskInfo taskInfo = TaskInfo.builder()
                .taskId(taskId)
                .taskStatus(task.getTaskStatus().getCode())
                .lastRunResult(task.getLastRunResult())
                .lastRunTime(task.getLastRunTime())
                .remark(task.getRemark())
                .lastRunTime(task.getLastRunTime())
                .lastRunResult(task.getLastRunResult())
                .build();
        taskInfo.setUpdateBy("system");
        return Result.ok(taskInfoService.update(taskInfo, new LambdaUpdateWrapper<TaskInfo>()
                .eq(TaskInfo::getTaskId, taskId)));
    }
}
