package com.tzld.piaoquan.api.job.wecom.thirdpart;

import com.aliyun.odps.data.Record;
import com.google.common.collect.Lists;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformIllegalVideoMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComVideoMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ext.ThirdPartWeComVideoMapperExt;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformIllegalVideo;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformIllegalVideoExample;
import com.tzld.piaoquan.api.model.po.wecom.thirdpart.ThirdPartWeComVideo;
import com.tzld.piaoquan.api.model.po.wecom.thirdpart.ThirdPartWeComVideoExample;
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.stereotype.Component;
import org.springframework.util.StringUtils;

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

@Slf4j
@Component
public class WeComVideoJob {

    @Autowired
    private ThirdPartWeComVideoMapperExt videoMapperExt;
    @Autowired
    private ThirdPartWeComVideoMapper videoMapper;
    @Autowired
    private ContentPlatformIllegalVideoMapper illegalVideoMapper;
    @Autowired
    private MessageAttachmentService messageAttachmentService;


    @XxlJob("syncThirdPartWeComVideoJob")
    public ReturnT<String> syncThirdPartWeComVideoJob(String param) {
        String dt = DateUtil.getBeforeDayDateString("yyyyMMdd");
        if (StringUtils.hasText(param)) {
            dt = param;
        }

        String maxDt = videoMapperExt.getVideoMaxDt();
        if (StringUtils.hasText(maxDt) && maxDt.equals(dt)) {
            return ReturnT.SUCCESS;
        }
        String sql = String.format("SELECT 视频id, 视频品类, 视频标题, 视频播放地址, 分数 " +
                "FROM loghubods.wecom_cooperation_video_candidate_pool_20251125 WHERE dt=%s;", dt);
        List<Record> dataList = OdpsUtil.getOdpsData(sql);
        Long now = System.currentTimeMillis();
        if (CollectionUtils.isNotEmpty(dataList)) {
            List<ThirdPartWeComVideo> saveList = new ArrayList<>();
            List<Long> existVideoIds = new ArrayList<>();
            for (Record record : dataList) {
                ThirdPartWeComVideo item = new ThirdPartWeComVideo();
                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));
                item.setDt(dt);
                item.setVideoId(videoId);
                item.setCategory(category);
                item.setTitle(title);
                item.setVideo(videoUrl);
                item.setScore(score);
                item.setCreateTimestamp(now);
                saveList.add(item);
            }
            // 获取视频封面
            setVideoCover(saveList);
            // save
            batchSaveVideo(dt, saveList, now);
        }
        // 更新封面
        updateVideoCover();
        return ReturnT.SUCCESS;
    }

    private void setVideoCover(List<ThirdPartWeComVideo> videoList) {
        for (List<ThirdPartWeComVideo> partition : Lists.partition(videoList, 20)) {
            List<Long> videoIds = partition.stream().map(ThirdPartWeComVideo::getVideoId).distinct().collect(Collectors.toList());
            Map<Long, VideoDetail> coverMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
            for (ThirdPartWeComVideo 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);
                    }
                }
            }
        }
    }

    private void batchSaveVideo(String dt, List<ThirdPartWeComVideo> saveList, Long now) {
        if (CollectionUtils.isNotEmpty(saveList)) {
            List<ThirdPartWeComVideo> 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(ThirdPartWeComVideo::getVideoId).collect(Collectors.toList());
                List<Long> videoIdList = saveList.stream().map(ThirdPartWeComVideo::getVideoId).collect(Collectors.toList());
                videoMapperExt.updateOtherVideoStatus(dt, videoIdList, now);
                saveList = saveList.stream().filter(item -> !tempExistVideoIds.contains(item.getVideoId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(saveList)) {
                    videoMapperExt.batchInsertThirdPartWeComVideo(saveList);
                }
            } else {
                videoMapperExt.batchInsertThirdPartWeComVideo(saveList);
            }
        }
    }

    private void updateVideoCover() {
        List<ThirdPartWeComVideo> nullCoverVideoList = getVideoNullCover();
        if (CollectionUtils.isNotEmpty(nullCoverVideoList)) {
            for (List<ThirdPartWeComVideo> partition : Lists.partition(nullCoverVideoList, 20)) {
                List<Long> videoIds = partition.stream().map(ThirdPartWeComVideo::getVideoId).distinct().collect(Collectors.toList());
                Map<Long, VideoDetail> coverMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
                for (ThirdPartWeComVideo 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);
                }
            }
        }
    }

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

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

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

    private List<ThirdPartWeComVideo> getVideoListByDt(String dt) {
        ThirdPartWeComVideoExample example = new ThirdPartWeComVideoExample();
        example.createCriteria().andDtEqualTo(dt);
        return videoMapper.selectByExample(example);
    }

    @XxlJob("checkThirdPartWeComVideoStatusJob")
    public ReturnT<String> checkThirdPartWeComVideoStatusJob(String param) {
        String dt = videoMapperExt.getVideoMaxDt();
        if (StringUtils.hasText(param)) {
            dt = param;
        }
        List<ThirdPartWeComVideo> videoList = getVideoListByDt(dt);
        Long now = System.currentTimeMillis();
        for (List<ThirdPartWeComVideo> partition : Lists.partition(videoList, 20)) {
            List<Long> videoIds = partition.stream().map(ThirdPartWeComVideo::getVideoId).collect(Collectors.toList());
            Map<Long, VideoDetail> videoDetailMap = messageAttachmentService.getVideoDetail(new HashSet<>(videoIds));
            for (ThirdPartWeComVideo 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) {
        videoMapperExt.updateVideoStatusWithOldStatus(videoId, status, oldStatus, now);
    }

}
