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

import cn.com.poc.agent_application.query.AgentApplicationDialoguesRecordQueryItem;
import cn.com.poc.agent_application.service.BizAgentApplicationDialoguesRecordService;
import cn.com.poc.ai_dialogues.aggregate.AiDialoguesService;
import cn.com.poc.ai_dialogues.constant.AiDialoguesTypeEnum;
import cn.com.poc.ai_dialogues.dto.AiDialoguesRecordDto;
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.StringUtils;
import cn.com.poc.expose.dto.DialoguesContextDto;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author alex.yao
 * @date 2025/6/19
 */
@Service
public class AiDialoguesServiceImpl implements AiDialoguesService {

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

    @Resource
    private BizAiDialoguesService bizAiDialoguesService;

    @Resource
    private BizFileUploadRecordService bizFileUploadRecordService;


    @Resource
    private BizAgentApplicationDialoguesRecordService bizAgentApplicationDialoguesRecordService;

    @Override
    public String create(AiDialoguesTypeEnum type, Long userId) throws Exception {
        return bizAiDialoguesService.create(type.getType(), userId);
    }

    @Override
    public String create(AiDialoguesTypeEnum type, String fileUrl, Long userId) throws Exception {
        return bizAiDialoguesService.create(type.getType(), fileUrl, userId);
    }

    @Override
    public AiDialoguesRecordDto dialoguesDetail(String dialoguesId, Long userId) throws Exception {
        logger.info("get ai dialogues detail dialoguesId:{}, userId:{}", dialoguesId, userId);
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(dialoguesId);
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> entities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            throw new BusinessException("对话不存在");
        }
        BizAiDialoguesEntity entity = entities.get(0);
        AiDialoguesRecordDto dto = new AiDialoguesRecordDto();
        dto.setDialoguesId(entity.getDialoguesId());
        dto.setDialoguesType(entity.getDialoguesType());
        dto.setTitle(entity.getTitle());
        dto.setMemberId(entity.getMemberId());
        if (StringUtils.isNotBlank(entity.getFileUrl())) {
            dto.setFileUrl(entity.getFileUrl());
            dto.setFileName(bizFileUploadRecordService.getFileNameByFileUrl(entity.getFileUrl()));
        }
        dto.setCreatedTime(entity.getCreatedTime());
        return dto;

    }

    @Override
    public List<AiDialoguesRecordDto> getList(AiDialoguesTypeEnum type, Long userId) throws Exception {
        logger.info("get ai dialogues list type:{}, userId:{}", type, userId);

        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesType(type.getType());
        bizAiDialoguesEntity.setMemberId(userId);
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> entities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);

        List<AiDialoguesRecordDto> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(entities)) {
            result = entities.stream()
                    .map(entity -> {
                        AiDialoguesRecordDto dto = new AiDialoguesRecordDto();
                        dto.setDialoguesId(entity.getDialoguesId());
                        dto.setDialoguesType(entity.getDialoguesType());
                        dto.setTitle(entity.getTitle());
                        dto.setMemberId(entity.getMemberId());
                        if (StringUtils.isNotBlank(entity.getFileUrl())) {
                            dto.setFileUrl(entity.getFileUrl());
                            dto.setFileName(bizFileUploadRecordService.getFileNameByFileUrl(entity.getFileUrl()));
                        }
                        dto.setCreatedTime(entity.getCreatedTime());
                        return dto;
                    })
                    .sorted(Comparator.comparing(AiDialoguesRecordDto::getCreatedTime).reversed())
                    .collect(Collectors.toList());
        }
        logger.debug("get ai dialogues list result:{}", result);
        return result;
    }

    @Override
    public void batchDelete(List<String> dialoguesIds, Long userId) throws Exception {
        logger.info("batchDelete dialoguesIds:{}", dialoguesIds);
        for (String dialoguesId : dialoguesIds) {
            BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
            bizAiDialoguesEntity.setDialoguesId(dialoguesId);
            bizAiDialoguesEntity.setMemberId(userId);
            bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
            List<BizAiDialoguesEntity> entities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
            if (CollectionUtils.isEmpty(entities)) {
                continue;
            }
            bizAiDialoguesService.deletedById(entities.get(0).getId());
        }
    }

    @Override
    public List<DialoguesContextDto> getDialogueContext(String dialogueId) {
        List<AgentApplicationDialoguesRecordQueryItem> items = bizAgentApplicationDialoguesRecordService.getDialogueRecord(dialogueId, null);
        if (CollectionUtils.isNotEmpty(items)) {
            return items.stream().map(value -> {
                        DialoguesContextDto dto = new DialoguesContextDto();
                        dto.setRole(value.getRole());
                        dto.setAgentId(value.getAgentId());
                        dto.setContent(value.getContent());
                        dto.setReasoningContent(value.getReasoningContent());
                        dto.setImageUrl(value.getImageUrl());
                        dto.setTimestamp(value.getTimestamp());
                        dto.setAgentTitle(value.getAgentTitle());
                        dto.setAgentAvatar(value.getAgentAvatar());
                        return dto;
                    }
            ).collect(Collectors.toList());
        }
        return null;
    }
}
