package cn.com.poc.meeting.aggregate.impl;

import cn.com.poc.agent_application.entity.BizAgentApplicationDialoguesRecordEntity;
import cn.com.poc.agent_application.entity.BizAgentApplicationGcConfigEntity;
import cn.com.poc.agent_application.entity.KnowledgeContentResult;
import cn.com.poc.agent_application.service.BizAgentApplicationDialoguesRecordService;
import cn.com.poc.agent_application.service.BizAgentApplicationGcConfigService;
import cn.com.poc.ai_dialogues.constant.AiDialoguesTypeEnum;
import cn.com.poc.ai_dialogues.entity.BizAiDialoguesEntity;
import cn.com.poc.ai_dialogues.service.BizAiDialoguesService;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.service.BizFileUploadRecordService;
import cn.com.poc.common.utils.*;
import cn.com.poc.example.ExampleTypeConstants;
import cn.com.poc.example.entity.BizExampleEntity;
import cn.com.poc.example.service.BizExampleService;
import cn.com.poc.knowledge.aggregate.KnowledgeService;
import cn.com.poc.knowledge.constant.KnowledgeConstant;
import cn.com.poc.knowledge.entity.BizKnowledgeDocumentEntity;
import cn.com.poc.knowledge.query.KnowledgeDocumentRelationQueryItem;
import cn.com.poc.knowledge.service.BizKnowledgeDocumentService;
import cn.com.poc.long_document.domain.LongtextDialoguesResult;
import cn.com.poc.meeting.aggregate.AiMeetingAssistantService;
import cn.com.poc.meeting.cache.KeyWordCounter;
import cn.com.poc.meeting.constants.MeetingAssistantConstantEnum;
import cn.com.poc.meeting.convert.BizMeetingAssistantAnalysisTaskConvert;
import cn.com.poc.meeting.entity.AnalysisTaskDetailEntity;
import cn.com.poc.meeting.entity.BizMeetingAssistantAnalysisTaskEntity;
import cn.com.poc.meeting.entity.BizMeetingAssistantAsrTaskEntity;
import cn.com.poc.meeting.service.BizMeetingAssistantAnalysisTaskService;
import cn.com.poc.meeting.service.BizMeetingAssistantAsrTaskService;
import cn.com.poc.thirdparty.resource.demand.ai.aggregate.DemandKnowledgeService;
import cn.com.poc.thirdparty.resource.demand.ai.constants.KnowledgeSearchTypeEnum;
import cn.com.poc.thirdparty.resource.demand.ai.constants.LLMRoleEnum;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Message;
import cn.com.poc.thirdparty.resource.demand.ai.entity.knowledge.SearchKnowledgeResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelResponse;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.AsrOfflineDetailResult;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.Translation;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.service.ASRService;
import cn.com.poc.thirdparty.service.LLMService;
import cn.com.poc.writing.dto.AiWritingTitleGenerationDto;
import cn.com.poc.writing.entity.BizAiWritingDialoguesRecordEntity;
import cn.com.poc.writing.service.BizAiWritingDialoguesRecordService;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class AiMeetingAssistantServiceImpl implements AiMeetingAssistantService {

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

    @Resource
    private ASRService asrService;

    @Resource
    private BizAiDialoguesService bizAiDialoguesService;

    @Resource
    private BizFileUploadRecordService bizFileUploadRecordService;

    @Resource
    private BizMeetingAssistantAsrTaskService bizMeetingAssistantAsrTaskService;

    @Resource
    private BizMeetingAssistantAnalysisTaskService bizMeetingAssistantAnalysisTaskService;

    @Resource
    private BizAgentApplicationDialoguesRecordService bizAgentApplicationDialoguesRecordService;

    @Resource
    private KnowledgeService knowledgeService;

    @Resource
    private BizKnowledgeDocumentService bizKnowledgeDocumentService;

    @Resource
    private DemandKnowledgeService demandKnowledgeService;

    @Resource
    private LLMService llmService;

    @Resource
    private BizExampleService bizExampleService;

    @Resource
    private BizAgentApplicationGcConfigService bizAgentApplicationGcConfigService;


    @Override
    public String createTask(String fileUrl, String dialoguesId, Long userId) {
        logger.info("创建会议解析任务,fileUrl:{},dialoguesId:{}", fileUrl, dialoguesId);

        // 1. 查询dialoguesId 是否存在并且会话标题使用文件名
        checkIsExistAndUpdateTitle(fileUrl, dialoguesId, userId);

        // 2. 调用语音识别任务 [异步]
        asrTask(fileUrl, dialoguesId, userId);

        // 3. 保存会议内容分析状态
        saveAnalysisTask(dialoguesId, userId);

        return MeetingAssistantConstantEnum.GENERATE.getStatus();
    }

    private void checkIsExistAndUpdateTitle(String fileUrl, String dialoguesId, Long userId) {
        // 1. 查询dialoguesId 是否存在
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setDialoguesType(AiDialoguesTypeEnum.MEETING_ASSISTANT.getType());
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> aiDialoguesEntities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isEmpty(aiDialoguesEntities)) {
            throw new BusinessException("会话不存在，查看会话ID是否正确");
        }

        //2. 获取文件名，更新标题
        String fileName = bizFileUploadRecordService.getFileNameByFileUrl(fileUrl);
        if (StringUtils.isBlank(fileName)) {
            throw new BusinessException("获取文件失败，重新上传文件");
        }

        try {
            BizAiDialoguesEntity updateAiDialoguesTitleEntity = aiDialoguesEntities.get(0);
            updateAiDialoguesTitleEntity.setTitle(fileName);
            bizAiDialoguesService.update(updateAiDialoguesTitleEntity);
        } catch (Exception e) {
            logger.error("------ update ai dialogues title error :", e);
            throw new BusinessException("更新对话标题异常");
        }
    }

    private void saveAnalysisTask(String dialoguesId, Long userId) {
        // 若存在旧数据则删除旧数据
        BizMeetingAssistantAnalysisTaskEntity findMeetingAssistantAnalysisTaskLegacyDataEntity = new BizMeetingAssistantAnalysisTaskEntity();
        findMeetingAssistantAnalysisTaskLegacyDataEntity.setDiaguesId(dialoguesId);
        findMeetingAssistantAnalysisTaskLegacyDataEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> analysisTaskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(findMeetingAssistantAnalysisTaskLegacyDataEntity, null);
        if (CollectionUtils.isNotEmpty(analysisTaskEntities)) {
            BizMeetingAssistantAnalysisTaskEntity taskEntity = analysisTaskEntities.get(0);
            bizMeetingAssistantAnalysisTaskService.deletedById(taskEntity.getId());
            logger.info("------ 会议内容分析存在旧任务，已删除旧任务 id:{}---------", taskEntity.getId());
        }

        try {
            BizMeetingAssistantAnalysisTaskEntity saveAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
            saveAnalysisTaskEntity.setDiaguesId(dialoguesId);
            saveAnalysisTaskEntity.setMemberId(userId);
            saveAnalysisTaskEntity.setAnalysisStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
            bizMeetingAssistantAnalysisTaskService.save(saveAnalysisTaskEntity);
        } catch (Exception e) {
            logger.error("--------- save meeting assistant analysis task error :", e);
            throw new BusinessException("保存分析任务失败");
        }
    }

    private void asrTask(String fileUrl, String dialoguesId, Long userId) {
        String sessionId = UUIDTool.getUUID();
        String status = asrService.speechToText(sessionId, fileUrl);
        if (StringUtils.isBlank(status) || !"success".equals(status)) {
            throw new BusinessException("语音识别任务创建失败");
        }
        try {
            BizMeetingAssistantAsrTaskEntity bizMeetingAssistantAsrTaskEntity = new BizMeetingAssistantAsrTaskEntity();
            bizMeetingAssistantAsrTaskEntity.setGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
            bizMeetingAssistantAsrTaskEntity.setSessionId(sessionId);
            bizMeetingAssistantAsrTaskEntity.setDiaguesId(dialoguesId);
            bizMeetingAssistantAsrTaskEntity.setMemberId(userId);
            bizMeetingAssistantAsrTaskService.save(bizMeetingAssistantAsrTaskEntity);
        } catch (Exception e) {
            logger.error("-------- save meeting assistant asr task error :", e);
            throw new BusinessException("保存语音识别任务状态异常");
        }
    }


    @Override
    public AnalysisTaskDetailEntity getTaskDetail(String dialoguesId, Long userId) {
        AnalysisTaskDetailEntity analysisTaskDetailEntity = new AnalysisTaskDetailEntity();

        // 1. 查询dialoguesId 是否存在
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setDialoguesType(AiDialoguesTypeEnum.MEETING_ASSISTANT.getType());
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> aiDialoguesEntities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isEmpty(aiDialoguesEntities)) {
            throw new BusinessException("会话不存在，查看会话ID是否正确");
        }

        // 内容分析任务
        BizMeetingAssistantAnalysisTaskEntity meetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        meetingAssistantAnalysisTaskEntity.setDiaguesId(dialoguesId);
        meetingAssistantAnalysisTaskEntity.setMemberId(userId);
        meetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> entities = bizMeetingAssistantAnalysisTaskService.findByExample(meetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            throw new BusinessException("无法找到对应解析任务，请重新生成");
        }
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = entities.get(0);

        // 语音识别任务
        BizMeetingAssistantAsrTaskEntity bizMeetingAssistantAsrTaskEntity = new BizMeetingAssistantAsrTaskEntity();
        bizMeetingAssistantAsrTaskEntity.setDiaguesId(dialoguesId);
        bizMeetingAssistantAsrTaskEntity.setMemberId(userId);
        bizMeetingAssistantAsrTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAsrTaskEntity> asrTaskEntities = bizMeetingAssistantAsrTaskService.findByExample(bizMeetingAssistantAsrTaskEntity, null);
        if (CollectionUtils.isEmpty(asrTaskEntities)) {
            throw new BusinessException("获取语音识别任务异常");
        }
        BizMeetingAssistantAsrTaskEntity asrTaskEntity = asrTaskEntities.get(0);
        if (MeetingAssistantConstantEnum.FAILED.getStatus().equals(asrTaskEntity.getGenerateStatus())) {
            analysisTaskDetailEntity.setAnalysisStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
            analysisTaskDetailEntity.setAsrStatus(asrTaskEntity.getGenerateStatus());
            logger.error("-------------- 语音识别任务失败 ,sessionId:{}--------------------", asrTaskEntity.getSessionId());
            return analysisTaskDetailEntity;
        } else if (MeetingAssistantConstantEnum.GENERATE.getStatus().equals(asrTaskEntity.getGenerateStatus())) {
            analysisTaskDetailEntity.setAnalysisStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
            analysisTaskDetailEntity.setAsrStatus(asrTaskEntity.getGenerateStatus());
            logger.error("-------------- 语音识别任务执行中 ,sessionId:{}--------------------", asrTaskEntity.getSessionId());
            return analysisTaskDetailEntity;
        }

        // 构造返回参数
        analysisTaskDetailEntity = BizMeetingAssistantAnalysisTaskConvert.bizEntityToDetailEntity(bizMeetingAssistantAnalysisTaskEntity);

        // 获取对话内容
        AsrOfflineDetailResult asrServiceDetail = asrService.getDetail(asrTaskEntity.getSessionId());
        List<Translation> translations = asrServiceDetail.getTranslation();
        analysisTaskDetailEntity.setTranslations(translations);

        // 获取说话人列表
        Set<Long> spkSets = new HashSet<>();
        for (Translation translation : translations) {
            spkSets.add(translation.getSpk());
        }
        analysisTaskDetailEntity.setSpkSets(spkSets);
        return analysisTaskDetailEntity;
    }

    /**
     * 示例-获取会议解析任务详情
     *
     * @param dialoguesId
     * @return
     */
    @Override
    public AnalysisTaskDetailEntity getExampleTaskDetail(String dialoguesId) throws Exception {
        Assert.notNull(dialoguesId, "dialoguesId不能为空");
        BizExampleEntity example = new BizExampleEntity();
        example.setBizExampleType(ExampleTypeConstants.ExampleType.AI_MEETING);
        example.setBizExampleBusissesId(dialoguesId);
        List<BizExampleEntity> bizExampleEntityList = bizExampleService.findByExample(example, null);
        if (CollectionUtils.isEmpty(bizExampleEntityList)) {
            throw new BusinessException("找不到示例数据，请重新尝试");
        }
        return this.getTaskDetail(dialoguesId, null);
    }


    @Override
    public void call(String dialoguesId, String fileUrl, String input, Integer[] knowledgeIds, Long userId) throws Exception {
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setDialoguesType(AiDialoguesTypeEnum.MEETING_ASSISTANT.getType());
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> bizAiDialoguesEntities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isEmpty(bizAiDialoguesEntities)) {
            throw new BusinessException("对话ID不存在");
        }
        BizAiDialoguesEntity aiDialoguesEntity = bizAiDialoguesEntities.get(0);


        // 初始化文件
        BizAgentApplicationDialoguesRecordEntity dialoguesRecordEntity = new BizAgentApplicationDialoguesRecordEntity();
        dialoguesRecordEntity.setDialogsId(dialoguesId);
        dialoguesRecordEntity.setMemberId(userId);
        dialoguesRecordEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAgentApplicationDialoguesRecordEntity> dialoguesRecordEntities = bizAgentApplicationDialoguesRecordService.findByExample(dialoguesRecordEntity, null);
        boolean isInit = false;
        if (CollectionUtils.isEmpty(dialoguesRecordEntities)) {
            if (StringUtils.isNoneBlank(aiDialoguesEntity.getFileUrl()) && StringUtils.isBlank(fileUrl)) {
                fileUrl = aiDialoguesEntity.getFileUrl();
            }
            isInit = true;
        }

        // 文件是否变更
        boolean isFileUrlChanged = (StringUtils.isNotBlank(fileUrl) && !fileUrl.equals(aiDialoguesEntity.getFileUrl()))
                || isInit;

        if (StringUtils.isBlank(fileUrl)) {
            fileUrl = aiDialoguesEntity.getFileUrl();
        }

        // 更新文件URL
        if (isFileUrlChanged) {
            if (!isInit && StringUtils.isNotBlank(fileUrl)) {
                aiDialoguesEntity.setFileUrl(fileUrl);
                bizAiDialoguesService.update(aiDialoguesEntity);
            }
        }

        //获取会议语音内容
        List<Translation> translations = getASRTranslations(dialoguesId, userId);

        //记录提问时间
        long inputTimestamp = System.currentTimeMillis();

        SSEUtil sseUtil = new SSEUtil();
        // 知识库
        //获取知识库配置
        List<Integer> kdIds = knowledgeService.getKdIdsByKnowledgeInfoIds(knowledgeIds);
        List<KnowledgeContentResult> knowledgeResult = knowledge(kdIds, input, 5, 0.5, KnowledgeSearchTypeEnum.MIX);

        if (CollectionUtils.isNotEmpty(knowledgeResult)) {
            LargeModelDemandResult result = new LargeModelDemandResult();
            result.setCode("0");
            result.setFunction(null);
            result.setDbChainResult(null);
            result.setKnowledgeContentResult(knowledgeResult);
            sseUtil.send(JsonUtils.serialize(result));
        }
        // 获取大模型配置
        String promptCode = "AiMeetingAssistantPrompt";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            logger.error("获取对话提示词失败 , configCode:{}", promptCode);
            throw new BusinessException("获取对话提示词失败");
        }
        //组装请求参数
        List<Message> messages = buildMessages(documentDialoguePrompt, dialoguesId, userId, input, fileUrl, knowledgeResult, translations);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel(documentDialoguePrompt.getLargeModel());
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(true);
        BufferedReader bufferedReader = llmService.chatChunk(largeModelResponse);
        LongtextDialoguesResult longtextDialoguesResult = textOutputStream(sseUtil, bufferedReader);


        // 保存用户输入记录
        BizAgentApplicationDialoguesRecordEntity inputRecord = new BizAgentApplicationDialoguesRecordEntity();
        inputRecord.setMemberId(userId);
        inputRecord.setContent(input);
        if (isFileUrlChanged) {
            inputRecord.setFileUrl(fileUrl);
        }
        inputRecord.setDialogsId(dialoguesId);
        inputRecord.setRole(LLMRoleEnum.USER.getRole());
        inputRecord.setTimestamp(inputTimestamp);

        // 保存AI回复记录
        BizAgentApplicationDialoguesRecordEntity assistantRecord = new BizAgentApplicationDialoguesRecordEntity();
        assistantRecord.setMemberId(userId);
        assistantRecord.setContent(longtextDialoguesResult.getMessage());
        assistantRecord.setReasoningContent(longtextDialoguesResult.getReasoningContent());
        assistantRecord.setDialogsId(dialoguesId);
        assistantRecord.setRole(LLMRoleEnum.ASSISTANT.getRole());
        assistantRecord.setTimestamp(System.currentTimeMillis());

        bizAgentApplicationDialoguesRecordService.save(inputRecord);
        bizAgentApplicationDialoguesRecordService.save(assistantRecord);
    }

    private List<Translation> getASRTranslations(String dialoguesId, Long userId) {
        // 获取会议分析内容
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(dialoguesId);
        bizMeetingAssistantAnalysisTaskEntity.setMemberId(userId);
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> bizMeetingAssistantAnalysisTaskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(bizMeetingAssistantAnalysisTaskEntities)) {
            throw new BusinessException("获取会议分析内容失败");
        }

        if (bizMeetingAssistantAnalysisTaskEntities.get(0).getAnalysisStatus().equals(MeetingAssistantConstantEnum.GENERATE.getStatus())) {
            throw new BusinessException("会议内容正在解析，待解析完成后才可进行对话");
        }
        if (bizMeetingAssistantAnalysisTaskEntities.get(0).getAnalysisStatus().equals(MeetingAssistantConstantEnum.FAILED.getStatus())) {
            throw new BusinessException("会议内容解析失败，无法进行对话");
        }
        //获取会议语音识别内容
        BizMeetingAssistantAsrTaskEntity bizMeetingAssistantAsrTaskEntity = new BizMeetingAssistantAsrTaskEntity();
        bizMeetingAssistantAsrTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        bizMeetingAssistantAsrTaskEntity.setDiaguesId(dialoguesId);
        bizMeetingAssistantAsrTaskEntity.setMemberId(userId);
        List<BizMeetingAssistantAsrTaskEntity> asrTaskEntities = bizMeetingAssistantAsrTaskService.findByExample(bizMeetingAssistantAsrTaskEntity, null);
        if (CollectionUtils.isEmpty(asrTaskEntities)) {
            throw new BusinessException("获取语音识别内容异常");
        }
        String sessionId = asrTaskEntities.get(0).getSessionId();
        AsrOfflineDetailResult asrServiceDetail = asrService.getDetail(sessionId);
        return asrServiceDetail.getTranslation();
    }

    /**
     * 文本输出结果
     *
     * @param sseUtil
     * @param bufferedReader
     * @throws IOException
     */
    private LongtextDialoguesResult textOutputStream(SSEUtil sseUtil, BufferedReader bufferedReader) throws IOException {
        String res = "";
        StringBuilder output = new StringBuilder();
        StringBuilder reasoningContent = new StringBuilder();
        try {
            while ((res = bufferedReader.readLine()) != null) {
                if (StringUtils.isEmpty(res)) {
                    continue;
                }
                res = StringUtils.replace(res, "data: ", StringUtils.EMPTY);
                LargeModelDemandResult result = JsonUtils.deSerialize(res, LargeModelDemandResult.class);
                if (!"0".equals(result.getCode())) {
                    logger.error("LLM Error,code:{}", result.getCode());
                    BusinessException ex = new BusinessException("exception/call.failure");
                    result.setMessage(ex.getMessage());
                    sseUtil.send(JsonUtils.serialize(result));
                    sseUtil.send("[DONE]");
                    sseUtil.complete();
                    throw ex;
                }
                result.setFunction(null);
                result.setDbChainResult(null);
                result.setKnowledgeContentResult(null);
                sseUtil.send(JsonUtils.serialize(result));
                if (StringUtils.isNotEmpty(result.getMessage())) {
                    output.append(result.getMessage());
                }
                if (StringUtils.isNotEmpty(result.getReasoningContent())) {
                    reasoningContent.append(result.getReasoningContent());
                }
            }
            // 关闭资源
            sseUtil.send("[DONE]");
            sseUtil.complete();
            LongtextDialoguesResult longtextDialoguesResult = new LongtextDialoguesResult();
            longtextDialoguesResult.setMessage(output.toString());
            longtextDialoguesResult.setReasoningContent(reasoningContent.toString());
            return longtextDialoguesResult;
        } catch (IOException e) {
            logger.error("连接断开,code:{}", e.getMessage());
            sseUtil.completeByError("连接断开");
            throw new BusinessException("连接断开");
        } finally {
            bufferedReader.close();
        }
    }

    private List<KnowledgeContentResult> knowledge(List<Integer> kdIds, String input, Integer topK, Double score, KnowledgeSearchTypeEnum searchTypeEnum) {
        List<KnowledgeContentResult> knowledgeContentResults = new ArrayList<>();
        if (CollectionUtils.isEmpty(kdIds)) {
            return knowledgeContentResults;
        }
        List<String> knowledgeIds = new ArrayList<>();
        for (Integer kdId : kdIds) {
            BizKnowledgeDocumentEntity knowledgeDocumentEntity = bizKnowledgeDocumentService.get(kdId);
            // 筛选训练完成的文档，否则跳过该文档
            if (null == knowledgeDocumentEntity && KnowledgeConstant.TrainStatus.COMPLETE.equals(knowledgeDocumentEntity.getTrainStatus())) {
                continue;
            }
            knowledgeIds.add(knowledgeDocumentEntity.getKnowledgeId());
        }

        SearchKnowledgeResult searchKnowledgeResult = demandKnowledgeService.searchKnowledge(input, knowledgeIds, topK, score, searchTypeEnum);

        if (CollectionUtils.isNotEmpty(searchKnowledgeResult.getDocuments())) {
            for (int i = 1; i <= searchKnowledgeResult.getDocuments().size(); i++) {
                KnowledgeContentResult knowledgeContentResult = new KnowledgeContentResult();
                knowledgeContentResult.setContent(searchKnowledgeResult.getDocuments().get(i - 1));
                knowledgeContentResult.setKnowledgeId(searchKnowledgeResult.getKnowledgeIds().get(i - 1));
                knowledgeContentResult.setScore(searchKnowledgeResult.getScore().get(i - 1));
                knowledgeContentResults.add(knowledgeContentResult);
            }
            // 根据knowledgeId获取知识库名和文档名
            knowledgeIds = knowledgeContentResults.stream().map(KnowledgeContentResult::getKnowledgeId).distinct().collect(Collectors.toList());
            List<KnowledgeDocumentRelationQueryItem> knowledgeDocumentRelationQueryItems = bizKnowledgeDocumentService.knowledgeDocumentRelationQuery(knowledgeIds, null);
            for (KnowledgeContentResult result : knowledgeContentResults) {
                String knowledgeId = result.getKnowledgeId();
                KnowledgeDocumentRelationQueryItem item = knowledgeDocumentRelationQueryItems.stream().filter(v -> v.getKnowledgeId().equals(knowledgeId)).findFirst().get();
                result.setKnowledgeName(item.getKnowledgeName());
                result.setKdId(item.getKdId());
                result.setDocumentName(item.getDocumentName());
            }
        }

        return knowledgeContentResults;
    }

    private List<Message> buildMessages(BizAgentApplicationGcConfigEntity documentDialoguePrompt, String dialogsId, Long userId, String input, String fileUrl, List<KnowledgeContentResult> knowledgeContentResults, List<Translation> translations) throws Exception {


        // 加载文件
        String fileContent = StringUtils.EMPTY;

        if (StringUtils.isNoneBlank(fileUrl)) {
            File file = DocumentLoad.downloadURLDocument(fileUrl);
            fileContent = DocumentLoad.documentToText(file);
        }

        // 加载对话提示词
        String prompt = documentDialoguePrompt.getConfigSystem();
        if (CollectionUtils.isNotEmpty(knowledgeContentResults)) {
            String knowledgeContent = JsonUtils.serialize(knowledgeContentResults);
            prompt = prompt.replace("${knowledgeContent}", knowledgeContent);
        } else {
            prompt = prompt.replace("${knowledgeContent}", StringUtils.EMPTY);
        }
        if (CollectionUtils.isNotEmpty(translations)) {
            StringBuilder contentsBuilder = new StringBuilder();
            for (Translation translation : translations) {
                Long spk = translation.getSpk();
                String content = translation.getContent();
                contentsBuilder.append(spk).append(":").append(content).append(cn.com.poc.common.utils.StringUtils.LF);
            }
            prompt = prompt.replace("${meeting_content}", contentsBuilder.toString().length() > 25000 ? contentsBuilder.substring(0, 25000) : contentsBuilder);
        } else {
            prompt = prompt.replace("${meeting_content}", StringUtils.EMPTY);
        }

        prompt = prompt.replace("${fileContent}", fileContent);

        // 配置message
        List<Message> messages = new ArrayList<>();
        Message systemMessage = new Message();
        systemMessage.setContent(prompt);
        systemMessage.setRole(LLMRoleEnum.SYSTEM.getRole());
        messages.add(systemMessage);

        // 对话记录
        BizAgentApplicationDialoguesRecordEntity recordEntity = new BizAgentApplicationDialoguesRecordEntity();
        recordEntity.setDialogsId(dialogsId);
        recordEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        recordEntity.setMemberId(userId);
        List<BizAgentApplicationDialoguesRecordEntity> recordEntities = bizAgentApplicationDialoguesRecordService.findByExample(recordEntity, null);
        if (CollectionUtils.isNotEmpty(recordEntities)) {
            for (BizAgentApplicationDialoguesRecordEntity entity : recordEntities) {
                Message message = new Message();
                message.setContent(entity.getContent());
                message.setRole(entity.getRole());
                messages.add(message);
            }
        }
        //判断最后是否为User，若是则删除。
        if (CollectionUtils.isNotEmpty(messages)) {
            if (LLMRoleEnum.USER.getRole().equals(messages.get(messages.size() - 1).getRole())) {
                Long recordId = recordEntities.get(recordEntities.size() - 1).getId();
                bizAgentApplicationDialoguesRecordService.deletedById(recordId);
                messages.remove(messages.size() - 1);
            }
        }

        // 用户输入
        Message message = new Message();
        message.setContent(input);
        message.setRole(LLMRoleEnum.USER.getRole());
        messages.add(message);
        logger.info("--------- Build Messages dialogsId:{},messages:{}--------------", dialogsId, messages);
        return messages;
    }
}

