package com.tzld.piaoquan.api.job.contentplatform;

import com.aliyun.odps.data.Record;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.google.common.collect.Lists;
import com.tzld.piaoquan.api.common.enums.contentplatform.UploadVideoAuditStatusEnum;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.*;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ext.ContentPlatformPlanMapperExt;
import com.tzld.piaoquan.api.model.po.contentplatform.*;
import com.tzld.piaoquan.api.util.CdnUtil;
import com.tzld.piaoquan.growth.common.model.bo.VideoDetail;
import com.tzld.piaoquan.growth.common.service.MessageAttachmentService;
import com.tzld.piaoquan.growth.common.utils.DateUtil;
import com.tzld.piaoquan.growth.common.utils.OdpsUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ContentPlatformVideoJob {

    @Autowired
    private ContentPlatformPlanMapperExt planMapperExt;
    @Autowired
    private ContentPlatformVideoMapper videoMapper;
    @Autowired
    private ContentPlatformVideoAggMapper videoAggMapper;
    @Autowired
    private ContentPlatformVideoDataStatMapper videoDataStatMapper;
    @Autowired
    private ContentPlatformVideoDataStatAggMapper videoDataStatAggMapper;
    @Autowired
    private ContentPlatformIllegalVideoMapper illegalVideoMapper;
    @Autowired
    private MessageAttachmentService messageAttachmentService;
    @Autowired
    private ContentPlatformUploadVideoMapper uploadVideoMapper;
    @Autowired
    private ContentPlatformAccountMapper accountMapper;

    @Value("${video.agg.days:30}")
    private Integer videoAggDays;

    @ApolloJsonValue("${video.recommend.score.config:{}}")
    private Map<String, Double> recommendScoreConfig;

    @XxlJob("syncContentPlatformVideoJob")
    public ReturnT<String> syncContentPlatformVideoJob(String param) {
        String aggDt = DateUtil.getBeforeDayDateString("yyyyMMdd");
        if (StringUtils.hasText(param)) {
            aggDt = param;
        }
        List<String> dtList = DateUtil.getBeforeDays(aggDt, aggDt, videoAggDays - 1);
        // 轮询查询大数据获取最近 videoAggDays 天视频
        for (String dt : dtList) {
            String sql = String.format("SELECT * FROM loghubods.wecom_cooperation_video_candidate_pool WHERE dt=%s;", dt);
            List<Record> dataList = OdpsUtil.getOdpsData(sql);
            Long now = System.currentTimeMillis();
            if (CollectionUtils.isNotEmpty(dataList)) {
                List<ContentPlatformVideo> saveList = new ArrayList<>();
                List<Long> existVideoIds = new ArrayList<>();
                for (Record record : dataList) {
                    ContentPlatformVideo item = new ContentPlatformVideo();
                    Long videoId = Long.parseLong((String) record.get(0));
                    if (existVideoIds.contains(videoId)) {
                        continue;
                    }
                    existVideoIds.add(videoId);
                    String category = (String) record.get(1);
                    String title = (String) record.get(2);
                    String videoUrl = (String) record.get(3);
                    Double score = Double.parseDouble((String) record.get(4));
                    Long exposure = parseLongSafe(record.get(5));
                    Double rovn = parseDoubleSafe(record.get(6));
                    if (exposure < 5000) {
                        continue;
                    }
                    item.setDt(dt);
                    item.setVideoId(videoId);
                    item.setCategory(category);
                    item.setTitle(title);
                    item.setVideo(videoUrl);
                    item.setScore(score);
                    item.setExposure(exposure);
                    item.setRovn(rovn);
                    item.setCreateTimestamp(now);
                    saveList.add(item);
                }
                // 获取视频封面
                for (List<ContentPlatformVideo> partition : Lists.partition(saveList, 20)) {
                    List<Long> videoIds = partition.stream().map(ContentPlatformVideo::getVideoId).distinct().collect(Collectors.toList());
                    Map<Long, VideoDetail> coverMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
                    for (ContentPlatformVideo item : partition) {
                        VideoDetail detail = coverMap.get(item.getVideoId());
                        if (Objects.nonNull(detail)) {
                            String cover = detail.getCover().substring(0, detail.getCover().indexOf("/watermark"));
                            item.setCover(cover);
                            if (detail.getAuditStatus() != 5) {
                                item.setStatus(0);
                            }
                        }
                    }
                }
                // save
                if (CollectionUtils.isNotEmpty(saveList)) {
                    List<ContentPlatformVideo> videoList = getVideoList(dt);
                    List<ContentPlatformIllegalVideo> illegalVideoList = getAllIllegalVideoList();
                    List<Long> illegalVideoIds = illegalVideoList.stream().map(ContentPlatformIllegalVideo::getVideoId).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(illegalVideoIds)) {
                        saveList = saveList.stream().filter(item -> !illegalVideoIds.contains(item.getVideoId())).collect(Collectors.toList());
                    }
                    if (CollectionUtils.isNotEmpty(videoList)) {
                        List<Long> tempExistVideoIds = videoList.stream().map(ContentPlatformVideo::getVideoId).collect(Collectors.toList());
                        List<Long> videoIdList = saveList.stream().map(ContentPlatformVideo::getVideoId).collect(Collectors.toList());
                        planMapperExt.updateOtherVideoStatus(dt, videoIdList, now);
                        saveList = saveList.stream().filter(item -> !tempExistVideoIds.contains(item.getVideoId())).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(saveList)) {
                            planMapperExt.batchInsertContentPlatformVideo(saveList);
                        }
                    } else {
                        planMapperExt.batchInsertContentPlatformVideo(saveList);
                    }
                }
            }
        }
        // 更新封面
        List<ContentPlatformVideo> nullCoverVideoList = getVideoNullCover();
        if (CollectionUtils.isNotEmpty(nullCoverVideoList)) {
            for (List<ContentPlatformVideo> partition : Lists.partition(nullCoverVideoList, 20)) {
                List<Long> videoIds = partition.stream().map(ContentPlatformVideo::getVideoId).distinct().collect(Collectors.toList());
                Map<Long, VideoDetail> coverMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
                for (ContentPlatformVideo item : partition) {
                    VideoDetail detail = coverMap.get(item.getVideoId());
                    if (Objects.isNull(detail)) {
                        continue;
                    }
                    String cover = detail.getCover().substring(0, detail.getCover().indexOf("/watermark"));
                    if (!cover.startsWith(CdnUtil.VIDEO_CDN_URL_HOST)
                            && StringUtils.hasText(detail.getVideoCoverSnapshotPath())
                            && detail.getVideoCoverSnapshotPath().startsWith(CdnUtil.VIDEO_CDN_URL_HOST)) {
                        cover = detail.getVideoCoverSnapshotPath() + cover.substring(cover.indexOf("?"));
                    }
                    item.setCover(cover);
                    if (detail.getAuditStatus() != 5) {
                        item.setStatus(0);
                    }
                    videoMapper.updateByPrimaryKeySelective(item);
                }
            }
        }
        long videoAggCount = getVideoAggCount(aggDt);
        if (videoAggCount > 0) {
            planMapperExt.deleteContentPlatformVideoAgg(aggDt);
        }
        // 聚合最近14天视频
        List<ContentPlatformVideoAgg> saveAggList = planMapperExt.getVideoAggList(aggDt, dtList);
        if (CollectionUtils.isNotEmpty(saveAggList)) {
            Long now = System.currentTimeMillis();
            for (ContentPlatformVideoAgg item : saveAggList) {
                item.setDt(aggDt);
                item.setCreateTimestamp(now);
            }
            planMapperExt.batchInsertContentPlatformVideoAgg(saveAggList);
        }
        return ReturnT.SUCCESS;
    }

    private List<ContentPlatformIllegalVideo> getAllIllegalVideoList() {
        ContentPlatformIllegalVideoExample example = new ContentPlatformIllegalVideoExample();
        return illegalVideoMapper.selectByExample(example);
    }

    private List<ContentPlatformVideo> getVideoNullCover() {
        ContentPlatformVideoExample example = new ContentPlatformVideoExample();
        example.createCriteria().andCoverIsNull();
        return videoMapper.selectByExample(example);
    }

    private List<ContentPlatformVideo> getVideoList(String dt) {
        ContentPlatformVideoExample example = new ContentPlatformVideoExample();
        example.createCriteria().andDtEqualTo(dt);
        return videoMapper.selectByExample(example);
    }

    private long getVideoAggCount(String dt) {
        ContentPlatformVideoAggExample example = new ContentPlatformVideoAggExample();
        example.createCriteria().andDtEqualTo(dt);
        return videoAggMapper.countByExample(example);
    }

    @XxlJob("checkContentPlatformVideoStatusJob")
    public ReturnT<String> checkContentPlatformVideoStatusJob(String param) {
        String dt = planMapperExt.getVideoMaxDt();
        if (StringUtils.hasText(param)) {
            dt = param;
        }
        List<ContentPlatformVideoAgg> videoList = getVideoListByDt(dt);
        Long now = System.currentTimeMillis();
        for (List<ContentPlatformVideoAgg> partition : Lists.partition(videoList, 20)) {
            List<Long> videoIds = partition.stream().map(ContentPlatformVideoAgg::getVideoId).collect(Collectors.toList());
            Map<Long, VideoDetail> videoDetailMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
            for (ContentPlatformVideoAgg video : partition) {
                VideoDetail videoDetail = videoDetailMap.get(video.getVideoId());
                if (videoDetail == null
                        || videoDetail.getAuditStatus() != 5) {
                    updateVideoStatusWithOldStatus(video.getVideoId(), 0, 1, now);
                } else if (videoDetail.getRecommendStatus() == -6 && video.getStatus() == 0) {
                    updateVideoStatusWithOldStatus(video.getVideoId(), 1, 0, now);
                }
            }
        }
        // 检查视频是否违规
        List<ContentPlatformIllegalVideo> illegalVideoList = getAllIllegalVideoList();
        List<Long> illegalVideoIds = illegalVideoList.stream().map(ContentPlatformIllegalVideo::getVideoId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(illegalVideoIds)) {
            for (Long illegalVideoId : illegalVideoIds) {
                updateVideoStatusWithOldStatus(illegalVideoId, 0, 1, now);
            }
        }
        return ReturnT.SUCCESS;
    }

    private void updateVideoStatusWithOldStatus(Long videoId, Integer status, Integer oldStatus, Long now) {
        planMapperExt.updateVideoStatusWithOldStatus(videoId, status, oldStatus, now);
        planMapperExt.updateVideoAggStatusWithOldStatus(videoId, status, oldStatus, now);
    }

    private List<ContentPlatformVideoAgg> getVideoListByDt(String dt) {
        ContentPlatformVideoAggExample example = new ContentPlatformVideoAggExample();
        example.createCriteria().andDtEqualTo(dt);
        return videoAggMapper.selectByExample(example);
    }

    private List<ContentPlatformVideoDataStatAgg> getVideoDatastatAggList(String dt, String strategy) {
        ContentPlatformVideoDataStatAggExample example = new ContentPlatformVideoDataStatAggExample();
        example.createCriteria().andDtEqualTo(dt).andStrategyEqualTo(strategy);
        return videoDataStatAggMapper.selectByExample(example);
    }

    @XxlJob("syncContentPlatformVideoDatastatJob")
    public ReturnT<String> syncContentPlatformVideoDatastatJob(String param) {
        String aggDt = DateUtil.getBeforeDayDateString("yyyyMMdd");
        if (StringUtils.hasText(param)) {
            aggDt = param;
        }
        List<String> dtList = DateUtil.getBeforeDays(aggDt, aggDt, 6);
        // 轮询查询大数据获取最近14天视频
        for (String dt : dtList) {
            String sql = String.format("SELECT 行业, 渠道, vid, 首层访问人数, t0裂变人数, t0裂变率 " +
                    "FROM loghubods.wecom_cooperation_video_candidate_pool_hy_qd WHERE dt=%s;", dt);
            List<Record> dataList = OdpsUtil.getOdpsData(sql);
            Long now = System.currentTimeMillis();
            if (CollectionUtils.isNotEmpty(dataList)) {
                List<ContentPlatformVideoDataStat> saveList = new ArrayList<>();
                for (Record record : dataList) {
                    ContentPlatformVideoDataStat item = new ContentPlatformVideoDataStat();
                    String type = (String) record.get(0);
                    String channel = (String) record.get(1);
                    Long videoId = Long.parseLong((String) record.get(2));
                    Long firstLevel = Long.parseLong((String) record.get(3));
                    Long fission0 = Long.parseLong((String) record.get(4));
                    Double fissionRate = Double.parseDouble((String) record.get(5));
                    item.setDt(dt);
                    item.setVideoId(videoId);
                    item.setType(type);
                    item.setChannel(channel);
                    item.setFirstLevel(firstLevel);
                    item.setFission0(fission0);
                    item.setFissionRate(fissionRate);
                    item.setCreateTimestamp(now);
                    saveList.add(item);
                }
                // save
                if (CollectionUtils.isNotEmpty(saveList)) {
                    planMapperExt.deleteContentPlatformVideoDatastat(dt);
                    planMapperExt.batchInsertContentPlatformVideoDatastat(saveList);
                }
            }
        }
        // 聚合最近14天视频
        List<ContentPlatformVideoDataStatAgg> saveAggList = buildVideoDataStatAggList(aggDt, dtList);
        if (CollectionUtils.isNotEmpty(saveAggList)) {
            planMapperExt.deleteContentPlatformVideoDatastatAgg(aggDt, null);
            String delDt = DateUtil.getBeforeDayDateString(15, "yyyyMMdd");
            planMapperExt.deleteContentPlatformVideoDatastatAgg(delDt, null);
            planMapperExt.batchInsertContentPlatformVideoDatastatAgg(saveAggList);
        }
        calContentPlatformVideoDatastatAggRecommendRateJob(param);
        return ReturnT.SUCCESS;
    }

    private List<ContentPlatformVideoDataStatAgg> buildVideoDataStatAggList(String aggDt, List<String> dtList) {
        Long now = System.currentTimeMillis();
        List<ContentPlatformVideoDataStat> dataStatList = getVideoDatastatList(dtList);
        Map<Long, Map<String, Map<String, List<ContentPlatformVideoDataStat>>>> videoIdMap = dataStatList.stream()
                .filter(o -> {
                    if ("sum".equals(o.getChannel())) {
                        return o.getFirstLevel() > 300;
                    } else {
                        return o.getFirstLevel() > 100;
                    }
                })
                .collect(Collectors.groupingBy(ContentPlatformVideoDataStat::getVideoId,
                        Collectors.groupingBy(ContentPlatformVideoDataStat::getType,
                                Collectors.groupingBy(ContentPlatformVideoDataStat::getChannel))));
        List<ContentPlatformVideoDataStatAgg> result = new ArrayList<>();
        for (Map.Entry<Long, Map<String, Map<String, List<ContentPlatformVideoDataStat>>>> entry : videoIdMap.entrySet()) {
            Long videoId = entry.getKey();
            Map<String, Map<String, List<ContentPlatformVideoDataStat>>> typeMap = entry.getValue();
            for (Map.Entry<String, Map<String, List<ContentPlatformVideoDataStat>>> typeEntry : typeMap.entrySet()) {
                String type = typeEntry.getKey();
                Map<String, List<ContentPlatformVideoDataStat>> channelMap = typeEntry.getValue();
                for (Map.Entry<String, List<ContentPlatformVideoDataStat>> channelEntry : channelMap.entrySet()) {
                    String channel = channelEntry.getKey();
                    List<ContentPlatformVideoDataStat> statList = channelEntry.getValue();
                    Long sumFirstLevel = statList.stream().map(ContentPlatformVideoDataStat::getFirstLevel).reduce(0L, Long::sum);
                    Long sumFission0 = statList.stream().map(ContentPlatformVideoDataStat::getFission0).reduce(0L, Long::sum);
                    sumFission0 = sumFission0 * 10;
                    ContentPlatformVideoDataStatAgg item = new ContentPlatformVideoDataStatAgg();
                    item.setDt(aggDt);
                    item.setVideoId(videoId);
                    item.setType(type);
                    item.setChannel(channel);
                    item.setStrategy("normal");
                    item.setFirstLevel(sumFirstLevel);
                    item.setFission0(sumFission0);
                    if (sumFirstLevel > 0) {
                        BigDecimal fissionRate = new BigDecimal(sumFission0).divide(new BigDecimal(sumFirstLevel), 4, RoundingMode.HALF_UP);
                        item.setFissionRate(fissionRate.doubleValue());
                    }
                    item.setCreateTimestamp(now);
                    result.add(item);
                }
            }
        }
        return result;
    }

    private List<ContentPlatformVideoDataStat> getVideoDatastatList(List<String> dtList) {
        ContentPlatformVideoDataStatExample example = new ContentPlatformVideoDataStatExample();
        example.createCriteria().andDtIn(dtList);
        return videoDataStatMapper.selectByExample(example);
    }

    @XxlJob("calContentPlatformVideoDatastatAggRecommendRateJob")
    public ReturnT<String> calContentPlatformVideoDatastatAggRecommendRateJob(String param) {
        String dt = planMapperExt.getVideoMaxDt();
        String datastatDt = planMapperExt.getVideoDatastatMaxDt();
        if (StringUtils.hasText(param)) {
            dt = param;
            datastatDt = param;
        }
        List<ContentPlatformVideoAgg> videoList = getVideoListByDt(dt);
        List<ContentPlatformVideoDataStatAgg> aggList = getVideoDatastatAggList(datastatDt, "normal");
        Map<String, Map<String, Map<Long, Double>>> videoIdTypeChannelScoreMap = aggList.stream()
                .filter(o -> "normal".equals(o.getStrategy()))
                .collect(Collectors.groupingBy(
                        ContentPlatformVideoDataStatAgg::getType,
                        Collectors.groupingBy(ContentPlatformVideoDataStatAgg::getChannel,
                                Collectors.toMap(ContentPlatformVideoDataStatAgg::getVideoId, ContentPlatformVideoDataStatAgg::getFissionRate))));
        List<String> typeList = Arrays.asList("自动回复", "服务号推送", "公众号推送", "企微-社群", "企微-自动回复");
        List<ContentPlatformAccount> accountList = getAllContentPlatformAccount();
        List<String> channelList = accountList.stream().map(ContentPlatformAccount::getChannel).collect(Collectors.toList());
        channelList.add("sum");
        List<ContentPlatformVideoDataStatAgg> saveList = new ArrayList<>();
        Long now = System.currentTimeMillis();
        String strategy = "recommend";
        for (String type : typeList) {
            for (String channel : channelList) {
                for (ContentPlatformVideoAgg video : videoList) {
                    if (!videoIdTypeChannelScoreMap.containsKey(type)) {
                        continue;
                    }
                    Map<Long, Double> typeVideoScoreMap = videoIdTypeChannelScoreMap.getOrDefault(type, new HashMap<>())
                            .getOrDefault("sum", new HashMap<>());
                    Map<Long, Double> channelVideoScoreMap = videoIdTypeChannelScoreMap.getOrDefault(type, new HashMap<>())
                            .getOrDefault(channel, new HashMap<>());
                    Double platformScore = video.getScore();

                    Double channelRate = 0.0;
                    if (!"sum".equals(channel) && Objects.nonNull(channelVideoScoreMap) && channelVideoScoreMap.containsKey(video.getVideoId())) {
                        channelRate = channelVideoScoreMap.get(video.getVideoId());
                    }
                    Double typeRate = 0.0;
                    if (Objects.nonNull(typeVideoScoreMap) && typeVideoScoreMap.containsKey(video.getVideoId())) {
                        typeRate = typeVideoScoreMap.get(video.getVideoId());
                    }
                    Double recommendScore = calRecommendScore(platformScore, channelRate, typeRate);
                    ContentPlatformVideoDataStatAgg agg = new ContentPlatformVideoDataStatAgg();
                    agg.setDt(datastatDt);
                    agg.setVideoId(video.getVideoId());
                    agg.setType(type);
                    agg.setChannel(channel);
                    agg.setStrategy(strategy);
                    agg.setFissionRate(recommendScore);
                    agg.setCreateTimestamp(now);
                    saveList.add(agg);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(saveList)) {
            planMapperExt.deleteContentPlatformVideoDatastatAgg(datastatDt, strategy);
            for (List<ContentPlatformVideoDataStatAgg> partition : Lists.partition(saveList, 1000)) {
                planMapperExt.batchInsertContentPlatformVideoDatastatAgg(partition);
            }
        }

        return ReturnT.SUCCESS;
    }

    private Double calRecommendScore(Double platformScore, Double channelRate, Double typeRate) {
        // channelRate 本渠道传播率，不存在的为0
        if (Objects.isNull(channelRate)) {
            channelRate = 0.0;
        }
        // typeRate 行业裂变率, 不存在的为0
        if (Objects.isNull(typeRate)) {
            typeRate = 0.0;
        }
        Double platformWeight = recommendScoreConfig.getOrDefault("platformWeight", 0.5);
        Double channelWeight = recommendScoreConfig.getOrDefault("channelWeight", 0.5);
        Double typeWeight = recommendScoreConfig.getOrDefault("typeWeight", 0.1);
        Double scalingWeight = recommendScoreConfig.getOrDefault("scalingWeight", 1.5);
        Double maxScore = recommendScoreConfig.getOrDefault("maxScore", 10.0);

        Double score = platformWeight * platformScore + channelWeight * channelRate;
        score += typeWeight * (10 - Math.min(10, typeRate));
        score *= scalingWeight;

        if (score > maxScore) {
            score = maxScore + (score - maxScore) / 10;
        }
        BigDecimal bdScore = new BigDecimal(score);
        return bdScore.setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    private Long parseLongSafe(Object v) {
        if (v == null) {
            return 0L;
        }
        try {
            String s = v.toString().trim();
            if (s.isEmpty() || "null".equalsIgnoreCase(s) || "NaN".equalsIgnoreCase(s)) {
                return 0L;
            }
            return (long) Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    private Double parseDoubleSafe(Object v) {
        if (v == null) {
            return 0.0;
        }
        try {
            String s = v.toString().trim();
            if (s.isEmpty() || "null".equalsIgnoreCase(s) || "NaN".equalsIgnoreCase(s)) {
                return 0.0;
            }
            double d = Double.parseDouble(s);
            return Double.isNaN(d) ? 0.0 : d;
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    private List<ContentPlatformAccount> getAllContentPlatformAccount() {
        ContentPlatformAccountExample example = new ContentPlatformAccountExample();
        example.createCriteria().andStatusEqualTo(1);
        return accountMapper.selectByExample(example);
    }

    @XxlJob("syncContentPlatformUploadVideoScoreJob")
    public ReturnT<String> syncContentPlatformUploadVideoScoreJob(String param) {
        String aggDt = DateUtil.getBeforeDayDateString("yyyyMMdd");
        List<ContentPlatformVideoAgg> saveAggList = getVideoListByDt(aggDt);
        Map<Long, ContentPlatformVideoAgg> videoIdMap = saveAggList.stream().collect(Collectors.toMap(ContentPlatformVideoAgg::getVideoId, o -> o));
        List<ContentPlatformUploadVideo> uploadVideoList = getAllUploadVideo();
        if (CollectionUtils.isNotEmpty(uploadVideoList)) {
            for (ContentPlatformUploadVideo uploadVideo : uploadVideoList) {
                ContentPlatformVideoAgg agg = videoIdMap.get(uploadVideo.getVideoId());
                if (Objects.nonNull(agg)) {
                    uploadVideo.setScore(agg.getScore());
                    uploadVideoMapper.updateByPrimaryKeySelective(uploadVideo);
                }
            }
        }
        return ReturnT.SUCCESS;
    }

    private List<ContentPlatformUploadVideo> getAllUploadVideo() {
        ContentPlatformUploadVideoExample example = new ContentPlatformUploadVideoExample();
        example.createCriteria().andIsDeleteEqualTo(0);
        return uploadVideoMapper.selectByExample(example);
    }

    @XxlJob("checkContentPlatformUploadVideoStatusJob")
    public ReturnT<String> checkContentPlatformUploadVideoStatusJob(String param) {
        List<ContentPlatformUploadVideo> uploadVideoList = getAllUploadVideo();
        Long now = System.currentTimeMillis();
        for (List<ContentPlatformUploadVideo> partition : Lists.partition(uploadVideoList, 20)) {
            List<Long> videoIds = partition.stream().map(ContentPlatformUploadVideo::getVideoId).collect(Collectors.toList());
            Map<Long, VideoDetail> videoDetailMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
            for (ContentPlatformUploadVideo video : partition) {
                VideoDetail videoDetail = videoDetailMap.get(video.getVideoId());
                if (videoDetail == null || videoDetail.getAuditStatus() != 5) {
                    updateUploadVideoStatusWithOldStatus(video.getVideoId(), UploadVideoAuditStatusEnum.AUDIT_REJECT.getVal(), now);
                }
            }
        }
        // 检查视频是否违规
        List<ContentPlatformIllegalVideo> illegalVideoList = getAllIllegalVideoList();
        List<Long> illegalVideoIds = illegalVideoList.stream().map(ContentPlatformIllegalVideo::getVideoId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(illegalVideoIds)) {
            for (Long illegalVideoId : illegalVideoIds) {
                updateUploadVideoStatusWithOldStatus(illegalVideoId, UploadVideoAuditStatusEnum.AUDIT_REJECT.getVal(), now);
            }
        }
        return ReturnT.SUCCESS;
    }

    private void updateUploadVideoStatusWithOldStatus(Long videoId, Integer status, Long now) {
        planMapperExt.updateUploadVideoStatusWithOldStatus(videoId, status, now);
    }

}



