package cn.com.capcloud.core.websocket;

import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.quartz.task.TaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 设置redis订阅发布接收者
 * @Author LiaoJiaHui
 * @Create 2024/3/20 14:23
 */

@Component
public class RedisSubscription implements MessageListener {

    @Resource
    private TaskService taskService;
    @Value("${rzth.isRunTask}")
    private String isRunTask;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel=new String(pattern);
        if(channel.equals("channel:message")){
            sendMessage(message);
        }
        if(channel.equals("channel:task")){
            if(isRunTask.equals("Y")){
                runTask(message);
            }
        }
        if(channel.equals("channel:updateTaskStatus")){
            if(isRunTask.equals("Y")){
                updateTaskStatus(message);
            }
        }
    }
    public void sendMessage(Message message){
        String messageBody = new String(message.getBody());
        JackJSONObject messageObject = JackJSONObject.fromObject(messageBody);
        String userId = String.valueOf(messageObject.get("userId"));
        String content = String.valueOf(messageObject.get("content"));
        WebSocket.sendMessageById(content,userId);
    }
    public void runTask(Message message){
        taskService.runTask(message);
    }
    public void updateTaskStatus(Message message){
        taskService.updateTaskStatus();
    }
}
