package com.infoepoch.pms.dispatchassistant.controller.langchain;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.infoepoch.pms.dispatchassistant.common.component.BaseController;
import com.infoepoch.pms.dispatchassistant.common.component.RedisTool;
import com.infoepoch.pms.dispatchassistant.common.component.Result;
import com.infoepoch.pms.dispatchassistant.common.exception.NotLoginException;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.common.utils.DateTool;
import com.infoepoch.pms.dispatchassistant.common.utils.JsonUtils;
import com.infoepoch.pms.dispatchassistant.controller.basic.Auth;
import com.infoepoch.pms.dispatchassistant.controller.system.DictTypeConstants;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import com.infoepoch.pms.dispatchassistant.domain.langchain.ChatMessage;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.ChatResponse;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.ChatService;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatSuccessResponse;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatResponse;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.Conversations;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.IMessagesRepository;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.Messages;
import com.infoepoch.pms.dispatchassistant.domain.langchain.qwen.QwenLine;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.Conversation;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.ConversationCriteria;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.ConversationService;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.HttpClientPoolConfig;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.line.*;
import com.infoepoch.pms.dispatchassistant.domain.system.dict.DictDataService;
import com.infoepoch.pms.dispatchassistant.domain.system.dict.SystemDictData;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.PreDestroy;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/langchain")
public class LangChainController extends BaseController {


    @Autowired
    private Auth auth;

    @Autowired
    private ChatService chatService;
    @Autowired
    private ConversationService conversationService;
    @Autowired
    private ConversationLineService conversationLineService;
    @Autowired
    private DictDataService dictDataService;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisTool redisTool;
    @Autowired
    private HttpClientPoolConfig httpClientPool;


    private static final Logger logger = LoggerFactory.getLogger(LangChainController.class);

    /**
     * 新增会话
     * @param conversation
     * @return
     * @throws NotLoginException
     */
    @PostMapping("/add-conversation")
    public Result addConversation(@RequestBody Conversation conversation) throws NotLoginException {
        if(StringUtils.isBlank(conversation.getType()))
            throw new ValidationException("会话类型不可为空");
        User user = auth.getUserReq();
        conversationService.save(conversation, user);
        return Result.successData(conversation);
    }

    /**
     * 通用对话请求
     *
     * @param chatMessage
     * @return
     */
    @PostMapping("/common-chat")
    public Result commonChat(@RequestBody ChatMessage chatMessage) {
        // 请求AI服务接口
        ChatResponse response = null;
        if (StringUtils.isBlank(chatMessage.getType())) {
            throw new ValidationException("对话类型不可为空");
        }
        List<String> allowTypeList = Arrays.asList("chat", "knowledge", "fast");
        if (!allowTypeList.contains(chatMessage.getType())) {
            throw new ValidationException("对话类型不合法");
        }
        if (chatMessage.getType().equals("chat")) {
            ChatRequest request = new ChatRequest(
                    chatMessage.getMessage(),
                    chatMessage.getConversationId(),
                    false,
                    "chatglm3-6b",
                    new BigDecimal("0.7"),
                    0,
                    "default"
            );
            List<ConversationLine> historyList = conversationService.queryConversationHistory(chatMessage.getConversationId(), 3);
            for (ConversationLine line : historyList) {
                request.addHistory("user", line.getQuery());
                request.addHistory("assistant", line.getAnswer());
            }
            String result = chatService.chat(request);
            ChatSuccessResponse chatSuccessResponse = JsonUtils.jsonToObject(result, ChatSuccessResponse.class);
            response = new ChatResponse(
                    "chat",
                    chatSuccessResponse.getText(),
                    null
            );
            // 存储对话记录
            conversationService.saveLine(chatMessage, request, response, result);
        } else if (chatMessage.getType().equals("knowledge")) {
            KnowledgeBaseChatRequest request = new KnowledgeBaseChatRequest(
                    chatMessage.getMessage(),
                    "jiangsu",
                    3,
                    1,
                    false,
                    "chatglm3-6b",
                    new BigDecimal("0.7"),
                    0,
                    "default"
            );
            String result = chatService.knowledgeChat(request);
            KnowledgeBaseChatResponse knowledgeBaseChatResponse = JsonUtils.jsonToObject(result, KnowledgeBaseChatResponse.class);
            response = new ChatResponse(
                    "knowledge",
                    knowledgeBaseChatResponse.getAnswer(),
                    knowledgeBaseChatResponse.getDocs()
            );
            // 存储对话记录
            conversationService.saveLine(chatMessage, request, response, result);
        }
        // 返回结果
        if (response == null) {
            return Result.error(-1, "获取对话结果失败");
        }
        return Result.successData(response);
    }


    /**
     * 通用对话请求
     *
     * @param chatMessage
     * @return
     */
    @PostMapping("/queryAnswer")
    public Result queryAnswer(@RequestBody String chatMessage) {
        // 请求AI服务接口
        String result="";
        result=conversationService.queryAnswer(chatMessage);
        return Result.successData(result);
    }



    /**
     * 会话类型列表
     *
     * @return
     */
    @GetMapping("/type-list")
    public Result typeList() {
        // 根据字典类型查询系统字典数据
        List<SystemDictData> dictDataList = dictDataService.queryByDictType(DictTypeConstants.CONVERSATION_TYPE);
        // 返回查询结果
        return Result.successData(dictDataList);
    }

