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

import cn.com.poc.agent_application.entity.CheckPluginUseEntity;
import cn.com.poc.agent_application.utils.AgentApplicationTools;
import cn.com.poc.expose.dto.DialoguesContextDto;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.FunctionCall;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Tool;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.ToolFunction;
import cn.com.poc.thirdparty.resource.demand.ai.entity.function.FunctionCallResult;
import cn.com.poc.thirdparty.resource.demand.ai.function.AbstractFunctionResult;
import cn.com.poc.thirdparty.resource.demand.ai.function.web_seach.WebSearchFunction;
import cn.com.poc.thirdparty.resource.demand.ai.function.web_seach.WebSearchFunctionResult;
import cn.com.poc.writing.dto.AiWritingDialoguesContextDto;
import cn.com.poc.writing.entity.BizAiWritingDialoguesRecordEntity;
import cn.com.poc.writing.query.AiWritingDialoguesRecordQueryItem;
import cn.com.poc.writing.service.BizAiWritingDialoguesRecordService;

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.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.utils.DocumentLoad;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.SSEUtil;
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.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.service.LLMService;
import cn.com.poc.writing.aggregate.AiWritingService;
import cn.com.poc.writing.dto.AiWritingExampleDto;
import cn.com.poc.writing.dto.AiWritingExampleTypeDto;
import cn.com.poc.writing.dto.AiWritingTitleGenerationDto;
import cn.com.poc.writing.entity.BizAiWritingExampleEntity;
import cn.com.poc.writing.entity.BizAiWritingExampleTypeEntity;
import cn.com.poc.writing.service.BizAiWritingExampleService;
import cn.com.poc.writing.service.BizAiWritingExampleTypeService;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author alex.yao
 * @date 2025/6/20
 */
@Service
public class AiWritingServiceImpl implements AiWritingService {


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

    @Resource
    private LLMService llmService;

    @Resource
    private BizAiDialoguesService bizAiDialoguesService;

    @Resource
    private BizAiWritingDialoguesRecordService bizAiWritingDialoguesRecordService;

    @Resource
    private BizAgentApplicationGcConfigService bizAgentApplicationGcConfigService;

    @Resource
    private KnowledgeService knowledgeService;

    @Resource
    private BizKnowledgeDocumentService bizKnowledgeDocumentService;

    @Resource
    private DemandKnowledgeService demandKnowledgeService;

    @Resource
    private BizAiWritingExampleService bizAiWritingExampleService;

    @Resource
    private BizAiWritingExampleTypeService bizAiWritingExampleTypeService;

    @Resource
    private WebSearchFunction webSearchFunction;


