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;


@Service("generative-knowledge")
public class GenerativeKnowledgeTemplate implements BaseTemplate{

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

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

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

        // 根据content内容调用模版并返回结果
        synchronized (WebSocketClient.LOCK) {

            String prefix = "你的任务是[针对给定的文段提出" + (content.length() /100 + 1 ) + "个问题并回答]。文段为:[\"";
            String suffix = "\"]。输出为一个JSON数组[{}]，每个元素是一个JSON：{“question”:,”answer”:}。不要给出任何解释说明。";
            log.info(prefix + content + suffix);
            webSocketClient.sendMsg(prefix + content + suffix);
            try {
                WebSocketClient.LOCK.wait();
                String result = (String)redisTemplate.opsForValue().get("group:websocket:content");
                try {
                    JSONArray jsonArray = JSONArray.parseArray(result);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("questions",jsonArray);
                    return jsonObject;
                } catch (JSONException je) {
                    // 返回结果错误，计日志，存log，返回空结果
                    log.error(je.getMessage(),je);
                    return null;
                }

            } catch (InterruptedException e) {
                log.warn(e.getMessage());
            }
        }
        return null;
    }

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