ReceptionService.java 14.3 KB
package com.bs.reception.service.BizService;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bs.common.core.domain.model.LoginUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.reception.entity.aliasr.AliAsrModelRes;
import com.bs.reception.entity.reception.ReceptionBizInfo;
import com.bs.reception.entity.reception.ReceptionOriginalLink;
import com.bs.reception.entity.reception.ReceptionRecording;
import com.bs.reception.manager.FileManager;
import com.bs.reception.manager.FunAsrManager;
import com.bs.reception.mapper.AliAsrModelResMapper;
import com.bs.reception.mapper.ExtractRecordMapper;
import com.bs.reception.mapper.ReceptionBizInfoMapper;
import com.bs.reception.model.reception.*;
import com.bs.reception.model.script.LabelInfo;
import com.bs.reception.model.script.LabelInfoResponse;
import com.bs.reception.model.script.LabelRequest;
import com.bs.reception.service.IReceptionBizInfoService;
import com.bs.reception.service.IReceptionOriginalLinkService;
import com.bs.reception.service.IReceptionRecordingService;
import com.bs.reception.utils.FFmpegAudioCutterUtils;
import com.bs.reception.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

import static com.bs.reception.listener.ReceptionInfoEventListener.getEndTime;

/**
 * 接待服务
 */
@Slf4j
@Service
public class ReceptionService {

    @Autowired
    private IReceptionBizInfoService receptionBizInfoService;
    @Autowired
    private IReceptionRecordingService receptionRecordingService;
    @Autowired
    private ReceptionBizInfoMapper receptionBizInfoMapper;
    @Autowired
    private IReceptionOriginalLinkService receptionOriginalLinkService;
    @Autowired
    private FileManager fileManager;
    @Autowired
    private FunAsrManager funAsrManager;
    @Autowired
    private Environment env;
    @Autowired
    private ExtractRecordMapper extractRecordMapper;
    @Autowired
    private AliAsrModelResMapper aliAsrModelResMapper;

    /**
     * 保存
     *
     * @param req
     * @return
     */
    public boolean save(ReceptionSaveRequest req) {
        ReceptionBizInfo info = new ReceptionBizInfo();
        List<ReceptionOriginalLink> links = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BeanUtils.copyProperties(req, info);
        if (loginUser != null) {
            info.setUserId(loginUser.getUserId());
            info.setUserName(loginUser.getUserName());
            info.setCreateById(loginUser.getUserId());
            info.setCreateBy(loginUser.getUserName());
            info.setCreateTime(new Date());
            info.setDelFlag(0);
            info.setStoreCode(loginUser.getStoreCode());
            info.setSpCode(loginUser.getSpCode());
        }
        req.getUrlList().forEach(url -> {
            ReceptionOriginalLink link = new ReceptionOriginalLink();
            link.setUrl(url);
            link.setMachineCode(req.getMachineCode());
            if (loginUser != null) {
                link.setCreateById(loginUser.getUserId());
                link.setCreateBy(loginUser.getUserName());
                link.setCreateTime(new Date());
                link.setDelFlag(0);
            }
            links.add(link);
        });
        return receptionBizInfoService.saveWithLinks(info, links);
    }

    /**
     * 分页查询
     *
     * @param query
     * @return
     */
    public IPage<ReceptionManagePageVO> pageManage(ReceptionManagePageQuery query) {
        if (query == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }

        int pageNum = query.getPageNum() == null || query.getPageNum() < 1 ? 1 : query.getPageNum();
        int pageSize = query.getPageSize() == null || query.getPageSize() < 1 ? 10 : query.getPageSize();
        query.setPageNum(pageNum);
        query.setPageSize(pageSize);
        if (SecurityUtils.getLoginUser() != null && SecurityUtils.getLoginUser().getSpCode() != null) {
            // 获取当前登录用户的spCode和storeCode
            query.setSpCode(SecurityUtils.getLoginUser().getSpCode());
            query.setStoreCode(SecurityUtils.getLoginUser().getStoreCode());
        }
        IPage<ReceptionManagePageVO> entityPage = receptionBizInfoService.receptionManagePage(query);
        if (entityPage.getRecords() != null && !entityPage.getRecords().isEmpty()) {
            entityPage.getRecords().forEach(e -> {
                if (e.getDuration() != null) {
                    e.setDurationStr(ReceptionManagePageVO.formatMinutesSeconds(e.getDuration()));
                }
            });
        }
        return entityPage;
    }

