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

import cn.com.poc.agent_application.aggregate.AgentApplicationService;
import cn.com.poc.agent_application.constant.AgentApplicationDialoguesRecordConstants;
import cn.com.poc.agent_application.entity.*;
import cn.com.poc.agent_application.service.BizAgentApplicationDialoguesRecordService;
import cn.com.poc.agent_application.service.BizAgentApplicationPublishService;
import cn.com.poc.agent_application.utils.AgentApplicationTools;
import cn.com.poc.ai_bi.aggregate.AiBiService;
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.StringUtils;
import cn.com.poc.knowledge.aggregate.KnowledgeService;
import cn.com.poc.thirdparty.resource.demand.ai.constants.KnowledgeSearchTypeEnum;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Message;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Tool;
import cn.com.poc.thirdparty.resource.demand.ai.entity.function.FunctionCallResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

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

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


    private final String FMX_PARAM_AGENT_ID_CODE = "ai_bi.agent_id";

    @Resource
    private FmxParamConfigService fmxParamConfigService;

    @Resource
    private BizAiDialoguesService bizAiDialoguesService;

    @Resource
    private AgentApplicationService agentApplicationService;

    @Resource
    private KnowledgeService knowledgeService;

    @Resource
    private BizAgentApplicationPublishService bizAgentApplicationPublishService;

    @Resource
    private BizAgentApplicationDialoguesRecordService bizAgentApplicationDialoguesRecordService;


    @Override
    public void call(String dialoguesId, String input, String fileUrl, Integer[] knowledgeIds, Integer[] databaseIds, Long userId) throws Exception {
        String agentId = fmxParamConfigService.getParam(FMX_PARAM_AGENT_ID_CODE);
        if (StringUtils.isBlank(agentId)) {
            logger.error("获取智能问数对话agentId失败");
            throw new BusinessException("对话异常");
        }

        // 获取Agent基本信息
        BizAgentApplicationPublishEntity infoEntity = bizAgentApplicationPublishService.getByAgentId(agentId);
        if (infoEntity == null) {
            logger.error("获取智能问数对话agent信息失败");
            throw new BusinessException("对话异常");
        }

        // 保存对话基础信息
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> bizAiDialoguesEntities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isEmpty(bizAiDialoguesEntities)) {
            logger.error("dialogues id 不存在，请重新创建");
            throw new BusinessException("对话异常");
        }

        // 保存标题信息
        if (StringUtils.isBlank(bizAiDialoguesEntities.get(0).getTitle())) {
            BizAiDialoguesEntity portalDialoguesEntity = bizAiDialoguesEntities.get(0);
            portalDialoguesEntity.setTitle(input);
            bizAiDialoguesService.update(portalDialoguesEntity);
        }

        // 获取对话配置
        String largeModel = infoEntity.getLargeModel();//获取模型
        String agentSystem = infoEntity.getAgentSystem();//获取Agent角色词
        List<Integer> kdIds = knowledgeService.getKdIdsByKnowledgeInfoIds(knowledgeIds);//获取知识库ids
        List<Message> messages = AgentApplicationTools.buildMessage(dialoguesId, agentId, userId, input);//构建消息
        List<Tool> tools = AgentApplicationTools.buildFunctionConfig(infoEntity.getVariableStructure(), infoEntity.getIsLongMemory(), dialoguesId, agentId, infoEntity.getUnitIds(), infoEntity.getIsDocumentParsing());//构建函数配置

        List<String> fileUrls = new ArrayList<>();//构建文件链接
        if (StringUtils.isNotBlank(fileUrl)) {
            fileUrls.add(fileUrl);
        }
        CheckPluginUseEntity checkPluginUseEntity = AgentApplicationTools.checkPluginUse(messages, tools, fileUrls);//检查插件使用
        FunctionCallResult functionCallResult = checkPluginUseEntity.getFunctionCallResult();//函数调用结果
        boolean stream = true;//是否流式输出
        KnowledgeSearchTypeEnum knowledgeSearchTypeEnum = KnowledgeSearchTypeEnum.valueOf(infoEntity.getKnowledgeSearchType());//知识库检索方式
        KnowledgeSuperclassProblemConfig knowledgeSuperclassProblemConfig = new KnowledgeSuperclassProblemConfig();//知识库超纲配置
        knowledgeSuperclassProblemConfig.setKnowledgeResponseType(infoEntity.getKnowledgeResponseType());//知识库回复类型
        knowledgeSuperclassProblemConfig.setKnowledgeCustomResponse(infoEntity.getKnowledgeCustomResponse());//知识库自定义回复

        // 记录用户输入时间戳
        Long inputTimestamp = System.currentTimeMillis();

        // 调用对话Agent
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        AgentResultEntity agentResultEntity = agentApplicationService.callAgentApplication(agentId,
                dialoguesId,
                largeModel,
                agentSystem,
                kdIds.toArray(new Integer[0]),
                databaseIds,
                infoEntity.getCommunicationTurn(),
                infoEntity.getTopP(),
                infoEntity.getTemperature(),
                messages,
                tools,
                functionCallResult,
                stream,
                infoEntity.getKnowledgeSimilarity(),
                infoEntity.getKnowledgeNResult(),
                knowledgeSearchTypeEnum,
                knowledgeSuperclassProblemConfig,
                response
        );

        //保存对话记录
        //用户输入记录
        BizAgentApplicationDialoguesRecordEntity inputRecord = new BizAgentApplicationDialoguesRecordEntity();
        inputRecord.setAgentId(agentId);
        inputRecord.setMemberId(userId);
        inputRecord.setContent(input);
        inputRecord.setDialogsId(dialoguesId);
        inputRecord.setRole(AgentApplicationDialoguesRecordConstants.ROLE.USER);
        inputRecord.setTimestamp(inputTimestamp);
        bizAgentApplicationDialoguesRecordService.save(inputRecord);
        //AI输出记录
        BizAgentApplicationDialoguesRecordEntity outputRecord = new BizAgentApplicationDialoguesRecordEntity();
        outputRecord.setRole(AgentApplicationDialoguesRecordConstants.ROLE.ASSISTANT);
        outputRecord.setAgentId(infoEntity.getAgentId());
        outputRecord.setDialogsId(dialoguesId);
        outputRecord.setMemberId(userId);
        outputRecord.setTimestamp(System.currentTimeMillis());
        outputRecord.setContent(agentResultEntity.getMessage());
        outputRecord.setReasoningContent(agentResultEntity.getReasoningContent());
        bizAgentApplicationDialoguesRecordService.save(outputRecord);
    }
}
