package cn.com.poc.agent_application.rest.impl;

import cn.com.poc.agent_application.aggregate.AgentApplicationInfoService;
import cn.com.poc.agent_application.convert.AgentApplicationInfoConvert;
import cn.com.poc.agent_application.domain.LargeModelInfo;
import cn.com.poc.agent_application.dto.*;
import cn.com.poc.agent_application.entity.*;
import cn.com.poc.agent_application.query.AgentApplicationInfoQueryCondition;
import cn.com.poc.agent_application.rest.AgentApplicationInfoRest;
import cn.com.poc.agent_application.service.*;
import cn.com.poc.agent_application.utils.AgentApplicationTools;
import cn.com.poc.common.annotation.RedisLimit;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.BlContext;
import cn.com.poc.data_analyze.aggregate.DataAnalyzeReportService;
import cn.com.poc.data_analyze.constants.DataAnalyzeChannelEnum;
import cn.com.poc.equity.aggregate.MemberEquityService;
import cn.com.poc.equity.aggregate.PointDeductionRulesService;
import cn.com.poc.equity.constants.ModifyEventEnum;
import cn.com.poc.equity.constants.RuleType;
import cn.com.poc.equity.domain.MemberEquityInfo;
import cn.com.poc.equity.domain.modifyEquityInfo.AgentUseModifyEventInfo;
import cn.com.poc.equity.entity.BizPointDeductionRulesEntity;
import cn.com.poc.equity.service.BizPointDeductionRulesService;
import cn.com.poc.knowledge.aggregate.KnowledgeService;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Tool;
import cn.com.poc.thirdparty.resource.demand.ai.function.long_memory.AgentLongMemoryEntity;
import cn.com.poc.thirdparty.resource.demand.ai.function.long_memory.LongMemory;
import cn.com.poc.thirdparty.resource.demand.ai.function.memory_variable_writer.MemoryVariableWriter;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.data.model.PagingInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class AgentApplicationInfoRestImpl implements AgentApplicationInfoRest {

    @Resource
    private BizAgentApplicationInfoService bizAgentApplicationInfoService;

    @Resource
    private AgentApplicationInfoService agentApplicationInfoService;

    @Resource
    private BizAgentApplicationPublishService bizAgentApplicationPublishService;

    @Resource
    private BizAgentApplicationLargeModelListService bizAgentApplicationLargeModelListService;

    @Resource
    private KnowledgeService knowledgeService;

    @Resource
    private BizMemberAgentApplicationCollectService bizMemberAgentApplicationCollectService;

    @Resource
    private BizAgentApplicationMallService bizAgentApplicationMallService;

    @Resource
    private PointDeductionRulesService pointDeductionRulesService;

    @Resource
    private MemberEquityService memberEquityService;

    @Resource
    private BizPointDeductionRulesService bizPointDeductionRulesService;

    @Resource
    private DataAnalyzeReportService dataAnalyzeReportService;


    @Override
    public AgentApplicationInfoDto saveVariableStructure(String agentId, List<Variable> variableStructure) {
        Assert.notNull(agentId);
        BizAgentApplicationInfoEntity bizAgentApplicationInfoEntity = bizAgentApplicationInfoService.saveVariableStructure(agentId, variableStructure);
        if (bizAgentApplicationInfoEntity == null) {
            throw new I18nMessageException("exception/application.does.not.exist");
        }
        return AgentApplicationInfoConvert.entityToDto(bizAgentApplicationInfoEntity);
    }

    @Override
    public List<AgentApplicationInfoDto> getListByMember(AgentApplicationInfoSearchDto dto, PagingInfo pagingInfo) throws Exception {
        UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
        Long userId = userBaseEntity.getUserId();
        AgentApplicationInfoQueryCondition condition = new AgentApplicationInfoQueryCondition();
        condition.setMemberId(userId);
        if (!StringUtils.isEmpty(dto.getQuery())) {
            condition.setQuery(dto.getQuery());
        }
        if (StringUtils.isNotBlank(dto.getPublishStatus())) {
            condition.setAgentPublishStatus(dto.getPublishStatus());
        }
        List<BizAgentApplicationInfoEntity> bizAgentApplicationInfoEntities = bizAgentApplicationInfoService.agentApplicationInfoQuery(condition, pagingInfo);
        List<AgentApplicationInfoDto> resultList = new ArrayList<>();
        for (BizAgentApplicationInfoEntity entity : bizAgentApplicationInfoEntities) {
            AgentApplicationInfoDto infoDto = AgentApplicationInfoConvert.entityToDto(entity);
            // 先判断有没有收藏的查询条件
            if (StringUtils.isNotBlank(dto.getIsCollect())) {
                // 如果有查询条件，则判断符不符合条件
                if (infoDto.getBaseInfo() != null) {
                    BizMemberAgentApplicationCollectEntity collect = bizMemberAgentApplicationCollectService.getByAgentId(infoDto.getBaseInfo().getAgentId());
                    // 如果符合条件，则把值加入
                    if (collect != null && collect.getIsCollect().equals(dto.getIsCollect())) {
                        infoDto.setIsCollect(collect.getIsCollect());
                    } else if (collect == null && CommonConstant.IsDeleted.N.equals(dto.getIsCollect())) {
                        infoDto.setIsCollect(CommonConstant.IsDeleted.N);
                    } else {
                        // 如果不符合条件，则continue
                        continue;
                    }
                } else {
                    continue;
                }
            } else {
                // 如何没有查询条件，则直接按照原来的逻辑走
                // 设置当前用户是否收藏了
                if (infoDto.getBaseInfo() != null) {
                    BizMemberAgentApplicationCollectEntity collect = bizMemberAgentApplicationCollectService.getByAgentId(infoDto.getBaseInfo().getAgentId());
                    if (collect != null) {
                        infoDto.setIsCollect(collect.getIsCollect());
                    } else {
                        infoDto.setIsCollect(CommonConstant.IsDeleted.N);
                    }
                }
            }
            // 判断是否发布了，若发布则设置agentPublishId
            BizAgentApplicationPublishEntity publishEntity = bizAgentApplicationPublishService.getByAgentId(entity.getAgentId());
            if (publishEntity != null) {
                infoDto.setAgentPublishId(publishEntity.getId());
                // 设置当前作品是否上架
                BizAgentApplicationMallEntity mallEntity = bizAgentApplicationMallService.getByAgentPublishId(publishEntity.getId());
                if (mallEntity != null) {
                    infoDto.setIsSale(mallEntity.getIsSale());
                } else {
                    infoDto.setIsSale(CommonConstant.IsDeleted.N);
                }
            } else {
                infoDto.setAgentPublishId(null);
            }
            resultList.add(infoDto);
        }
        return resultList;

    }

    @Override
    public AgentApplicationInfoDto saveOrUpdate(AgentApplicationInfoDto dto) throws Exception {
        Assert.notNull(dto);
        Assert.notNull(dto.getBaseInfo());
        Assert.notNull(dto.getCommConfig());
        Assert.notNull(dto.getCommModelConfig());
        Assert.notNull(dto.getKnowledgeConfig());

        UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
        if (userBaseEntity == null) {
            throw new I18nMessageException("exception/user.does.not.exist");
        }
        Long userId = userBaseEntity.getUserId();
        dto.getBaseInfo().setMemberId(userId.intValue());
        BizAgentApplicationInfoEntity entity = AgentApplicationInfoConvert.dtoToEntity(dto);
        //次数检查
        if (StringUtils.isBlank(entity.getAgentId())) {
            MemberEquityInfo equityInfo = memberEquityService.getEquityInfo(userId);
            if (equityInfo.getAgentNum() > 0 && equityInfo.getAgentNum() <= equityInfo.getUsedAgentNum()) {
                throw new I18nMessageException("exception/create.num.limit");
            }
        }
        return AgentApplicationInfoConvert.entityToDto(agentApplicationInfoService.saveOrUpdate(entity));
    }


    public AgentApplicationInfoDto update(AgentApplicationInfoDto dto) throws Exception {
        Assert.notNull(dto);
        Assert.notNull(dto.getBaseInfo());
        Assert.notNull(dto.getBaseInfo().getAgentId());
        Assert.notNull(dto.getCommConfig());
        Assert.notNull(dto.getCommModelConfig());
        Assert.notNull(dto.getKnowledgeConfig());
        BizAgentApplicationInfoEntity entity = AgentApplicationInfoConvert.dtoToEntity(dto);
        return AgentApplicationInfoConvert.entityToDto(bizAgentApplicationInfoService.update(entity));
    }

    @Override
    public AgentApplicationInfoDto getInfo(String agentId) throws Exception {
        Assert.notNull(agentId);
        BizAgentApplicationInfoEntity entity = bizAgentApplicationInfoService.getByAgentId(agentId);
        if (entity == null) {
            throw new I18nMessageException("exception/application.does.not.exist");
        }
        return AgentApplicationInfoConvert.entityToDto(entity);
    }

    @Override
    public void delete(String agentId) throws Exception {
        Assert.notNull(agentId);
        agentApplicationInfoService.deletedAgentApplication(agentId);
    }

    @Override
    public boolean updateAndPublish(AgentApplicationInfoDto dto) throws Exception {
        Assert.notNull(dto);
        Assert.notNull(dto.getBaseInfo());
        Assert.notNull(dto.getBaseInfo().getAgentId());
        Assert.notNull(dto.getBaseInfo().getAgentTitle());
        Assert.notNull(dto.getCommConfig());
        Assert.notNull(dto.getCommModelConfig());
        Assert.notNull(dto.getKnowledgeConfig());
        BizAgentApplicationInfoEntity bizAgentApplicationInfoEntity = AgentApplicationInfoConvert.dtoToEntity(dto);
        agentApplicationInfoService.updateAndPublish(bizAgentApplicationInfoEntity);
        return true;
    }

    @Override
    public void preview(AgentApplicationPreviewDto dto, HttpServletResponse httpServletResponse) throws Exception {
        Assert.notNull(dto);
        Assert.notNull(dto.getAgentId());
        Assert.notEmpty(dto.getMessages());
        String reduceSn = "";
        try {
            UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
            String agentId = dto.getAgentId();
            String dialogueId = dto.getAgentId();
            List<String> fileUrls = dto.getFileUrls();
            BizAgentApplicationInfoEntity infoEntity = bizAgentApplicationInfoService.getByAgentId(agentId);
            if (infoEntity == null) {
                throw new I18nMessageException("exception/application.does.not.exist");
            }
            // 判断文件是否为空，如果不为空
            AgentApplicationTools.checkDialogueContentIsEmpty(fileUrls);

            //获取知识库配置
            List<Integer> kdIds = knowledgeService.getKdIdsByKnowledgeInfoIds(infoEntity.getKnowledgeIds());

            //配置对话function
            List<Tool> tools = AgentApplicationTools.buildFunctionConfig(infoEntity.getVariableStructure(), infoEntity.getIsLongMemory(), dialogueId, agentId, infoEntity.getUnitIds(), infoEntity.getIsDocumentParsing());

            //获取对话图片
            List<String> imageUrls = AgentApplicationTools.getMessageImageUrl(dto.getMessages());

            //对话大模型配置
            String model = StringUtils.isNotBlank(dto.getModelNickName()) ? dto.getModelNickName() : infoEntity.getLargeModel();
            Float topP = dto.getTopP() == null ? infoEntity.getTopP() : dto.getTopP();
            Float temperature = dto.getTemperature() == null ? infoEntity.getTemperature() : dto.getTemperature();
            String agentSystem = StringUtils.isBlank(dto.getAgentSystem()) ? infoEntity.getAgentSystem() : dto.getAgentSystem();
            Integer communicationTurn = dto.getCommunicationTurn() == null ? infoEntity.getCommunicationTurn(): dto.getCommunicationTurn();

            // 判断是否调用function
            //计算扣分数
            CheckPluginUseEntity checkPluginUseEntity = AgentApplicationTools.checkPluginUse(dto.getMessages(), tools,fileUrls,imageUrls);
            Long pointDeductionNum = pointDeductionRulesService.calculatePointDeductionNum(model, communicationTurn, checkPluginUseEntity.getDeductionTools());
            AgentUseModifyEventInfo agentUseModifyEventInfo = new AgentUseModifyEventInfo();
            agentUseModifyEventInfo.setAgentId(agentId);
            agentUseModifyEventInfo.setIsPublish(CommonConstant.IsDeleted.N);
            reduceSn = memberEquityService.reducePoint(userBaseEntity.getUserId(), pointDeductionNum, ModifyEventEnum.use, agentUseModifyEventInfo);
            //调用应用服务
            agentApplicationInfoService.callAgentApplication(agentId, dialogueId, model,
                    agentSystem, kdIds.toArray(new Integer[0]), communicationTurn, topP,
                    temperature, dto.getMessages(), tools, checkPluginUseEntity.getFunctionCallResult(), dto.getFileUrls(), true, imageUrls, httpServletResponse);
            //数据采集
            if (StringUtils.isBlank(dto.getChannel())) {
                dto.setChannel(DataAnalyzeChannelEnum.preview.getChannel());
            }
            dataAnalyzeReportService.dataReport(dto.getAgentId(), DataAnalyzeChannelEnum.valueOf(dto.getChannel()), userBaseEntity.getUserId(), userBaseEntity.getUserId(), pointDeductionNum);
        } catch (Exception e) {
            httpServletResponse.setContentType("text/event-stream");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("data: {\"code\":-1,\"message\":\"" + e.getLocalizedMessage() + "\"} \n\n");
            writer.write("data: [DONE]\n\n");
            writer.flush();
            memberEquityService.rollbackPoint(reduceSn);
        }
    }


    @Override
    public List<BizAgentApplicationLargeModelListDto> getLargeModelList() throws Exception {
        List<BizAgentApplicationLargeModelListEntity> entities = bizAgentApplicationLargeModelListService.findByExample(new BizAgentApplicationLargeModelListEntity(), null);
        Map<String, List<BizAgentApplicationLargeModelListEntity>> map = entities.stream()
                .collect(Collectors.groupingBy(BizAgentApplicationLargeModelListEntity::getOwner));

        List<BizAgentApplicationLargeModelListDto> result = new ArrayList<>();
        for (String owner : map.keySet()) {
            BizAgentApplicationLargeModelListDto dto = new BizAgentApplicationLargeModelListDto();
            List<BizAgentApplicationLargeModelListEntity> modelListEntities = map.get(owner);
            dto.setOwner(owner);
            dto.setModels(modelListEntities.stream().map(BizAgentApplicationLargeModelListEntity::getModelNickName).collect(Collectors.toList()));
            dto.setIcon(modelListEntities.get(0).getIconUrl());
            result.add(dto);
        }
        return result;
    }

    @Override
    public List<BizAgentApplicationLargeModelListV2Dto> getLargeModelListV2() throws Exception {
        List<BizAgentApplicationLargeModelListEntity> entities = bizAgentApplicationLargeModelListService.findByExample(new BizAgentApplicationLargeModelListEntity(), null);
        Map<String, List<BizAgentApplicationLargeModelListEntity>> map = entities.stream()
                .collect(Collectors.groupingBy(BizAgentApplicationLargeModelListEntity::getOwner));
        BizPointDeductionRulesEntity bizPointDeductionRulesEntity = new BizPointDeductionRulesEntity();
        bizPointDeductionRulesEntity.setRuleType(RuleType.MODEL.getRuleType());
        bizPointDeductionRulesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizPointDeductionRulesEntity> rulesEntityList = bizPointDeductionRulesService.findByExample(bizPointDeductionRulesEntity, null);
        Map<String, List<BizPointDeductionRulesEntity>> rulesMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(rulesEntityList)) {
            rulesMap = rulesEntityList.stream().collect(Collectors.groupingBy(BizPointDeductionRulesEntity::getRelationId));
        }

        List<BizAgentApplicationLargeModelListV2Dto> result = new ArrayList<>();
        for (String owner : map.keySet()) {
            BizAgentApplicationLargeModelListV2Dto dto = new BizAgentApplicationLargeModelListV2Dto();
            List<BizAgentApplicationLargeModelListEntity> modelListEntities = map.get(owner);
            dto.setOwner(owner);
            List<LargeModelInfo> largeModelInfos = new ArrayList<>();
            for (BizAgentApplicationLargeModelListEntity modelListEntity : modelListEntities) {
                LargeModelInfo largeModelInfo = new LargeModelInfo();
                largeModelInfo.setModelNickName(modelListEntity.getModelNickName());
                Long pointNumber = 0L;
                if (rulesMap.containsKey(modelListEntity.getModelNickName())) {
                    List<BizPointDeductionRulesEntity> rulesEntities = rulesMap.get(modelListEntity.getModelNickName());
                    pointNumber = rulesEntities.get(0).getNumber();
                }
                BigDecimal points = new BigDecimal(pointNumber).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                largeModelInfo.setPoints(points);
                largeModelInfos.add(largeModelInfo);
            }
            dto.setModels(largeModelInfos);
            dto.setIcon(modelListEntities.get(0).getIconUrl());
            result.add(dto);
        }
        return result;
    }

    @Override
    public BizAgentApplicationLargeModelListDto getLargeModelInfo(String query) throws Exception {
        Assert.notNull(query);
        BizAgentApplicationLargeModelListEntity bizAgentApplicationLargeModelListEntity = new BizAgentApplicationLargeModelListEntity();
        bizAgentApplicationLargeModelListEntity.setModelNickName(query);
        List<BizAgentApplicationLargeModelListEntity> entities = bizAgentApplicationLargeModelListService.findByExample(bizAgentApplicationLargeModelListEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            throw new I18nMessageException("exception/model.not.exist");
        }
        BizAgentApplicationLargeModelListEntity entity = entities.get(0);
        BizAgentApplicationLargeModelListDto result = new BizAgentApplicationLargeModelListDto();
        result.setModels(ListUtil.toList(entity.getModelNickName()));
        result.setOwner(entity.getOwner());
        result.setIcon(entity.getIconUrl());
        return result;
    }

    @Override
    public BizAgentApplicationLargeModelListV2Dto getLargeModelInfoV2(String query) throws Exception {
        Assert.notNull(query);
        BizAgentApplicationLargeModelListEntity bizAgentApplicationLargeModelListEntity = new BizAgentApplicationLargeModelListEntity();
        bizAgentApplicationLargeModelListEntity.setModelNickName(query);
        List<BizAgentApplicationLargeModelListEntity> entities = bizAgentApplicationLargeModelListService.findByExample(bizAgentApplicationLargeModelListEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            throw new I18nMessageException("exception/model.not.exist");
        }
        BizAgentApplicationLargeModelListEntity entity = entities.get(0);

        BizPointDeductionRulesEntity bizPointDeductionRulesEntity = new BizPointDeductionRulesEntity();
        bizPointDeductionRulesEntity.setRuleType(RuleType.MODEL.getRuleType());
        bizPointDeductionRulesEntity.setRelationId(query);
        bizPointDeductionRulesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizPointDeductionRulesEntity> rulesEntityList = bizPointDeductionRulesService.findByExample(bizPointDeductionRulesEntity, null);

        BizAgentApplicationLargeModelListV2Dto result = new BizAgentApplicationLargeModelListV2Dto();

        List<LargeModelInfo> largeModelInfos = new ArrayList<>();
        LargeModelInfo largeModelInfo = new LargeModelInfo();
        largeModelInfo.setModelNickName(entity.getModelNickName());
        Long pointNumber = 0L;
        if (CollectionUtils.isNotEmpty(rulesEntityList)) {
            pointNumber = rulesEntityList.get(0).getNumber();
        }
        BigDecimal points = new BigDecimal(pointNumber).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        largeModelInfo.setPoints(points);
        largeModelInfos.add(largeModelInfo);
        result.setModels(largeModelInfos);
        result.setOwner(entity.getOwner());
        result.setIcon(entity.getIconUrl());
        return result;
    }

    @Override
    public void createAgentSystem(AgentApplicationGCDto dto, HttpServletResponse response) throws Exception {
        Assert.notNull(dto.getInput());
        agentApplicationInfoService.createAgentSystem(dto.getInput(), response);
    }

    @Override
    public List<String> createFeaturedQuestions(AgentApplicationGCDto dto) {
        return agentApplicationInfoService.createFeaturedQuestions(dto.getAgentTitle(), dto.getAgentDesc());
    }

    @Override
    public String createPreamble(AgentApplicationGCDto dto) {
        return agentApplicationInfoService.createPreamble(dto.getAgentTitle(), dto.getAgentDesc(), dto.getAgentSystem());
    }

    @Override
    public String createAgentApplicationAvatar(AgentApplicationGCDto dto) throws Exception {
        Assert.isTrue(StringUtils.isNotBlank(dto.getAgentDesc()) || StringUtils.isNotBlank(dto.getAgentTitle()));
        return agentApplicationInfoService.createAgentIcon(dto.getAgentTitle(), dto.getAgentDesc());
    }

    @Override
    public AgentApplicationGCDto createAgentTitleAndDesc(AgentApplicationGCDto dto) {
        Assert.notNull(dto.getInput());
        CreateAgentTitleAndDescEntity entity = agentApplicationInfoService.createAgentTitleAndDesc(dto.getInput());
        if (null == entity) {
            throw new I18nMessageException("exception/generation.failed.please.try.again.later");
        }
        AgentApplicationGCDto result = new AgentApplicationGCDto();
        result.setAgentTitle(entity.getAgentTitle());
        result.setAgentDesc(entity.getAgentDesc());
        return result;
    }

    @Override
    @RedisLimit(key = "collect:agent_person", currentUser = true, count = 1, timeout = 1, exceptionInfo = "exception/too.many.requests")
    public void collectOrCancelAgentInPerson(String agentId) throws Exception {
        Assert.notNull(agentId);
        agentApplicationInfoService.collectOrCancelAgentInPerson(agentId);
    }

    @Override
    public List<AgentApplicationValueMemoryDto> getVariableList(String agentId) {
        List<AgentApplicationValueMemoryDto> result = new ArrayList<>();
        BizAgentApplicationInfoEntity infoEntity = bizAgentApplicationInfoService.getByAgentId(agentId);
        Map<Object, Object> map = MemoryVariableWriter.get(agentId + ":" + agentId);
        List<Variable> variableStructure = infoEntity.getVariableStructure();
        if (MapUtils.isEmpty(map)) {
            if (CollectionUtils.isEmpty(variableStructure)) {
                return result;
            }
            for (Variable variable : variableStructure) {
                AgentApplicationValueMemoryDto valueMemoryDto = new AgentApplicationValueMemoryDto();
                valueMemoryDto.setKey(variable.getKey());
                valueMemoryDto.setValue(variable.getVariableDefault());
                result.add(valueMemoryDto);
            }
        } else {
            for (Variable variable : variableStructure) {
                AgentApplicationValueMemoryDto valueMemoryDto = new AgentApplicationValueMemoryDto();
                valueMemoryDto.setKey(variable.getKey());
                valueMemoryDto.setValue(map.containsKey(variable.getKey()) ? map.get(variable.getKey()).toString() : variable.getVariableDefault());
                result.add(valueMemoryDto);
            }
        }
        return result;
    }

    @Override
    public List<AgentLongMemoryDto> getLongMemoryList(String agentId) {
        Assert.notNull(agentId);
        List<AgentLongMemoryEntity> longMemoryEntities = LongMemory.get(AgentApplicationTools.identifier(agentId, agentId));
        return longMemoryEntities.stream().map(value -> {
            AgentLongMemoryDto agentLongMemoryDto = new AgentLongMemoryDto();
            BeanUtil.copyProperties(value, agentLongMemoryDto);
            return agentLongMemoryDto;
        }).sorted(Comparator.comparing(AgentLongMemoryDto::getTimestamp).reversed()).collect(Collectors.toList());
    }

    @Override
    public void deleteLongMemoryByKey(String agentId, String timestamp) {
        Assert.notNull(agentId);
        Assert.notNull(timestamp);
        LongMemory.delByKey(agentId, timestamp);
    }

    @Override
    public void deleteLongMemory(String agentId) {
        Assert.notNull(agentId);
        LongMemory.clean(agentId);
    }
}