    /**
     * 会话列表
     *
     * @param type
     * @return
     */
    @GetMapping("/conversation-list/{type}")
    public Result conversationList(@PathVariable String type) throws NotLoginException {
        User user = auth.getUserReq();
        ConversationCriteria criteria = new ConversationCriteria();
        criteria.setType(type);
        criteria.setUserId(user.getId());
        List<Conversation> conversationList = conversationService.list(criteria);
        return Result.successData(conversationList);
    }

    /**
     * 会话记录列表
     *
     * @param conversationId
     * @return
     */
    @GetMapping("/conversation-history/{conversationId}")
    public Result conversationHistory(@PathVariable String conversationId) {
        ConversationLineCriteria criteria = new ConversationLineCriteria();
        criteria.setConversationId(conversationId);
        List<ConversationLine> conversationHistory = conversationLineService.list(criteria);
        return Result.successData(conversationHistory);
    }

    /**
     * @param message
     * @return
     */
    @PostMapping("/chat")
    public Result chat(String message) {
        ChatRequest request = new ChatRequest(
                message,
                "1",
                false,
                "chatglm3-6b",
                new BigDecimal("0.7"),
                0,
                "default"
        );
        String result = chatService.chat(request);
        ChatSuccessResponse chatSuccessResponse = JsonUtils.jsonToObject(result, ChatSuccessResponse.class);
        ChatResponse response = new ChatResponse(
                "chat",
                chatSuccessResponse.getText(),
                null
        );
        return Result.successData(response);
    }

    /**
     * @param message
     * @return
     */
    @PostMapping("/knowledge-chat")
    public Result knowledgeChat(String message) {
        KnowledgeBaseChatRequest request = new KnowledgeBaseChatRequest(
                message,
                "jiangsu",
                3,
                1,
                false,
                "chatglm3-6b",
                new BigDecimal("0.7"),
                0,
                "default"
        );
        String result = chatService.knowledgeChat(request);
        KnowledgeBaseChatResponse knowledgeBaseChatResponse = JsonUtils.jsonToObject(result, KnowledgeBaseChatResponse.class);
        ChatResponse response = new ChatResponse(
                "knowledge",
                knowledgeBaseChatResponse.getAnswer(),
                knowledgeBaseChatResponse.getDocs()
        );
        return Result.successData(response);
    }