    /**
     * 接待数据统计
     *
     * @param query
     * @return
     */
    public ReceptionStatisticsVO getReceptionStatistics(ReceptionStatisticsQuery query) {
        if (query == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }
        return receptionBizInfoService.getReceptionStatistics(query);
    }


    private static ReceptionManagePageVO toManagePageVO(ReceptionBizInfo entity) {
        ReceptionManagePageVO vo = new ReceptionManagePageVO();
        vo.setId(entity.getId());
        vo.setTypeCode(entity.getTypeCode());
        vo.setStoreCode(entity.getStoreCode());
        vo.setSpCode(entity.getSpCode());
        vo.setCarType(entity.getCarType());
        vo.setCustomerType(entity.getCustomerType());
        vo.setCustomerName(entity.getCustomerName());
        vo.setCustomerPhone(entity.getCustomerPhone());
        vo.setUserId(entity.getUserId());
        vo.setUserName(entity.getUserName());
        vo.setStartTime(entity.getStartTime());
        vo.setEndTime(entity.getEndTime());
        vo.setMaterialId(entity.getMaterialId());
        vo.setCreateBy(entity.getCreateBy());
        vo.setCreateById(entity.getCreateById());
        vo.setCreateTime(entity.getCreateTime());
        vo.setUpdateBy(entity.getUpdateBy());
        vo.setUpdateById(entity.getUpdateById());
        vo.setUpdateTime(entity.getUpdateTime());
        vo.setRemark(entity.getRemark());
        return vo;
    }

    /**
     * 补偿录音文件合并失败和创建语音转文本任务失败的
     */
    public void fileMergeOrFunAsrTaskCreate() {
        //查询ReceptionRecording中url为空或者tfTaskId为空的,且创建时间距离当前时间上一小时内的记录
        long st = 2L * 24 * 60 * 60 * 1000;
        long et = 60 * 60 * 1000;
        String startTime = env.getProperty("reception.filemerge.funasrtask.compensation.start", st + "");
        String endTime = env.getProperty("reception.filemerge.funasrtask.compensation.end", et + "");
        List<ReceptionRecording> recordings = receptionRecordingService.lambdaQuery()
                .and(wrapper -> wrapper.isNull(ReceptionRecording::getTfTaskId)
                        .or()
                        .isNull(ReceptionRecording::getUrl))
                .eq(ReceptionRecording::getDelFlag, 0)
                .ge(ReceptionRecording::getCreateTime, new Date(System.currentTimeMillis() - Long.parseLong(startTime)))
                .le(ReceptionRecording::getCreateTime, new Date(System.currentTimeMillis() - Long.parseLong(endTime)))
                .last("LIMIT 10")
                .list();


        // 如果存在,遍历,重新发起语音转文本任务
        if (recordings != null && !recordings.isEmpty()) {
            recordings.forEach(recording -> {
                try {
                    if (recording.getUrl() == null) {
                        //获取文件上传+语音转文本
                        List<ReceptionOriginalLink> links = receptionOriginalLinkService.lambdaQuery()
                                .eq(ReceptionOriginalLink::getBizInfoId, recording.getBizInfoId())
                                .eq(ReceptionOriginalLink::getDelFlag, 0)
                                .list();
                        long duration = 0;
                        if (links != null && !links.isEmpty()) {
                            String mergeFile = fileManager.mergeFile(links.stream().map(ReceptionOriginalLink::getUrl).toList());
                            if (mergeFile != null) {
                                log.info("合并后的文件mergeFile:{}", mergeFile);
                                log.info("mergeFile: {}", mergeFile);
                                Long fileSize = FileUtils.fileSize(mergeFile);
                                log.info("文件大小:{}", fileSize);
                                recording.setFilesize(fileSize);
                                duration = FFmpegAudioCutterUtils.duation(mergeFile);
                                log.info("时长:{}", duration);
                                recording.setDuration(duration);
                                recording.setEndTime(getEndTime(recording.getStartTime(), duration));
                                // 更细接待主表接待结束时间
                                updateReceptionBizInfo(recording.getBizInfoId(), recording.getStartTime(), duration);
                                //上传文件
                                String uploadFile = fileManager.uploadFile(mergeFile);
                                log.info("上传后的文件uploadFile:{}", uploadFile);
                                if (uploadFile != null) {
                                    recording.setUrl(uploadFile);
                                    //创建语音转文本任务
                                    String asrTaskId = funAsrManager.createAsrTask(uploadFile);
                                    log.info("创建语音转文本任务asrTaskId:{}", asrTaskId);
                                    if (asrTaskId != null) {
                                        recording.setTfTaskId(asrTaskId);
                                    } else {
                                        log.error("创建语音转文本任务失败");
                                        // 二次处理还是为空,则设置为空字符串
                                        recording.setTfTaskId("");
                                    }
                                }
                                boolean removed = FileUtils.removeLocalFile(mergeFile);
                                if (!removed) {
                                    log.error("删除本地临时文件失败 filePath:{}", mergeFile);
                                }
                            } else {
                                log.error("合并文件失败");
                                // 二次处理还是为空,则设置为空字符串
                                recording.setUrl("");
                            }
                        }
                    } else if (recording.getTfTaskId() == null) {
                        // 重新发起语音转文本任务
                        String asrTaskId = funAsrManager.createAsrTask(recording.getUrl());
                        log.info("创建语音转文本任务asrTaskId:{}", asrTaskId);
                        if (asrTaskId == null) {
                            log.error("http调用funAsr创建语音转文本任务失败,改为直接写表形式");
                            asrTaskId = insertAliAsrModelRes(recording.getUrl(),recording.getCreateBy());
                        }
                        recording.setTfTaskId(asrTaskId);
                    }
                    recording.setUpdateBy("job");
                    recording.setUpdateTime(new Date());
                    receptionRecordingService.updateById(recording);
                } catch (Exception e) {
                    log.error("补偿文件合并或语音转文本任务创建失败:{}", e.getMessage(), e);
                }
            });
        }
    }

