package com.xueyi.nlt.nlt.template;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.xueyi.nlt.netty.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("free-chat")
public class FreeChatTemplate implements BaseTemplate{

    private static final Logger log = LoggerFactory.getLogger(FreeChatTemplate.class);
    @Autowired
    WebSocketClient webSocketClient;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public JSONObject handle(String devId, String content) {

        // 根据content内容调用模版并返回结果
        synchronized (WebSocketClient.LOCK) {
            // 通过redis获取数字人上下文信息
            Long size = redisTemplate.opsForList().size("group:device:" + devId);
            if (size > 8) {
                redisTemplate.opsForList().leftPop("group:device:" + devId,2);
            }
            redisTemplate.opsForList().rightPush("group:device:" + devId,content);
            List<String> context = redisTemplate.opsForList().range("group:device:" + devId,0,size);
            String prefix = "你的任务是[针对给定的文段提出" + (content.length() /100 + 1 ) + "个问题并回答]。文段为:[\"";
            String suffix = "\"]。输出为一个JSON数组[{}]，每个元素是一个JSON：{“question”:,”answer”:}。不要给出任何解释说明。";
            log.info(prefix + content + suffix);
//            webSocketClient.sendMsg(prefix + content + suffix);
            webSocketClient.sendMsg(context);
            try {
                WebSocketClient.LOCK.wait();
                String result = (String)redisTemplate.opsForValue().get("group:websocket:content");
                redisTemplate.opsForList().rightPush("group:device:" + devId,result);
                JSONObject resultJson = new JSONObject();
                resultJson.put("msg",result);
                return resultJson;
            } catch (InterruptedException e) {
                log.warn(e.getMessage());
            }
        }
        return null;
    }

    @Override
    public JSONObject handle(String dev, String content, Long tenantId) {
        return null;
    }
}