package cn.com.poc.message.service.impl;

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.JsonUtils;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.meeting.analysis.FeaturedQuestionAnalyzer;
import cn.com.poc.meeting.analysis.KeyWordAnalyzer;
import cn.com.poc.meeting.analysis.SummaryAnalyzer;
import cn.com.poc.meeting.analysis.ThemeAnalyzer;
import cn.com.poc.meeting.cache.KeyWordCounter;
import cn.com.poc.meeting.constants.MeetingAssistantConstantEnum;
import cn.com.poc.meeting.entity.BizMeetingAssistantAnalysisTaskEntity;
import cn.com.poc.meeting.service.BizMeetingAssistantAnalysisTaskService;
import cn.com.poc.message.entity.meeting.AnalysisTaskUpdateMessage;
import cn.com.poc.message.entity.meeting.MeetingAssistantAnalysisMessage;
import cn.com.poc.message.entity.meeting.MeetingAssistantGenerateAnalysisContentMessage;
import cn.com.poc.message.service.MeetingAssistantAnalysisConsumerService;
import cn.com.poc.message.service.MeetingAssistantAnalysisProducerService;
import cn.com.poc.message.topic.MeetingAssistantTopic;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.Translation;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.tumbleweed.client.annotation.Consumer;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
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.List;
import java.util.Map;

@Service
public class MeetingAssistantAnalysisConsumerServiceImpl implements MeetingAssistantAnalysisConsumerService {

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

    @Resource
    private BizMeetingAssistantAnalysisTaskService bizMeetingAssistantAnalysisTaskService;

    @Resource
    private MeetingAssistantAnalysisProducerService meetingAssistantAnalysisProducerService;

    @Resource
    private BizAiDialoguesService bizAiDialoguesService;


    @Override
    @Consumer(topic = MeetingAssistantTopic.CONTENT_ANALYSIS, scale = 2)
    public void analysisTask(MeetingAssistantAnalysisMessage meetingAssistantAnalysisMessage) {

        //更新状态
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(meetingAssistantAnalysisMessage.getDiaguesId());
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> taskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(taskEntities)) {
            throw new BusinessException("无法找到对应的会议内容分析任务");
        }

        BizMeetingAssistantAnalysisTaskEntity taskEntity = taskEntities.get(0);
        if (MeetingAssistantConstantEnum.COMPLETED.getStatus().equals(taskEntity.getAnalysisStatus())) {
            logger.info("------------ 任务已完成，无需重复生成 ,diaguesId:{}------------", meetingAssistantAnalysisMessage.getDiaguesId());
            return;
        }

        StringBuilder contentsBuilder = new StringBuilder();
        List<Translation> translations = meetingAssistantAnalysisMessage.getTranslations();
        for (Translation translation : translations) {
            Long spk = translation.getSpk();
            String content = translation.getContent();
            contentsBuilder.append(spk).append(":").append(content).append(StringUtils.LF);
        }

        MeetingAssistantGenerateAnalysisContentMessage analysisContentMessage = new MeetingAssistantGenerateAnalysisContentMessage();
        analysisContentMessage.setContent(contentsBuilder.toString());
        analysisContentMessage.setDiaguesId(meetingAssistantAnalysisMessage.getDiaguesId());

        if (StringUtils.isBlank(taskEntity.getFeaturedQuestionsGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getFeaturedQuestionsGenerateStatus())) {
            meetingAssistantAnalysisProducerService.generateFeaturedQuestion(analysisContentMessage);
            taskEntity.setFeaturedQuestionsGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        }
//        if (StringUtils.isBlank(taskEntity.getThemeGenerateStatus())
//                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getThemeGenerateStatus())) {
//            meetingAssistantAnalysisProducerService.generateTheme(analysisContentMessage);
//            taskEntity.setThemeGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
//        }

        if (StringUtils.isBlank(taskEntity.getMeetingSummaryGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getMeetingSummaryGenerateStatus())) {
            meetingAssistantAnalysisProducerService.generateSummry(analysisContentMessage);
            taskEntity.setMeetingSummaryGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        }

