package com.mortals.xhx.thread;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mortals.xhx.webflux.factory.FlowChatContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * 机器人响应消息
 *
 * @author: zxfei
 * @date: 2025/3/19 20:36
 */
@AllArgsConstructor
@Slf4j
public class ChatMsgRspThread implements Runnable {


    private FlowChatContext context;

    /**
     * 最大重试次数
     */
    public final Integer MAX_RETRY_COUNT = 10;


    @Override
    public void run() {
        log.info("快速响应线程开始，msgId:{}", context.getMsgId());
        StringBuilder answer = context.getAnswer();
        int reCount = 0;
        while (reCount < MAX_RETRY_COUNT) {
            if (!answer.toString().isEmpty()) {
                log.info("快速响应线程结束 answer:{}", answer);
                break;
            }
            //创建一个初始化的answer
            JSONObject rspJson = new JSONObject();
            rspJson.put("id", context.getMsgId());
            rspJson.put("created", new Date().getTime());
            rspJson.put("model", "");

            JSONArray jsonArray = new JSONArray();
            JSONObject obj = new JSONObject();

            JSONObject delta = new JSONObject();
            delta.put("role", "");
            if (reCount == 0) {
                delta.put("role", "assistant");
            }
            delta.put("content", "");
            obj.put("delta", delta);

            obj.put("index", 0);
            obj.put("finish_reason", null);

            jsonArray.add(obj);
            rspJson.put("choices", jsonArray);
            rspJson.put("object", "");


            log.info("快速响应线程写入数据，rsp:{}", rspJson.toJSONString(rspJson,SerializerFeature.WriteMapNullValue));
           // context.getEmitter().next("data:"+rspJson.toJSONString());
            context.getEmitter().next(rspJson.toJSONString(rspJson,SerializerFeature.WriteMapNullValue));
            reCount++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptedException) {
            }
        }


    }


}
