package cn.com.poc.meeting.scheduler;


import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.meeting.constants.MeetingAssistantConstantEnum;
import cn.com.poc.meeting.entity.BizMeetingAssistantAnalysisTaskEntity;
import cn.com.poc.meeting.entity.BizMeetingAssistantAsrTaskEntity;
import cn.com.poc.meeting.service.BizMeetingAssistantAnalysisTaskService;
import cn.com.poc.meeting.service.BizMeetingAssistantAsrTaskService;
import cn.com.poc.message.entity.meeting.MeetingAssistantAnalysisMessage;
import cn.com.poc.message.service.MeetingAssistantAnalysisProducerService;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.AsrOfflineDetailResult;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.entity.GetDetailResult;
import cn.com.poc.thirdparty.resource.simultanous_interpretation.service.ASRService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 会议助手-定时任务
 */
@Component
public class MeetingAssistantScheduler {

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

    @Resource
    private MeetingAssistantAnalysisProducerService meetingAssistantAnalysisProducerService;

    @Resource
    private BizMeetingAssistantAsrTaskService bizMeetingAssistantAsrTaskService;

    @Resource
    private BizMeetingAssistantAnalysisTaskService bizMeetingAssistantAnalysisTaskService;

    @Resource
    private ASRService asrService;

    /**
     * 语音识别任务状态查询
     */
    @Scheduled(fixedDelay = 15000)
    public void taskStatusUpdate() {
        logger.info("------- 执行[语音识别任务状态查询]定时任务 -------");
        BizMeetingAssistantAsrTaskEntity bizMeetingAssistantAsrTaskEntity = new BizMeetingAssistantAsrTaskEntity();
        bizMeetingAssistantAsrTaskEntity.setGenerateStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        bizMeetingAssistantAsrTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMeetingAssistantAsrTaskEntity> taskEntities = bizMeetingAssistantAsrTaskService.findByExample(bizMeetingAssistantAsrTaskEntity, null);
        if (CollectionUtils.isEmpty(taskEntities)) {
            return;
        }

        for (BizMeetingAssistantAsrTaskEntity taskEntity : taskEntities) {
            String sessionId = taskEntity.getSessionId();
            GetDetailResult getDetailResult = asrService.getDetailByFullInformation(sessionId);
            if (getDetailResult == null) {
                logger.error("--------- 查询语音识别任务异常,响应结果为空,sessionId:{}---------", sessionId);
                continue;
            }
            if (0 != getDetailResult.getCode()) {
                logger.error("------ 查询语音识别任务异常,sessionId:{},code:{} ,message:{}", sessionId, getDetailResult.getCode(), getDetailResult.getMessage());
                continue;
            }
            if (null == getDetailResult.getData()) {
                logger.error("---------- 查询语音识别任务异常，data为空 -----------");
                continue;
            }
            AsrOfflineDetailResult data = getDetailResult.getData();
            if (data != null) {
                if (MeetingAssistantConstantEnum.COMPLETED.getStatus().equals(data.getGenerateStatus())) {
                    if (CollectionUtils.isEmpty(data.getTranslation())) {
                        logger.warn("-------- 语音识别任务已完成，但 Translation 内容为空 ----------");
                        taskEntity.setGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
                        taskEntity.setMessage("translation is null");
                        bizMeetingAssistantAsrTaskService.update(taskEntity);
                    } else {
                        taskEntity.setGenerateStatus(MeetingAssistantConstantEnum.COMPLETED.getStatus());
                        bizMeetingAssistantAsrTaskService.update(taskEntity);
                        //执行内容分析任务
                        MeetingAssistantAnalysisMessage meetingAssistantAnalysisMessage = new MeetingAssistantAnalysisMessage();
                        meetingAssistantAnalysisMessage.setDiaguesId(taskEntity.getDiaguesId());
                        meetingAssistantAnalysisMessage.setTranslations(data.getTranslation());
                        meetingAssistantAnalysisProducerService.analysisTask(meetingAssistantAnalysisMessage);
                    }
                } else if (MeetingAssistantConstantEnum.FAILED.getStatus().equals(data.getGenerateStatus())) {
                    taskEntity.setGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
                    bizMeetingAssistantAsrTaskService.update(taskEntity);
                    // 更新会议内容分析任务状态
                    updateAnalysisTaskToFailed(taskEntity);
                } else {
                    //判断执行时长，若超过15分钟则判断为失败.
                    Date now = new Date();
                    long diffTwoDate = DateUtils.diffTwoDate(now, taskEntity.getCreatedTime());
                    if (diffTwoDate > 15 * 60 * 1000){
                        taskEntity.setGenerateStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
                        taskEntity.setMessage("Time Out");
                        bizMeetingAssistantAsrTaskService.update(taskEntity);
                        // 更新会议内容分析任务状态
                        updateAnalysisTaskToFailed(taskEntity);
                    }
                }
            }
        }
    }

    private void updateAnalysisTaskToFailed(BizMeetingAssistantAsrTaskEntity taskEntity) {
        BizMeetingAssistantAnalysisTaskEntity bizMeetingAssistantAnalysisTaskEntity = new BizMeetingAssistantAnalysisTaskEntity();
        bizMeetingAssistantAnalysisTaskEntity.setDiaguesId(taskEntity.getDiaguesId());
        bizMeetingAssistantAnalysisTaskEntity.setMemberId(taskEntity.getMemberId());
        bizMeetingAssistantAnalysisTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        bizMeetingAssistantAnalysisTaskEntity.setAnalysisStatus(MeetingAssistantConstantEnum.GENERATE.getStatus());
        List<BizMeetingAssistantAnalysisTaskEntity> bizMeetingAssistantAnalysisTaskEntities = bizMeetingAssistantAnalysisTaskService.findByExample(bizMeetingAssistantAnalysisTaskEntity, null);
        if (CollectionUtils.isNotEmpty(bizMeetingAssistantAnalysisTaskEntities)) {
            logger.info("---------- 更新会议内容分析任务为 failed 状态, diaguesId:{}----------", taskEntity.getDiaguesId());
            BizMeetingAssistantAnalysisTaskEntity analysisTaskEntity = bizMeetingAssistantAnalysisTaskEntities.get(0);
            analysisTaskEntity.setAnalysisStatus(MeetingAssistantConstantEnum.FAILED.getStatus());
            bizMeetingAssistantAnalysisTaskService.update(analysisTaskEntity);
        } else {
            logger.warn("------------ 无法找到对应的内容分析任务数据,diaguesId:{} -----------", taskEntity.getDiaguesId());
        }
    }
}