    //调用智能体
    @GetMapping("/sseIntelligent")
    public ResponseEntity<SseEmitter> sse(@RequestParam String  chatMessage,@RequestParam String dialogId,
                                          @RequestParam String selectedExpert ,@RequestParam String selectedOrg)  {
        String condition="";
        String regionName= chatService.getAuthRegionName();
        if("内部专家".equals(selectedExpert)) {
            if ("组织内".equals(selectedOrg) && StringUtils.isNotEmpty(regionName)) {
                condition = ",只能查找" + regionName;
            } else if ("组织外".equals(selectedOrg) && StringUtils.isNotEmpty(regionName)) {
                condition = ",排除" + regionName;
            }
        }

       // String urlAddr = "http://10.32.41.35:40517/scene_gateway/agent/6809d0895428476bb6789ad70c525c97";
        String urlAddr = chatService.getUrl(selectedExpert);

        //String urlAddr = "http://10.32.41.35:40517/scene_gateway/agent/83f77143b09c461993dd9a7db403eb94";
        SseEmitter emitter = new SseEmitter(0L);
        QuestionRequest questionRequest=new QuestionRequest();
        questionRequest.setKeyword(chatMessage+condition);
        questionRequest.setRequestId(getRequestId());
        questionRequest.setDialogId(dialogId);
        Conversations conversations=chatService.saveConversations(dialogId,chatMessage,selectedExpert);
        Messages messagesQusetion=new Messages();
        messagesQusetion.setRequestId(dialogId);
        messagesQusetion.setContent(chatMessage);
        messagesQusetion.setRole("user");
        messagesQusetion.setModelName("qwen2.5-72b");
        messagesQusetion=chatService.insertQuestionMessage(conversations,messagesQusetion);
        Messages messagesContent=new Messages();
        messagesContent.setRole("assistant");
        messagesContent.setModelName("qwen2.5-72b");
        messagesContent.setParentMsgId(messagesQusetion.getId());
        messagesContent.setSort(messagesQusetion.getSort()+1);
        chatService.insertMessage(conversations,messagesContent);
        String params = JsonUtils.objectToJson(questionRequest);
        StringBuffer content =new StringBuffer();
        StringBuffer lineCotent =new StringBuffer();
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlAddr);
                // 建立链接
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("AuthToken", "4009fe23e6b648539792330c14f5ed8e");
               // connection.setRequestProperty("AuthToken", "fc40db5b7abe47dabfe1899e61fde2d7");
                // 允许输入和输出
                connection.setDoInput(true);
                connection.setDoOutput(true);
                // 设置超时为0，表示无限制
                connection.setConnectTimeout(0);
                connection.setReadTimeout(0);
                try (OutputStream os = connection.getOutputStream()) {
                    os.write(params.getBytes(StandardCharsets.UTF_8));
                    os.flush();
                }
                // 检查响应码
                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    emitter.completeWithError(new RuntimeException("SSE 连接失败: " + responseCode));
                    return;
                }
                // 持续读取 SSE 数据流
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        logger.info(line);
                        if (!line.startsWith("data:CALLBACK#")) {
                            if (line.startsWith("data:")) {
                                String data = line.substring(5);
                                if("stop".equals(data))
                                {
                                    emitter.send(SseEmitter.event().data("stop"),MediaType.parseMediaType("application/json; charset=UTF-8"));
                                }else
                                {
                                    lineCotent.append(data);
                                    String sendData=data.replace("attachment#[]#attachment","").replace("source#[]#source","")
                                            .replace("#","").replace("*","");
                                    sendData=sendData.replace("$", "#");
                                    emitter.send(SseEmitter.event().data(sendData), MediaType.parseMediaType("application/json; charset=UTF-8"));
                                    if(!sendData.startsWith("SUGGEST["))
                                    content.append(sendData);
                                }
                            }
                        }
                    }
                }
                emitter.complete(); // 流结束
            } catch (Exception e) {
                emitter.completeWithError(e);
                logger.info(e.getMessage());
            } finally {
                messagesContent.setContent(content.toString());
                chatService.updateMessage(messagesContent);
                if (connection != null) {
                    connection.disconnect();
                }
                logger.info(lineCotent.toString());
            }
        }).start();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);

    }


    //模拟see接口
    @GetMapping("/simulate")
    public ResponseEntity<SseEmitter> simulateStream(@RequestParam String chatMessage,@RequestParam String sessionId) {
        // 在这里处理authToken，验证用户身份
        // ...
        //
        String history= redisTool.get(sessionId);
        List<Map<String,Object>> historyList=new ArrayList<>();
        if(StringUtils.isNotEmpty(history))
            historyList= JsonUtils.jsonToMapList(history);
        Map map=new HashMap<>();
        map.put("stream",true);
        map.put("model","qwen");
        map.put("max_tokens",2048);
        List<Map<String,Object>> mesList=new ArrayList<>();
        Map mes=new HashMap<>();
        mes.put("role","user");
        mes.put("content",chatMessage);
        mesList.add(mes);

        Conversations conversations=chatService.saveConversations(sessionId,chatMessage,"内部专家");
        Messages messagesQusetion=new Messages();
        messagesQusetion.setRequestId(sessionId);
        messagesQusetion.setContent(chatMessage);
        messagesQusetion.setRole("user");
        messagesQusetion.setModelName("qwen2.5-72b");
        messagesQusetion=chatService.insertQuestionMessage(conversations,messagesQusetion);
        Messages messagesContent=new Messages();
        messagesContent.setRole("assistant");
        messagesContent.setModelName("qwen2.5-72b");
        messagesContent.setParentMsgId(messagesQusetion.getId());
        messagesContent.setSort(messagesQusetion.getSort()+1);
        chatService.insertMessage(conversations,messagesContent);
        if(historyList!=null&&historyList.size()>0) {
            historyList.addAll(mesList);
            map.put("messages", historyList);
        }else
        {

            historyList.addAll(mesList);
            map.put("messages", historyList);
        }
        SseEmitter emitter = new SseEmitter();
        Map mapGet=new HashMap<>();
        StringBuffer contentGet =new StringBuffer();
        // 使用线程模拟发送SSE事件
        List<Map<String, Object>> finalHistoryList = historyList;
        new Thread(() -> {
            try {
                for (int i = 0; i < 24; i++) {
                    String a="<a href='#tabs-1'>发起调度单</a>";
                    // 这里可以基于keyword, requestId, dialogId处理逻辑，但示例中仅发送简单事件
                    contentGet.append("");
                    emitter.send(SseEmitter.event().data(a.substring(i,i+1)),MediaType.parseMediaType("application/json; charset=UTF-8"));
                    Thread.sleep(1000); // 每秒发送一个事件
                }
                emitter.send(SseEmitter.event().data("stop"),MediaType.parseMediaType("application/json; charset=UTF-8"));
                mapGet.put("role","assistant");
                mapGet.put("content",contentGet.toString());
                finalHistoryList.add(mapGet);
                messagesContent.setContent(contentGet.toString());
                chatService.updateMessage(messagesContent);
                redisTool.put(sessionId, JsonUtils.objectToJson(finalHistoryList), 2, TimeUnit.HOURS);
                Thread.sleep(1000);
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();


        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);
    }

    @GetMapping("/sseBigTwo")
    public ResponseEntity<SseEmitter> sseBigTwoTest(){
        SseEmitter emitter = new SseEmitter(0L);
        new Thread(() -> {
            try {
                // 模拟大模型分次生成回复
                String a = "attachment#[]#attachmentsource#[]#source根据您的需求，以下是匹配值最高的5位南京专家信息：<br /><br />1.**专家信息**:姓名:薛宇城,电话:13901587782,部门:工程建设部,科室:无线网建设班,地市:南京,<br />简介:中级工程师，集团卓越工程师，中国移动工匠，获得第十七届“振兴杯”全国青年职业技能大赛（职工组）江苏省选拔赛金奖，近三年参与公司在岗革新11个获奖。<br />**推荐原因**:薛宇城在南京地区有丰富的无线网络建设和运维经验，是南京分公司的中级工程师，具备较高的技术水平和项目管理能力。<br /><br />2.**专家信息**:姓名:吴东平,电话:13905180703,部门:规划技术部,科室:基建组,地市:南京,<br />简介:负责IT规划、投资计划、基建规划等工作，曾被评为省级IT技术专家。目前主要负责扬州仪征数据中心、南京江北数据中心、南通、徐州通信枢纽规划建设。近年来，完成中国移动智算南京中心机电方案编制，字节定制化数据中心（合同额超百亿）土建、变电站、室外工程方案编制，完成南通通信枢纽、徐州通信枢纽方案编制。对数据中心的规划建设及绿电、储能等有积累，熟悉网络云、核心机房、汇聚机房动力配套规划和建设。<br />**推荐原因**:吴东平在南京地区的数据中心规划和建设方面有丰富经验，特别是在南京江北数据中心的建设中发挥了重要作用，具备高级技术和管理能力。<br /><br />3.**专家信息**:姓名:高珂,电话:13905180047,部门:网络部,科室:核心网维护室,地市:南京,<br />简介:负责5GtoB中兴区域业务支撑及维护工作。曾牵头完成5GtoB南京SA预商用迁移工作，顺利完成省内10个项目由南京SA预商用网络向商用5GtoB网络的迁移，其中包括全国首个异厂家插花集团，并协助集团总部输出业务迁移经验手册。曾参与5G专网关键网络能力试点、5GtoB核心网与IMS互通改造等新技术试点项目中，具有一定的项目支撑经验。曾获2020年网络条线技能竞赛核心网专业三等奖、2021年度网络部网络维护安全先进个人、“赋能建功”2024年网络条线技能竞赛5G核心网专业三等奖等荣誉。<br />**推荐原因**:高珂在南京地区的5GtoB网络维护和支持方面有丰富的经验和成功案例，特别是在5GSA预商用迁移项目中的突出表现，使其成为该领域的优秀专家。<br /><br />4.**专家信息**:姓名:徐荣蓉,电话:15705186998,部门:紫金研究院,科室:区块链研发部,地市:南京,<br />简介:熟悉数据水印系统研发、数字政府的数据要素流通产品研发，有南京市重大科技专项-可信能碳综合管理体系研究与产业化、工信部重点实验室开放课题-基于区块链的分布式可信智能计算关键技术研究、软件供应链开源威胁检测平台、数智流程自动化管理平台、数据要素采集治理平台研发等相关项目经历。<br />**推荐原因**:徐荣蓉在南京地区的区块链和数据要素流通技术研发方面有深厚的技术背景和项目经验，适合涉及这些领域的技术支持和咨询。<br /><br />5.**专家信息**:姓名:应葆华,电话:15805169804,部门:紫金研究院,科室:区块链研发部,地市:南京,<br />简介:熟悉数据水印系统研发、数字政府的数据要素流通产品研发、数智流程自动化管理平台，有南京市重大科技专项-可信能碳综合管理体系研究与产业化、工信部重点实验室开放课题-基于区块链的分布式可信智能计算关键技术研究、软件供应链开源威胁检测平台、数据要素采集治理平台研发等相关项目经历。<br />**推荐原因**:应葆华在南京地区的区块链和数据要素流通技术研发方面有丰富的项目经验和技术积累，能够提供专业的技术支持和解决方案。";
                a = a.replace("attachment#[]#attachmentsource#[]#source","").replace("<br />", "\n").replaceAll("###(?=\\S)", "### ");;
                int chunkSize = 5;
                int stringLength = a.length();
                int chunksCount = (stringLength + chunkSize - 1) / chunkSize;
                String[] chunks = new String[chunksCount];

                for (int i = 0; i < chunksCount; i++) {
                    int start = i * chunkSize;
                    int end = Math.min(start + chunkSize, stringLength);
                    chunks[i] = a.substring(start, end);
                }

                for (String chunk : chunks) {
                    // 每次发送一个数据块
                    emitter.send(SseEmitter.event().data(chunk), MediaType.parseMediaType("application/json; charset=UTF-8"));
                    Thread.sleep(100);
                }
                emitter.send(SseEmitter.event().data("SUGGEST#[\" 我可以联系这些专家吗？他们的联系方式是否公开？\", \" 这些专家是否有特定的专业领域或擅长的项目类型？\", \" 除了这五位专家，还有其他南京地区的专家推荐吗？\"]#SUGGEST"), MediaType.parseMediaType("application/json; charset=UTF-8"));
                emitter.send(SseEmitter.event().data("stop"),MediaType.parseMediaType("application/json; charset=UTF-8"));
            } catch (IOException e) {
                emitter.completeWithError(e);  // 出错时关闭连接
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);
    }


    //调用大模型接口
    @GetMapping("/sseQwen")
    public  ResponseEntity<SseEmitter> sseQwen(@RequestParam String  chatMessage,@RequestParam String sessionId) {

        String history= redisTool.get(sessionId);
        List<Map<String,Object>> historyList=new ArrayList<>();
        if(StringUtils.isNotEmpty(history))
            historyList= JsonUtils.jsonToMapList(history);

        // 发送请求体
        Map map=new HashMap<>();
        map.put("stream",true);
        map.put("model","qwen");
        map.put("max_tokens",2048);
        List<Map<String,Object>> messageList=new ArrayList<>();
        Map message=new HashMap<>();
        message.put("role","user");
        message.put("content",chatMessage);
        messageList.add(message);
        map.put("messages",messageList);
        if(historyList!=null&&historyList.size()>0) {
            historyList.addAll(messageList);
            map.put("messages", historyList);
        }else
        {
            historyList.addAll(messageList);
            map.put("messages", historyList);
        }

        SseEmitter emitter = new SseEmitter(0L); // 超时时间设为无限
        Map mapAssistant=new HashMap<>();
        StringBuffer contentAssistant =new StringBuffer();
        // 启动线程处理 SSE 连接
        List<Map<String, Object>> finalHistoryList = historyList;
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL("http://10.32.41.228:39080/v1/chat/completions");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                connection.setRequestProperty("AI-API-CODE", "7xU7Aa1IMj");
                connection.setRequestProperty("AI-APP-KEY", "vXRDti1mJg");
                connection.setDoOutput(true);

                String jsonInputString =JsonUtils.objectToJson(map);
                logger.info(jsonInputString);
                try (OutputStream os = connection.getOutputStream()) {
                    os.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
                    os.flush();
                }
                // 检查响应码
                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    emitter.completeWithError(new RuntimeException("SSE 连接失败: " + responseCode));
                    return;
                }

                // 持续读取 SSE 数据流
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String data = line.substring(5).trim();
                            logger.info(data);
                            QwenLine qwenLine= JsonUtils.jsonToObject(data,QwenLine.class);
                            String lineContent=qwenLine.getChoices().get(0).getDelta().getContent();
                            String lineFinish=qwenLine.getChoices().get(0).getFinish_reason();
                            logger.info(lineContent);
                            logger.info(lineFinish);
                            if("stop".equals(lineFinish))
                            {
                                emitter.send(SseEmitter.event().data("stop"),MediaType.parseMediaType("application/json; charset=UTF-8"));
                                mapAssistant.put("role","assistant");
                                mapAssistant.put("content",contentAssistant.toString());
                                finalHistoryList.add(mapAssistant);
                                redisTool.put(sessionId, JsonUtils.objectToJson(finalHistoryList), 2, TimeUnit.HOURS);
                            }else
                            {
                                contentAssistant.append(lineContent);
                                emitter.send(SseEmitter.event().data(lineContent),MediaType.parseMediaType("application/json; charset=UTF-8"));
                            }
                            // 将数据转发给前端
                        }
                    }
                }
                emitter.complete(); // 流结束
            } catch (Exception e) {
                emitter.completeWithError(e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);
    }



    private static final CloseableHttpClient httpClient;


    static {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(100);
        connManager.setDefaultMaxPerRoute(20);

        httpClient = HttpClients.custom()
                .setConnectionManager(connManager)
                .build();
    }

    @GetMapping("/chat-stream")
    public SseEmitter chatStream(@RequestParam("chatMessage") String chatMessage) {
        SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
        Map map=new HashMap<>();
        map.put("stream",true);
        map.put("model","qwen");
        map.put("max_tokens",2048);
        List<Map> mesList=new ArrayList<>();
        Map mes=new HashMap<>();
        mes.put("role","user");
        mes.put("content",chatMessage);
        mesList.add(mes);
        map.put("messages",mesList);
        String jsonInputString =JsonUtils.objectToJson(map);
        new Thread(() -> {
            try{
                // 使用HttpComponents更优雅的请求构建方式
                HttpPost post = new HttpPost("http://10.32.41.228:39080/v1/chat/completions");
                //post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
                post.addHeader("Content-Type", "application/json;charset=UTF-8");
                post.addHeader("AI-API-CODE", "7xU7Aa1IMj");
                post.addHeader("AI-APP-KEY", "vXRDti1mJg");
                post.setEntity(new StringEntity(objectMapper.writeValueAsString(jsonInputString),
                        ContentType.APPLICATION_JSON));
                // 执行请求（带重试）
                try (CloseableHttpResponse response = httpClient.execute(post)) {
                    processStreamResponse(response, emitter);
                }
            } catch (Exception e) {
                handleException(e, emitter);
            }
        }).start();

        // 超时和完成回调
        emitter.onTimeout(() -> logger.warn("SSE连接超时"));
        emitter.onCompletion(() -> logger.info("SSE连接完成"));
        return emitter;
    }

    // 流式响应处理私有方法
    private void processStreamResponse(HttpResponse response, SseEmitter emitter)
            throws IOException {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("data: ")) {
                    String data = line.substring(5).trim();
                    QwenLine qwenLine= JsonUtils.jsonToObject(data,QwenLine.class);
                    String lineContent=qwenLine.getChoices().get(0).getDelta().getContent();
                    String lineFinish=qwenLine.getChoices().get(0).getFinish_reason();
                    if ("stop".equals(lineFinish)) break;
                    logger.info(line);
                    logger.info(lineContent);
                    if (!lineContent.isEmpty()) {
                        emitter.send(SseEmitter.event()
                                .data(lineContent)
                                .id(UUID.randomUUID().toString()));
                    }
                }
            }
            emitter.complete();
        }
    }

    @PreDestroy
    public void destroy() throws IOException {
        httpClient.close(); // 程序退出时关闭
    }

    // 统一异常处理
    private void handleException(Exception e, SseEmitter emitter) {
        logger.error("API调用异常", e);
        if (e instanceof SocketTimeoutException) {
            emitter.completeWithError(new RuntimeException("连接DeepSeek服务超时"));
        } else {
            emitter.completeWithError(new RuntimeException("服务内部错误"));
        }
    }

    //获取sessionId
    @GetMapping("/getSessionId")
    public Result getSessionId() {
        return Result.successData(UUID.randomUUID().toString().replace("-", ""));
    }

    //获取requestId
    public String getRequestId() {
        // (yyyyMMddHHmmssSSS)+6位随机数;
        //Random random = new Random();
        Integer min = 100000; // 最小值（6位起始）
        Integer max = 999999; // 最大值（6位结束）
        // 生成范围：min <= num <= max
        SecureRandom random;
        try{
            random = SecureRandom.getInstance("SHA1PRNG");
        }catch (Exception e){
            throw new ValidationException("随机数获取失败");
        }
        Integer randomNum = random.nextInt(max - min + 1) + min;
        String currentDay = DateTool.format(new Date(), "yyyyMMddHHmmssSSS");
        return currentDay+randomNum.toString();
    }

    //获取会话ID
    @GetMapping("/getDialogId")
    public Result getDialogId() {
        // (yyyyMMddHHmmssSSS)+6位随机数;
      //  Random random = new Random();
        Integer min = 100000; // 最小值（6位起始）
        Integer max = 999999; // 最大值（6位结束）
        // 生成范围：min <= num <= max
        SecureRandom random;
        try{
            random = SecureRandom.getInstance("SHA1PRNG");
        }catch (Exception e){
            throw new ValidationException("随机数获取失败");
        }
        Integer randomNum = random.nextInt(max - min + 1) + min;
        String currentDay = DateTool.format(new Date(), "yyyyMMddHHmmssSSS");
        return Result.successData(currentDay+randomNum.toString());
    }


    /**
     * 会话记录列表
     *
     * @param
     * @return
     */
    @GetMapping("/conversationHistory")
    public Result conversationHistory() {
        List<Map<String,Object>> mapList = chatService.conversationHistory();
        return Result.successData(mapList);
    }

    /**
     * 会话记录列表
     *
     * @param
     * @return
     */
    @GetMapping("/conversationMessages")
    public Result conversationMessages(@RequestParam String sessionId) {
        List<Messages> mapList= chatService.conversationMessages(sessionId);
        return Result.successData(mapList);
    }

    //删除历史对话

    /**
     * 会话记录列表
     *
     * @param
     * @return
     */
    @PostMapping("/deleteChat")
    public Result deleteChat(@RequestBody String sessionId) {
        chatService.deleteChat(sessionId);
        return Result.successData("删除成功");
    }



    //调用智能体
    @GetMapping("/sseTest")
    public ResponseEntity<SseEmitter> sseTest(@RequestParam String  chatMessage,@RequestParam String dialogId,
                                          @RequestParam String selectedExpert ,@RequestParam String selectedOrg)  {
        String condition="";
        // String regionName= chatService.getAuthRegionName();
//        if("内部专家".equals(selectedExpert)) {
//            if ("组织内".equals(selectedOrg) && StringUtils.isNotEmpty(regionName)) {
//                condition = ",只能查找" + regionName;
//            } else if ("组织外".equals(selectedOrg) && StringUtils.isNotEmpty(regionName)) {
//                condition = ",排除" + regionName;
//            }
//        }

        // String urlAddr = "http://10.32.41.35:40517/scene_gateway/agent/6809d0895428476bb6789ad70c525c97";
        String urlAddr ="http://10.32.41.35:40517/scene_gateway/agent/468fd1bfa3e543fc8526a82a9093097a"; //chatService.getUrl(selectedExpert);

        //String urlAddr = "http://10.32.41.35:40517/scene_gateway/agent/83f77143b09c461993dd9a7db403eb94";
        SseEmitter emitter = new SseEmitter(0L);
        QuestionRequest questionRequest=new QuestionRequest();
        questionRequest.setKeyword(chatMessage+condition);
        questionRequest.setRequestId(getRequestId());
        questionRequest.setDialogId(dialogId);
//        Conversations conversations=chatService.saveConversations(dialogId,chatMessage,selectedExpert);
//        Messages messagesQusetion=new Messages();
//        messagesQusetion.setRequestId(dialogId);
//        messagesQusetion.setContent(chatMessage);
//        messagesQusetion.setRole("user");
//        messagesQusetion.setModelName("qwen2.5-72b");
//        messagesQusetion=chatService.insertQuestionMessage(conversations,messagesQusetion);
//        Messages messagesContent=new Messages();
//        messagesContent.setRole("assistant");
//        messagesContent.setModelName("qwen2.5-72b");
//        messagesContent.setParentMsgId(messagesQusetion.getId());
//        messagesContent.setSort(messagesQusetion.getSort()+1);
//        chatService.insertMessage(conversations,messagesContent);
        String params = JsonUtils.objectToJson(questionRequest);
        StringBuffer content =new StringBuffer();
        StringBuffer lineCotent =new StringBuffer();
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlAddr);
                // 建立链接
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("AuthToken", "4009fe23e6b648539792330c14f5ed8e");
                // connection.setRequestProperty("AuthToken", "fc40db5b7abe47dabfe1899e61fde2d7");
                // 允许输入和输出
                connection.setDoInput(true);
                connection.setDoOutput(true);
                // 设置超时为0，表示无限制
                connection.setConnectTimeout(0);
                connection.setReadTimeout(0);
                try (OutputStream os = connection.getOutputStream()) {
                    os.write(params.getBytes(StandardCharsets.UTF_8));
                    os.flush();
                }
                // 检查响应码
                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    emitter.completeWithError(new RuntimeException("SSE 连接失败: " + responseCode));
                    return;
                }
                // 持续读取 SSE 数据流
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        logger.info(line);
                        if (!line.startsWith("data:CALLBACK#")) {
                            if (line.startsWith("data:")) {
                                String data = line.substring(5).trim();
                                if("stop".equals(data))
                                {
                                    emitter.send(SseEmitter.event().data("stop"),MediaType.parseMediaType("application/json; charset=UTF-8"));
                                }else
                                {
                                    lineCotent.append(data);
                                    String sendData=data.replace("attachment#[]#attachment","").replace("source#[]#source","")
                                            .replace("#","").replace("*","");
                                    emitter.send(SseEmitter.event().data(sendData), MediaType.parseMediaType("application/json; charset=UTF-8"));
                                    if(!sendData.startsWith("SUGGEST["))
                                        content.append(sendData);
                                }
                            }
                        }
                    }
                }
                emitter.complete(); // 流结束
            } catch (Exception e) {
                emitter.completeWithError(e);
                logger.info(e.getMessage());
            } finally {
                //  messagesContent.setContent(content.toString());
                //  chatService.updateMessage(messagesContent);
                if (connection != null) {
                    connection.disconnect();
                }
                logger.info(lineCotent.toString());
            }
        }).start();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);

    }

    //内部专家外部专家融合智能体
    @GetMapping("/sseFusionIntelligent")
    public ResponseEntity<SseEmitter> sseFusionIntelligent(@RequestParam String  chatMessage,@RequestParam String dialogId,
                                          @RequestParam String selectedExpert ,@RequestParam String selectedOrg)  {

         String urlAddr = "http://10.32.41.25:40349/invoke/api/open/sse/unifiedcapability";
         SseEmitter emitter = new SseEmitter(0L);
        AgentChatParams agentChatParams = new AgentChatParams();
        agentChatParams.setKeyword(chatMessage);
        agentChatParams.setRequestId(getRequestId());
        agentChatParams.setDialogId(dialogId);
        agentChatParams.setHistory(5);
        AgentChatRequest agentChatRequest = new AgentChatRequest();
        agentChatRequest.setCapabilityCode("a3a5a5efd03747faabc83a9424aae85b");//5386f9144ee042578d1c0f66c2598d06
        agentChatRequest.setCapabilityType("2");
        agentChatRequest.setParams(agentChatParams);

        Conversations conversations=chatService.saveConversations(dialogId,chatMessage,selectedExpert);
        Messages messagesQusetion=new Messages();
        messagesQusetion.setRequestId(dialogId);
        messagesQusetion.setContent(chatMessage);
        messagesQusetion.setRole("user");
        messagesQusetion.setModelName("qwen2.5-72b");
        messagesQusetion=chatService.insertQuestionMessage(conversations,messagesQusetion);
        Messages messagesContent=new Messages();
        messagesContent.setRole("assistant");
        messagesContent.setModelName("qwen2.5-72b");
        messagesContent.setParentMsgId(messagesQusetion.getId());
        messagesContent.setSort(messagesQusetion.getSort()+1);
        chatService.insertMessage(conversations,messagesContent);
        String params = JsonUtils.objectToJson(agentChatRequest);
        StringBuffer content =new StringBuffer();
        StringBuffer lineCotent =new StringBuffer();
        new Thread(() -> {
            CloseableHttpClient closeableHttpClient = httpClientPool.sseHttpClient();
            HttpPost httpPost = new HttpPost(urlAddr);
            try {

                httpPost.setHeader("AuthToken", "4009fe23e6b648539792330c14f5ed8e");
                httpPost.setHeader("Content-Type", "application/json");

                httpPost.setEntity(new StringEntity(params, StandardCharsets.UTF_8));
                logger.info("调用智宇智能体请求体:" + params);
                boolean isSendStop = false;
                try (CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
                     InputStream inputStream = response.getEntity().getContent();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){
                    // 检查响应码
                    int statusCode = response.getStatusLine().getStatusCode();

                    // 持续读取 SSE 数据流
                    String line;
                    while ((line = reader.readLine()) != null) {
                        logger.info("Response body：" + line);
                        if (!line.startsWith("data:CALLBACK#")) {
                            if (line.startsWith("data:")) {
                                String data = line.substring(5).trim();
                                if ("stop".equals(data)) {
                                    emitter.send(SseEmitter.event().data("stop"), MediaType.parseMediaType("application/json; charset=UTF-8"));
                                    isSendStop = true;
                                } else {
                                    lineCotent.append(data);
                                    String sendData = data.replace("attachment#[]#attachment", "").replace("source#[]#source", "")
                                            .replace("#", "").replace("*", "");
                                    emitter.send(SseEmitter.event().data(sendData), MediaType.parseMediaType("application/json; charset=UTF-8"));
                                    if (!sendData.startsWith("SUGGEST["))
                                        content.append(sendData);
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    emitter.completeWithError(e);
                    logger.error("调用智宇智能体接口异常: ", e);
                }
                if (!isSendStop){//如果没有发送stop，发送stop。
                    emitter.send(SseEmitter.event().data("stop"), MediaType.parseMediaType("application/json; charset=UTF-8"));
                }
                emitter.complete(); // 流结束
            } catch (Exception e) {
                emitter.completeWithError(e);
                logger.info(e.getMessage());
            } finally {
                messagesContent.setContent(content.toString());
                chatService.updateMessage(messagesContent);
                logger.info(lineCotent.toString());
            }
        }).start();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);


    }

    //调用插件智能体
    @GetMapping("/sseIntelligentNew")
    public ResponseEntity<SseEmitter> sseIntelligentNew(@RequestParam String  chatMessage,@RequestParam String dialogId,
                                          @RequestParam String selectedExpert ,@RequestParam String selectedOrg)  {
        String condition="";
        String regionName= chatService.getAuthRegionName();
        if("内部专家".equals(selectedExpert)) {
            if ("组织内".equals(selectedOrg) && StringUtils.isNotEmpty(regionName)) {
                condition = ",只能查找" + regionName;
            } else if ("组织外".equals(selectedOrg) && StringUtils.isNotEmpty(regionName)) {
                condition = ",排除" + regionName;
            }
        }

        String urlAddr = "http://10.32.41.25:40349/invoke/api/open/sse/unifiedcapability";

        //String urlAddr = chatService.getUrl(selectedExpert);
        AgentChatParams agentChatParams = new AgentChatParams();
        agentChatParams.setKeyword(chatMessage);
        agentChatParams.setRequestId(getRequestId());
        agentChatParams.setDialogId(dialogId);
        agentChatParams.setHistory(5);
        AgentChatRequest agentChatRequest = new AgentChatRequest();
        if("外部专家".equals(selectedExpert)) {
            agentChatRequest.setCapabilityCode("cd438f7a96964382998bc89b957bf3dc");
        }
        else {
            agentChatRequest.setCapabilityCode("5386f9144ee042578d1c0f66c2598d06");
        }
        agentChatRequest.setCapabilityType("2");
        agentChatRequest.setParams(agentChatParams);

        SseEmitter emitter = new SseEmitter(0L);
        QuestionRequest questionRequest=new QuestionRequest();
        questionRequest.setKeyword(chatMessage+condition);
        questionRequest.setRequestId(getRequestId());
        questionRequest.setDialogId(dialogId);
        Conversations conversations=chatService.saveConversations(dialogId,chatMessage,selectedExpert);
        Messages messagesQusetion=new Messages();
        messagesQusetion.setRequestId(dialogId);
        messagesQusetion.setContent(chatMessage);
        messagesQusetion.setRole("user");
        messagesQusetion.setModelName("qwen2.5-72b");
        messagesQusetion=chatService.insertQuestionMessage(conversations,messagesQusetion);
        Messages messagesContent=new Messages();
        messagesContent.setRole("assistant");
        messagesContent.setModelName("qwen2.5-72b");
        messagesContent.setParentMsgId(messagesQusetion.getId());
        messagesContent.setSort(messagesQusetion.getSort()+1);
        chatService.insertMessage(conversations,messagesContent);
        String params = JsonUtils.objectToJson(agentChatRequest);
        StringBuffer content =new StringBuffer();
        StringBuffer lineCotent =new StringBuffer();
        new Thread(() -> {
            CloseableHttpClient closeableHttpClient = httpClientPool.sseHttpClient();
            HttpPost httpPost = new HttpPost(urlAddr);
            try {

                httpPost.setHeader("AuthToken", "4009fe23e6b648539792330c14f5ed8e");
                httpPost.setHeader("Content-Type", "application/json");

                httpPost.setEntity(new StringEntity(params, StandardCharsets.UTF_8));
                logger.info("调用智宇智能体请求体:" + params);
                boolean isSendStop = false;
                try (CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
                     InputStream inputStream = response.getEntity().getContent();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){
                    // 检查响应码
                    int statusCode = response.getStatusLine().getStatusCode();

                    // 持续读取 SSE 数据流
                    String line;
                    while ((line = reader.readLine()) != null) {
                        logger.info("Response body：" + line);
                        if (!line.startsWith("data:CALLBACK#")) {
                            if (line.startsWith("data:")) {
                                String data = line.substring(5);
                                if ("stop".equals(data)) {
                                    emitter.send(SseEmitter.event().data("stop"), MediaType.parseMediaType("application/json; charset=UTF-8"));
                                    isSendStop = true;
                                } else {
                                    lineCotent.append(data);
                                    String sendData = data.replace("attachment#[]#attachment", "").replace("source#[]#source", "")
                                            .replace("#", "").replace("*", "")
                                            .replace("^", " ");
                                    sendData=sendData.replace("$", "#");
                                    emitter.send(SseEmitter.event().data(sendData), MediaType.parseMediaType("application/json; charset=UTF-8"));
                                    if (!sendData.startsWith("SUGGEST["))
                                        content.append(sendData);
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    emitter.completeWithError(e);
                    logger.error("调用智宇智能体接口异常: ", e);
                }
                if (!isSendStop){//如果没有发送stop，发送stop。
                    emitter.send(SseEmitter.event().data("stop"), MediaType.parseMediaType("application/json; charset=UTF-8"));
                }
                emitter.complete(); // 流结束
            } catch (Exception e) {
                emitter.completeWithError(e);
                logger.info(e.getMessage());
            } finally {
                messagesContent.setContent(content.toString());
                chatService.updateMessage(messagesContent);
                logger.info(lineCotent.toString());
            }
        }).start();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
                .body(emitter);

    }

}