    @Override
    public void call(String dialoguesId, String fileUrl, String input, Integer[] knowledgeIds, Long userId, Boolean enableSearchEngine, Boolean enableDeepThinking) throws Exception {
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setDialoguesType(AiDialoguesTypeEnum.AI_WRITING.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);

        //更新标题
        if (StringUtils.isBlank(aiDialoguesEntity.getTitle())) { // 标题
            aiDialoguesEntity.setTitle(input.substring(0, Math.min(input.length(), 150)));
            aiDialoguesEntity = bizAiDialoguesService.update(aiDialoguesEntity);
        }
        BizAiWritingDialoguesRecordEntity dialoguesRecordEntity = new BizAiWritingDialoguesRecordEntity();
        dialoguesRecordEntity.setDialogsId(dialoguesId);
        dialoguesRecordEntity.setMemberId(userId);
        dialoguesRecordEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiWritingDialoguesRecordEntity> dialoguesRecordEntities = bizAiWritingDialoguesRecordService.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);
            }
        }

        //记录提问时间
        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));
        }

        //作文标题生成
        AiWritingTitleGenerationDto aiWritingTitleGenerationDto = titleGeneration(input);
        Boolean needWriting = aiWritingTitleGenerationDto.getNeedWriting();
        if (needWriting && StringUtils.isNotBlank(aiWritingTitleGenerationDto.getTitle())) {
            sseUtil.send(JsonUtils.serialize(aiWritingTitleGenerationDto));
        }

        // 插件调用
        ToolFunction toolFunction = getToolFunction(dialoguesId, input, enableSearchEngine, sseUtil);


        //组装请求参数
        List<Message> messages = buildMessages(dialoguesId, userId, input, fileUrl, knowledgeResult, aiWritingTitleGenerationDto, toolFunction);
        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel(enableDeepThinking ? "deepseek-chat" : "deepseek-v3");
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setStream(true);
        BufferedReader bufferedReader = llmService.chatChunk(largeModelResponse);
        LongtextDialoguesResult longtextDialoguesResult = textOutputStream(sseUtil, bufferedReader);


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

        // 保存AI回复记录
        BizAiWritingDialoguesRecordEntity assistantRecord = new BizAiWritingDialoguesRecordEntity();
        assistantRecord.setMemberId(userId);
        assistantRecord.setContent(longtextDialoguesResult.getMessage());
        assistantRecord.setReasoningContent(longtextDialoguesResult.getReasoningContent());
        if (needWriting) {
            assistantRecord.setDocumentTitle(aiWritingTitleGenerationDto.getTitle());
        }
        assistantRecord.setDialogsId(dialoguesId);
        assistantRecord.setRole(LLMRoleEnum.ASSISTANT.getRole());
        assistantRecord.setTimestamp(System.currentTimeMillis());

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

    private ToolFunction getToolFunction(String dialoguesId, String input, Boolean enableSearchEngine, SSEUtil sseUtil) throws IOException {
        ToolFunction toolFunction = null;
        if (enableSearchEngine) {
            List<Message> messages = new ArrayList<>();
            Message message = new Message();
            message.setRole("user");
            message.setContent(input);
            messages.add(message);

            String[] unitIds = new String[1];
            unitIds[0] = "web_search";
            List<Tool> tools = AgentApplicationTools.buildFunctionConfig(null, "N", dialoguesId, dialoguesId, unitIds, "N");
            CheckPluginUseEntity checkPluginUseEntity = AgentApplicationTools.checkPluginUse(messages, tools, null);
            FunctionCallResult functionCallResult = checkPluginUseEntity.getFunctionCallResult();
            if (functionCallResult != null && functionCallResult.isNeed()) {
                FunctionCall functionCall = functionCallResult.getFunctionCall();
                if (functionCallResult.isNeed() && functionCall != null && "web_search".equals(functionCall.getName())) {
                    AbstractFunctionResult<List<WebSearchFunctionResult>> functionResult = webSearchFunction.doFunction(functionCall.getArguments(), dialoguesId, null, null);
                    if (functionResult != null && CollectionUtils.isNotEmpty(functionResult.getFunctionResult())) {
                        List<WebSearchFunctionResult> webSearchFunctionResults = functionResult.getFunctionResult();
                        if (CollectionUtils.isNotEmpty(webSearchFunctionResults)) {
                            toolFunction = new ToolFunction();
                            toolFunction.setResult(JsonUtils.serialize(webSearchFunctionResults));
                            toolFunction.setName("web_search");
                            toolFunction.setArguments(functionCall.getArguments());
                            toolFunction.setDisplayFormat("json");
                            LargeModelDemandResult result = new LargeModelDemandResult();
                            result.setCode("0");
                            result.setFunction(toolFunction);
                            result.setDbChainResult(null);
                            result.setKnowledgeContentResult(null);
                            sseUtil.send(JsonUtils.serialize(result));
                        }
                    }
                }
            }
        }
        return toolFunction;
    }


    @Override
    public List<AiWritingExampleDto> example(String type) throws Exception {
        BizAiWritingExampleEntity bizAiWritingExample = new BizAiWritingExampleEntity();
        if (!"ALL".equals(type)) {
            bizAiWritingExample.setType(type);
        }
        List<BizAiWritingExampleEntity> exampleEntities = bizAiWritingExampleService.findByExample(bizAiWritingExample, null);
        if (CollectionUtils.isEmpty(exampleEntities)) {
            return Collections.emptyList();
        }
        return exampleEntities.stream().map(entity -> {
            AiWritingExampleDto dto = new AiWritingExampleDto();
            dto.setType(entity.getType());
            dto.setTitle(entity.getTitle());
            dto.setIcon(entity.getIcon());
            dto.setDescription(entity.getDescription());
            dto.setQuestion(entity.getQuestion());
            return dto;
        }).collect(Collectors.toList());
    }


    @Override
    public List<AiWritingExampleTypeDto> exampleType() throws Exception {

        List<BizAiWritingExampleTypeEntity> entities = bizAiWritingExampleTypeService.findByExample(new BizAiWritingExampleTypeEntity(), null);
        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }

        return entities.stream().map(entity -> {
            AiWritingExampleTypeDto dto = new AiWritingExampleTypeDto();
            dto.setType(entity.getType());
            dto.setName(entity.getName());
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public AiWritingTitleGenerationDto titleGeneration(String input) {
        String system = "## 角色\n" +
                "你的任务需要帮我判断用户是否需要进行【写作】\n" +
                "\n" +
                "## 输出\n" +
                "1.包含字段有  needWriting:bool    判断是否需要写作  true-需要 false-不需要 。 title-写作标题，如果需要则生成文章的标题\n" +
                "2.仅使用文本方式输出内容。\n" +
                "\n" +
                "## 输出案例\n" +
                "{\"needWriting\":true,\"title\":\"论人工智能发展对生产力的影响\"}";

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

        Message userMessage = new Message();
        userMessage.setContent(input);
        userMessage.setRole(LLMRoleEnum.USER.getRole());
        messages.add(userMessage);

        LargeModelResponse largeModelResponse = new LargeModelResponse();
        largeModelResponse.setModel("deepseek-v3");
        largeModelResponse.setMessages(messages.toArray(new Message[0]));
        largeModelResponse.setTopP(0.7F);
        largeModelResponse.setTemperature(0.5F);
        largeModelResponse.setStream(false);
        LargeModelDemandResult largeModelDemandResult = llmService.chat(largeModelResponse);
        if (largeModelDemandResult == null || StringUtils.isBlank(largeModelDemandResult.getMessage())) {
            throw new BusinessException("调用大模型失败");
        }

        String message = largeModelDemandResult.getMessage();
        int startEnd = message.indexOf("{");
        int endIndex = message.lastIndexOf("}");
        if (startEnd == -1 || endIndex == -1) {
            logger.error("解析内容失败, message:{}", message);
            throw new BusinessException("解析内容失败");
        }
        String substring = message.substring(startEnd, endIndex + 1);
        AiWritingTitleGenerationDto aiWritingTitleGenerationDto = JsonUtils.deSerialize(substring, AiWritingTitleGenerationDto.class);
        if (aiWritingTitleGenerationDto == null) {
            aiWritingTitleGenerationDto.setNeedWriting(false);
            aiWritingTitleGenerationDto.setTitle(StringUtils.EMPTY);
        }
        return aiWritingTitleGenerationDto;
    }

    private List<Message> buildMessages(String dialogsId, Long userId, String input, String fileUrl, List<KnowledgeContentResult> knowledgeContentResults, AiWritingTitleGenerationDto aiWritingTitleGenerationDto, ToolFunction toolFunction) throws Exception {
        // 获取对话提示词
        String promptCode = "AiWritingPrompt";
        BizAgentApplicationGcConfigEntity documentDialoguePrompt = bizAgentApplicationGcConfigService.getByConfigCode(promptCode);
        if (documentDialoguePrompt == null || StringUtils.isBlank(documentDialoguePrompt.getConfigSystem())) {
            logger.error("获取对话提示词失败 , configCode:{}", promptCode);
            throw new BusinessException("获取对话提示词失败");
        }

        // 加载文件
        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 (aiWritingTitleGenerationDto != null && aiWritingTitleGenerationDto.getNeedWriting()) {
            prompt = prompt.replace("${title}", aiWritingTitleGenerationDto.getTitle());
        } else {
            prompt = prompt.replace("${title}", StringUtils.EMPTY);
        }
        if (toolFunction != null) {
            prompt = prompt.replace("${toolFunction}", JsonUtils.serialize(toolFunction));
        }

        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);

        // 对话记录
        BizAiWritingDialoguesRecordEntity recordEntity = new BizAiWritingDialoguesRecordEntity();
        recordEntity.setDialogsId(dialogsId);
        recordEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        recordEntity.setMemberId(userId);
        List<BizAiWritingDialoguesRecordEntity> recordEntities = bizAiWritingDialoguesRecordService.findByExample(recordEntity, null);
        if (CollectionUtils.isNotEmpty(recordEntities)) {
            for (BizAiWritingDialoguesRecordEntity 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();
                bizAiWritingDialoguesRecordService.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;
    }


    @Override
    public List<AiWritingDialoguesContextDto> getDialogueContext(String dialogueId) {
        List<AiWritingDialoguesRecordQueryItem> items = bizAiWritingDialoguesRecordService.getDialogueRecord(dialogueId);
        if (CollectionUtils.isNotEmpty(items)) {
            return items.stream().map(value -> {
                        AiWritingDialoguesContextDto dto = new AiWritingDialoguesContextDto();
                        dto.setRole(value.getRole());
                        dto.setAgentId(value.getAgentId());
                        dto.setDocumentTitle(value.getDocumentTitle());
                        dto.setContent(value.getContent());
                        dto.setReasoningContent(value.getReasoningContent());
                        dto.setTimestamp(value.getTimestamp());
                        dto.setAgentTitle(value.getAgentTitle());
                        dto.setAgentAvatar(value.getAgentAvatar());
                        return dto;
                    }
            ).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 文本输出结果
     *
     * @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;
    }
}
