OtherBizService.java 13.1 KB
package cn.fw.dalaran.service.biz;

import cn.fw.dalaran.common.constants.DalaranConstants;
import cn.fw.dalaran.common.exception.BusinessException;
import cn.fw.dalaran.common.utils.PublicUtil;
import cn.fw.dalaran.common.utils.StringUtils;
import cn.fw.dalaran.domain.db.*;
import cn.fw.dalaran.domain.enums.FileTypeEnum;
import cn.fw.dalaran.domain.param.LiveCheckParams;
import cn.fw.dalaran.domain.vo.FileDesc;
import cn.fw.dalaran.domain.vo.LiveCheckVo;
import cn.fw.dalaran.rpc.erp.UserRoleRpcService;
import cn.fw.dalaran.rpc.erp.dto.ShopMsg;
import cn.fw.dalaran.service.data.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;

/**
 * @author wmy3969
 * @version 1.0
 * @date 2022/6/7 10:58
 * @Description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OtherBizService {
    @Value("${spring.profiles.active}")
    private String env;// 获取系统当前环境
    private final ActivityThemeService activityThemeService;
    private final LivePoolService livePoolService;
    private final LiveCheckResultService liveCheckResultService;
    private final AccountService accountService;
    private final UserRoleRpcService userRoleRpcService;
    private final TodoHistoryService todoHistoryService;
    private final ThemeFileService themeFileService;

    /**
     * 获取直播审计页面
     *
     * @param userId  当前登录用户id
     * @param themeId 主题id
     * @return 审计视图
     */
    @Transactional
    public LiveCheckVo getLiveCheck(Long userId, Long themeId) {
        LiveCheckVo vo = new LiveCheckVo();
        final List<ShopMsg> userRoleRange = userRoleRpcService.getUserRoleRange(userId, DalaranConstants.ZBSJ_ROLE_CODE);// 查询用户角色授权范围
        List<LiveCheckResult> waitCheckLives = new ArrayList<>();
        List<LiveCheckResult> list = liveCheckResultService.lambdaQuery()
                .eq(LiveCheckResult::getThemeId, themeId)
                .in(LiveCheckResult::getShopId, userRoleRange
                        .stream()
                        .map(ShopMsg::getShopId)
                        .collect(Collectors.toList())
                ).list();// 查询待办用户能审计到的直播
        if (!CollectionUtils.isEmpty(list)) {
            if (list.stream().noneMatch(item -> Objects.equals(item.getStatus(), 1)))
                waitCheckLives = list;
        } else {
            waitCheckLives = livePoolService.lambdaQuery()
                    .eq(LivePool::getValidLive, 11)
                    .eq(LivePool::getThemeId, themeId)
                    .list()
                    .stream()
                    .map(item -> {
                        final Account account = accountService.getById(item.getAccountId());
                        return LiveCheckResult.builder()
                                .themeId(themeId)
                                .userId(account.getUserId())
                                .shopId(account.getShopId())
                                .liveId(item.getId())
                                .counterfeit(-1)
                                .pay(Objects.equals(item.getValidLive(), -1) ? 1 : 0)
                                .valid(item.getValidLive() > 0 ? 1 : 0)
                                .status(-1)
                                .build();
                    })
                    .collect(Collectors.toList());
            liveCheckResultService.saveBatch(waitCheckLives);
        }
        if (!CollectionUtils.isEmpty(waitCheckLives)) {
            vo.setTheme(ActivityTheme.toVO(Objects.requireNonNull(activityThemeService.getById(themeId))));
            vo.setLiveList(PublicUtil.copyList(waitCheckLives, LiveCheckVo.liveSummary.class).stream()
                    .peek(item -> {
                        final LivePool live = livePoolService.getById(item.getLiveId());
                        item.setTitle(live.getTitle());
                        item.setPlaybackUrl(live.getPlaybackUrl());
                    })
                    .sorted(Comparator.comparing(LiveCheckVo.liveSummary::getCounterfeit))
                    .collect(Collectors.toList())
            );
        }
        return vo;
    }

    /**
     * 保存审核结果
     *
     * @param userId 用户id
     * @param param  审核结果
     * @return 操作结果
     */
    @Transactional
    public boolean saveCheckResult(Long userId, LiveCheckParams param) {
        final Integer type = param.getType();
        final Long dataId = param.getDataId();
        if (Objects.equals(type, 0)) {
            final LiveCheckResult liveCheckResult = PublicUtil.copy(param.getCheckResult(), LiveCheckResult.class);
            final Long liveCheckResultId = liveCheckResult.getId();
            if (Objects.equals(liveCheckResult.getCounterfeit(), -1))
                throw new BusinessException("请选择是否空挂");
            if (Objects.equals(liveCheckResult.getCounterfeit(), 1) &&
                    StringUtils.isEmpty(liveCheckResult.getOpinion()))
                throw new BusinessException("判断空挂必须给出审核意见");
            final List<Long> oldFileIds = Optional.ofNullable(themeFileService.lambdaQuery()
                    .eq(ThemeFile::getType, FileTypeEnum.LIVE_CHECK.getValue())
                    .eq(ThemeFile::getExtraId, liveCheckResultId)
                    .list()
            ).orElse(new ArrayList<>())
                    .stream()
                    .map(ThemeFile::getId)
                    .collect(Collectors.toList());// 获取原来的文件id
            final List<ThemeFile> liveCheckResultFiles = param.getCheckResult().getAllFileDesc().stream().map(item -> {
                final ThemeFile copy = PublicUtil.copy(item, ThemeFile.class);
                copy.setFileId(item.getFid());
                return copy;
            }).collect(Collectors.toList());
            final List<Long> newFileIds = liveCheckResultFiles.stream()
                    .map(ThemeFile::getId)
                    .collect(Collectors.toList());// 本次提交的文件id
            if (!CollectionUtils.isEmpty(oldFileIds)) {
                List<Long> retain = new ArrayList<>(oldFileIds);// 交集
                List<Long> remove = new ArrayList<>(oldFileIds);// 差集
                newFileIds.retainAll(oldFileIds);
                retain = newFileIds;
                remove.removeAll(retain);
                themeFileService.removeByIds(remove);
            }
            themeFileService.saveOrUpdateBatch(liveCheckResultFiles
                    .stream()
                    .peek(item -> {
                        item.setThemeId(dataId);
                        item.setExtraId(liveCheckResultId);
                        item.setType(FileTypeEnum.LIVE_CHECK.getValue());
                    })
                    .collect(Collectors.toList())
            );
            liveCheckResult.setStatus(type);
            liveCheckResult.setValid(Objects.equals(liveCheckResult.getCounterfeit(), 0) && Objects.equals(liveCheckResult.getPay(), 0) ? 1 : 0);
            return liveCheckResultService.updateById(liveCheckResult);
        } else if (Objects.equals(type, 1)) {// 完成待办
            final List<LiveCheckVo.liveSummary> summaries = this.getLiveCheck(userId, dataId).getLiveList();
            if (summaries.stream().anyMatch(item -> Objects.equals(item.getCounterfeit(), -1))) {
                throw new BusinessException("还有未完成审核的直播, 请完成所有直播审核后重新提交");
            } else {
                if (!todoHistoryService.lambdaUpdate()
                        .set(TodoHistory::getDone, true)
                        .eq(TodoHistory::getUserId, userId)
                        .eq(TodoHistory::getDataId, dataId)
                        .eq(TodoHistory::getTodoCode, DalaranConstants.CHECK_LIVE)
                        .update())
                    throw new BusinessException("完成待办失败");
                final List<Long> invalidLiveIds = summaries.stream()
                        .filter(item -> Objects.equals(item.getValid(), 0))
                        .map(LiveCheckVo.liveSummary::getLiveId)
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(invalidLiveIds)) {
                    ActivityTheme activityTheme = activityThemeService.getById(param.getDataId());
                    if (Objects.nonNull(activityTheme)) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        boolean flag = false;
                        int cnt = 0;
                        while (!flag && cnt < 5) {
                            if (cnt > 0)
                                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
                            flag = this.sendGetRequest("http://" + (env.contains("prd") ? "" : "test") + "gate.feewee.cn/report2/debug/extract/data/dalaran?dateType=DAILY&type=Dalaran004D&date=" +
                                    sdf.format(activityTheme.getEndTime())
                            );
                            cnt++;
                        }
                    }
                    livePoolService.lambdaUpdate()
                            .set(LivePool::getValidLive, -2)
                            .in(LivePool::getId, invalidLiveIds)
                            .update();// 将审核结果对应的不合格直播更新为空挂状态
                }
                return liveCheckResultService.lambdaUpdate()
                        .set(LiveCheckResult::getStatus, type)
                        .in(LiveCheckResult::getId, summaries
                                .stream()
                                .map(LiveCheckVo.liveSummary::getId)
                                .collect(Collectors.toList())
                        ).update();
            }
        }
        return false;
    }

    /**
     * 获取某条审计详情
     *
     * @param id
     * @return
     */
    public LiveCheckVo.liveSummary getLiveCheckDetails(Long id) {
        final LiveCheckResult checkResult = liveCheckResultService.getById(id);
        final LiveCheckVo.liveSummary liveSummary = PublicUtil.copy(checkResult, LiveCheckVo.liveSummary.class);
        final LivePool live = livePoolService.getById(checkResult.getLiveId());
        liveSummary.setTitle(live.getTitle());
        liveSummary.setPlaybackUrl(live.getPlaybackUrl());
        liveSummary.setAllFileDesc(themeFileService.lambdaQuery()
                .eq(ThemeFile::getType, FileTypeEnum.LIVE_CHECK.getValue())
                .eq(ThemeFile::getExtraId, id)
                .list()
                .stream()
                .map(item -> FileDesc.builder()
                        .id(item.getId())
                        .fid(item.getFileId())
                        .fileName(item.getFileName())
                        .fileType(item.getFileType())
                        .build())
                .collect(Collectors.toList())
        );
        return liveSummary;
    }

    /**
     * 发送GET请求
     *
     * @param url 请求地址
     * @return
     */
    @Async
    public String GET(String url) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();// 打开和URL之间的连接
            // 设置通用的请求属性
            connection.setRequestProperty("Authorization", "Basic ZGVidWc6ZndAMjAxNw==");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();// 建立实际的连接
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));// 定义 BufferedReader输入流来读取URL的响应, 防止乱码
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常!", e);
        } finally {// 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }

    private boolean sendGetRequest(String targetUrl) {
        try {
            this.GET(targetUrl);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}