        if (StringUtils.isBlank(taskEntity.getKeyWordGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getKeyWordGenerateStatus())) {
            meetingAssistantAnalysisProducerService.keyWord(analysisContentMessage);
            taskEntity.setKeyWordGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        }
        logger.info("---- 更新会议内容分析任务状态 ,entity:{}------", JsonUtils.serialize(bizMeetingAssistantAnalysisTaskEntity));
        taskEntity.setAnalysisStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        bizMeetingAssistantAnalysisTaskService.update(taskEntity);
    }

    @Override
    @Consumer(topic = MeetingAssistantTopic.UPDATE_ANALYSIS, retry = true)
    public void analysisTaskUpdate(AnalysisTaskUpdateMessage message) {
        logger.info("-------- update meeting assistant analysis task , message:{} ", message);
        Long id = message.getId();
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = bizMeetingAssistantAnalysisTaskService.get(id);
        if (bizMeetingAssistantAnalysisTaskEntity == null) {
            logger.error("------------- can not find meeting assistant analysis task , id:{} -------------", id);
            return;
        }

        CopyOptions copyOptions = new CopyOptions();
        copyOptions.setIgnoreNullValue(true);
        BeanUtil.copyProperties(message, bizMeetingAssistantAnalysisTaskEntity, copyOptions);
        logger.info("-------- update meeting  meeting assistant analysis , entity:{}----------", bizMeetingAssistantAnalysisTaskEntity);
        if (checkAllIsCompleted(bizMeetingAssistantAnalysisTaskEntity)) {
            bizMeetingAssistantAnalysisTaskEntity.setAnalysisStatus(MeetingAssistantConstantEnum.COMPLETED.getStatus());
        } else if (checkExistFaild(bizMeetingAssistantAnalysisTaskEntity)) {
            bizMeetingAssistantAnalysisTaskEntity.setAnalysisStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
        }
        bizMeetingAssistantAnalysisTaskService.update(bizMeetingAssistantAnalysisTaskEntity);
        //更新会话标题
        logger.info("-------- update dialogues title -------------");
        BizAiDialoguesEntity bizAiDialoguesEntity = new BizAiDialoguesEntity();
        bizAiDialoguesEntity.setDialoguesId(bizMeetingAssistantAnalysisTaskEntity.getDiaguesId());
        bizAiDialoguesEntity.setDialoguesType(AiDialoguesTypeEnum.MEETING_ASSISTANT.getType());
        bizAiDialoguesEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizAiDialoguesEntity> aiDialoguesEntities = bizAiDialoguesService.findByExample(bizAiDialoguesEntity, null);
        if (CollectionUtils.isNotEmpty(aiDialoguesEntities)) {
            BizAiDialoguesEntity updateAiDialoguesEntity = aiDialoguesEntities.get(0);
            if (StringUtils.isNotBlank(bizMeetingAssistantAnalysisTaskEntity.getThemeContent())
                    && !bizMeetingAssistantAnalysisTaskEntity.getThemeContent().equals(updateAiDialoguesEntity.getTitle())) {
                updateAiDialoguesEntity.setTitle(bizMeetingAssistantAnalysisTaskEntity.getThemeContent());
                bizAiDialoguesService.update(updateAiDialoguesEntity);
                logger.info("------- update dialogues title success , title:{} -----------", updateAiDialoguesEntity.getTitle());
            }
        }

    }

    @Override
    @Consumer(topic = MeetingAssistantTopic.GENERATE_FEATURED_QUESTION, retry = true, scale = 2)
    public void generateFeaturedQuestion(MeetingAssistantGenerateAnalysisContentMessage message) {
        // 执行处理器
        FeaturedQuestionAnalyzer featuredQuestionAnalyzer = new FeaturedQuestionAnalyzer();
        List<String> featuredQuestionList = featuredQuestionAnalyzer.run(message.getContent());

        // 更新状态
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(message.getDiaguesId());
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> taskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(taskEntities)) {
            throw new BusinessException("无法找到对应的会议内容分析任务");
        }
        BizMeetingAssistantAnalysisTaskEntity taskEntity = taskEntities.get(0);
        // 发送更新消息
        AnalysisTaskUpdateMessage updateMessage = new AnalysisTaskUpdateMessage();
        updateMessage.setId(taskEntity.getId());

        if (CollectionUtils.isNotEmpty(featuredQuestionList)) {
            updateMessage.setFeaturedQuestionsGenerateStatus(MeetingAssistantConstantEnum.COMPLETED.getStatus());
            updateMessage.setFeaturedQuestions(JsonUtils.serialize(featuredQuestionList));
        } else {
            updateMessage.setFeaturedQuestionsGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
        }
        meetingAssistantAnalysisProducerService.analysisTaskUpdate(updateMessage);
    }


    @Override
    @Consumer(topic = MeetingAssistantTopic.GENERATE_SUMMARY, scale = 2)
    public void generateSummry(MeetingAssistantGenerateAnalysisContentMessage message) {
        SummaryAnalyzer summaryAnalyzer = new SummaryAnalyzer();
        String summary = summaryAnalyzer.run(message.getContent());

        // 更新状态
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(message.getDiaguesId());
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> taskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(taskEntities)) {
            throw new BusinessException("无法找到对应的会议内容分析任务");
        }
        BizMeetingAssistantAnalysisTaskEntity taskEntity = taskEntities.get(0);
        // 发送更新消息
        AnalysisTaskUpdateMessage updateMessage = new AnalysisTaskUpdateMessage();
        updateMessage.setId(taskEntity.getId());

        if (StringUtils.isNotBlank(summary)) {
            updateMessage.setMeetingSummaryGenerateStatus(MeetingAssistantConstantEnum.COMPLETED.getStatus());
            updateMessage.setMeetingSummaryContent(summary);
        } else {
            updateMessage.setMeetingSummaryGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
        }
        meetingAssistantAnalysisProducerService.analysisTaskUpdate(updateMessage);


        if (StringUtils.isBlank(taskEntity.getThemeGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getThemeGenerateStatus())) {
            MeetingAssistantGenerateAnalysisContentMessage meetingAssistantGenerateAnalysisContentMessage = new MeetingAssistantGenerateAnalysisContentMessage();
            meetingAssistantGenerateAnalysisContentMessage.setContent(summary);
            meetingAssistantGenerateAnalysisContentMessage.setDiaguesId(message.getDiaguesId());
            meetingAssistantAnalysisProducerService.generateTheme(meetingAssistantGenerateAnalysisContentMessage);
            taskEntity.setThemeGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        }
    }

    @Override
    @Consumer(topic = MeetingAssistantTopic.GENERATE_KEYWORD, scale = 2)
    public void keyWord(MeetingAssistantGenerateAnalysisContentMessage message) {
        KeyWordAnalyzer keyWordAnalyzer = new KeyWordAnalyzer();
        List<String> keyWords = keyWordAnalyzer.run(message.getContent());

        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(message.getDiaguesId());
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> taskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(taskEntities)) {
            throw new BusinessException("无法找到对应的会议内容分析任务");
        }
        BizMeetingAssistantAnalysisTaskEntity taskEntity = taskEntities.get(0);
        // 发送更新消息
        AnalysisTaskUpdateMessage updateMessage = new AnalysisTaskUpdateMessage();
        updateMessage.setId(taskEntity.getId());

        if (CollectionUtils.isNotEmpty(keyWords)) {
            // 关键词计数
            Map<String, Integer> countMap = KeyWordCounter.keywordCount(message.getContent(), keyWords);
            KeyWordCounter.cacheKeyWordCount(message.getDiaguesId(), countMap);

            updateMessage.setKeyWordGenerateStatus(MeetingAssistantConstantEnum.COMPLETED.getStatus());
            updateMessage.setKeyWordContent(JsonUtils.serialize(countMap.entrySet()));
        } else {
            updateMessage.setKeyWordGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
        }
        meetingAssistantAnalysisProducerService.analysisTaskUpdate(updateMessage);

    }

    @Override
    @Consumer(topic = MeetingAssistantTopic.GENERATE_THEME, scale = 2)
    public void generateTheme(MeetingAssistantGenerateAnalysisContentMessage message) {
        ThemeAnalyzer themeAnalyzer = new ThemeAnalyzer();
        String theme = themeAnalyzer.run(message.getContent());

        // 更新状态
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(message.getDiaguesId());
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAnalysisTaskEntity> taskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isEmpty(taskEntities)) {
            throw new BusinessException("无法找到对应的会议内容分析任务");
        }
        BizMeetingAssistantAnalysisTaskEntity taskEntity = taskEntities.get(0);
        // 发送更新消息
        AnalysisTaskUpdateMessage updateMessage = new AnalysisTaskUpdateMessage();
        updateMessage.setId(taskEntity.getId());

        if (StringUtils.isNotBlank(theme)) {
            updateMessage.setThemeGenerateStatus(MeetingAssistantConstantEnum.COMPLETED.getStatus());
            updateMessage.setThemeContent(theme);
        } else {
            updateMessage.setThemeGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
        }
        meetingAssistantAnalysisProducerService.analysisTaskUpdate(updateMessage);
    }

    /**
     * 检查是否全部已经完成
     *
     * @param taskEntity
     * @return
     */
    private boolean checkAllIsCompleted(BizMeetingAssistantAnalysisTaskEntity taskEntity) {
        // 所有皆完成
        return MeetingAssistantConstantEnum.COMPLETED.getStatus().equals(taskEntity.getFeaturedQuestionsGenerateStatus())
                && MeetingAssistantConstantEnum.COMPLETED.getStatus().equals(taskEntity.getMeetingSummaryGenerateStatus())
                && MeetingAssistantConstantEnum.COMPLETED.getStatus().equals(taskEntity.getKeyWordGenerateStatus())
                && MeetingAssistantConstantEnum.COMPLETED.getStatus().equals(taskEntity.getThemeGenerateStatus());
    }

    /**
     * 检查是否存在失败任务
     *
     * @param taskEntity
     * @return
     */
    private boolean checkExistFaild(BizMeetingAssistantAnalysisTaskEntity taskEntity) {
        return MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getFeaturedQuestionsGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getMeetingSummaryGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getKeyWordGenerateStatus())
                || MeetingAssistantConstantEnum.FAILED.getStatus().equals(taskEntity.getThemeGenerateStatus());
    }
}
