package com.fs.app.service.impl;
import com.fs.app.service.AiSendService;
import com.fs.app.websocket.service.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AiSendServiceImpl implements AiSendService {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    WebSocketServer webSocketServer;

    @Override
    @Async
    public void sendHookMsg(String key) {
        String s = redisTemplate.opsForValue().get("AiMsgSend:" + key);
        if (s!=null&& !s.equals("")){
            System.out.println("有正在处理的线程跳过");
        }else {
            sendMsg(key);
        }
    }


    public void sendMsg(String key){
        try {
            Thread.sleep(1000); // 5000 毫秒 = 5 秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String message = redisTemplate.opsForList().rightPop("AiMsg:"+key);
        if (message!=null&&message!=""){
            redisTemplate.opsForValue().set("AiMsgSend:" + key, "1", 1, TimeUnit.MINUTES);
            addWebSocketMsg(key,message);
            sendMsg(key);
        }else {
            redisTemplate.delete("AiMsgSend:" + key);
        }
    }


    public  void addWebSocketMsg(String key,String sendAIParam){
        System.out.println("发送消息:"+key);
        webSocketServer.sendInfo(key, sendAIParam);
    }

}