    /**
     * 插入阿里云asr任务
     * @param uploadFile
     * @param createBy
     * @return
     */
    private String insertAliAsrModelRes(String uploadFile, String createBy) {
        try {
            AliAsrModelRes aliAsrModelRes = new AliAsrModelRes();
            String taskId = UUID.randomUUID().toString();
            aliAsrModelRes.setTaskId(taskId);
            aliAsrModelRes.setFileUrl(uploadFile);
            aliAsrModelRes.setTaskStatus(0);
            aliAsrModelRes.setCreatedTime(new Date());
            aliAsrModelRes.setCreatedBy(createBy);
            aliAsrModelRes.setDelFlag(0);
            aliAsrModelResMapper.insert(aliAsrModelRes);
            return taskId;
        } catch (Exception e) {
            log.error("插入阿里云asr任务失败:{}", e);
            return null;
        }
    }

    private void updateReceptionBizInfo(Long id, Date startTime, long duration) {
        Date endTime = getEndTime(startTime, duration);
        ReceptionBizInfo receptionBizInfo = new ReceptionBizInfo();
        receptionBizInfo.setEndTime(endTime);
        receptionBizInfo.setUpdateTime(new Date());
        UpdateWrapper<ReceptionBizInfo> updateWrapper = new UpdateWrapper<ReceptionBizInfo>();
        updateWrapper.eq("id", id);
        receptionBizInfoMapper.update(receptionBizInfo, updateWrapper);
    }

    public List<LabelInfo> getSuggestionLabelWithBurialPoint(LabelRequest param) {
        Assert.isTrue(CollectionUtils.isNotEmpty(param.getTagList()), "labels不能为空");
        Assert.isTrue(param.getTagResponseCount()!=null, "count不能为空");
        List<LabelInfoResponse> suggestionLabel = extractRecordMapper.getSuggestionLabel(param);
        List<LabelInfo> labelResponse = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(suggestionLabel)) {
            Map<String, List<String>> collect = suggestionLabel.stream()
                    .collect(Collectors.groupingBy(LabelInfoResponse::getLabelName, Collectors.mapping(LabelInfoResponse::getSuggestion, Collectors.toList())));
            for (String labelName : collect.keySet()) {
                List<String> suggestionList = collect.get(labelName);
                labelResponse.add(new LabelInfo(labelName, suggestionList));
            }
        }
        return labelResponse;
    }
}