package com.chushang.task.consumer;

import com.alibaba.fastjson2.JSON;
import com.chushang.common.core.constant.ServiceConstant;
import com.chushang.task.entity.TaskInfo;
import com.chushang.task.entity.dto.CreateTaskDTO;
import com.chushang.task.enums.TaskStatusEnum;
import com.chushang.task.service.TaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @auther: zhao
 * @date: 2024/6/12 15:03
 * 后台任务队列 --> 此处用于创建以及修改后台任务
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = ServiceConstant.TASK, consumerGroup = ServiceConstant.TASK_CONSUMER_GROUP)
public class TaskConsumerService implements RocketMQListener<CreateTaskDTO> {

    @Resource
    TaskInfoService taskInfoService;

    @Override
    public void onMessage(CreateTaskDTO task) {
        log.info("创建后台任务 {}", JSON.toJSONString(task));
        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);
        }
    }
}
