package cn.reghao.tnb.content.app.vod.service.impl;

import cn.reghao.file.api.iface.OssService;
import cn.reghao.jutil.jdk.db.Page;
import cn.reghao.jutil.jdk.db.PageList;
import cn.reghao.jutil.web.WebResult;
import cn.reghao.oss.sdk.model.dto.media.VideoInfo;
import cn.reghao.oss.sdk.model.dto.media.VideoUrlDto;
import cn.reghao.tnb.account.api.iface.AccountQuery;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.common.util.StringUtil;
import cn.reghao.tnb.content.api.constant.PostScope;
import cn.reghao.tnb.content.api.constant.VideoStatus;
import cn.reghao.tnb.content.api.dto.UserVideoPost;
import cn.reghao.tnb.content.api.dto.VideoCard;
import cn.reghao.tnb.content.api.dto.VideoPostCard;
import cn.reghao.tnb.content.app.vod.db.mapper.*;
import cn.reghao.tnb.content.app.vod.db.repository.VideoRepository;
import cn.reghao.tnb.content.app.vod.model.po.*;
import cn.reghao.tnb.content.app.vod.model.vo.BannerVideoVO;
import cn.reghao.tnb.content.app.vod.model.vo.VideoDetail;
import cn.reghao.tnb.content.app.vod.model.query.VideoQuery;
import cn.reghao.tnb.content.app.vod.service.CategoryService;
import cn.reghao.tnb.content.app.vod.service.ContentPermission;
import cn.reghao.tnb.content.app.vod.service.VideoPostQuery;
import cn.reghao.tnb.user.api.dto.UserCard;
import cn.reghao.tnb.user.api.iface.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2024-08-06 21:01:22
 */
@Service
public class VideoPostQueryImpl implements VideoPostQuery {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private AccountQuery accountQuery;
    @DubboReference(check = false)
    private UserService userService;
    @DubboReference(check = false)
    private OssService ossService;

    private final int pageSize = 12;
    private final VideoPostMapper videoPostMapper;
    private final VideoFileMapper videoFileMapper;
    private final VideoStatisticMapper videoStatisticMapper;
    private final VideoCategoryPostMapper videoCategoryPostMapper;
    private final VideoTagMapper videoTagMapper;
    private final VideoPostTagMapper videoPostTagMapper;
    private final ContentPermission contentPermission;
    private final CategoryService categoryService;
    private final VideoRepository videoRepository;
    private final Random random = new SecureRandom();
    private final BannerVideoMapper bannerVideoMapper;

    public VideoPostQueryImpl(VideoPostMapper videoPostMapper, VideoFileMapper videoFileMapper, VideoTagMapper videoTagMapper,
                              VideoStatisticMapper videoStatisticMapper, VideoCategoryPostMapper videoCategoryPostMapper,
                              ContentPermission contentPermission, CategoryService categoryService,
                              VideoRepository videoRepository, VideoPostTagMapper videoPostTagMapper,
                              BannerVideoMapper bannerVideoMapper) {
        this.videoPostMapper = videoPostMapper;
        this.videoFileMapper = videoFileMapper;
        this.videoTagMapper = videoTagMapper;
        this.videoStatisticMapper = videoStatisticMapper;
        this.videoCategoryPostMapper = videoCategoryPostMapper;
        this.contentPermission = contentPermission;
        this.categoryService = categoryService;
        this.videoRepository = videoRepository;
        this.videoPostTagMapper = videoPostTagMapper;
        this.bannerVideoMapper = bannerVideoMapper;
    }

    public List<VideoCard> getVideoCards(List<String> videoIds) {
        List<VideoPostCard> list = videoPostMapper.findVideoCardByVideoIds(videoIds);
        return list.stream().map(videoPostCard -> getVideoCard(videoPostCard, true)).collect(Collectors.toList());
    }

    public PageList<VideoCard> getCategoryVideos(int categoryId, int pageNumber) {
        VideoCategory videoCategory = categoryService.getVideoCategory(categoryId);
        if (videoCategory == null) {
            return PageList.empty();
        }

        List<Integer> scopes = contentPermission.getUserScopes();
        VideoQuery videoQuery;
        int pid = videoCategory.getPid();
        if (pid == 0) {
            videoQuery = new VideoQuery.Builder()
                    .scope(scopes)
                    .categoryPid(categoryId)
                    .groupBy("publish_by")
                    .orderBy("publish_at")
                    .orderDirection("desc")
                    .build();
        } else {
            videoQuery = new VideoQuery.Builder()
                    .scope(scopes)
                    .categoryId(categoryId)
                    .groupBy("publish_by")
                    .orderBy("publish_at")
                    .orderDirection("desc")
                    .build();
        }

        return getVideoCardsByUserGroup(videoQuery, pageNumber);
    }

    public VideoDetail getShortVideo() {
        String videoId = getRandomVideoId();
        if (videoId == null) {
            return null;
        }

        VideoPost videoPost = videoPostMapper.findByVideoId(videoId);
        VideoStatistic videoStatistic = videoStatisticMapper.findByVideoId(videoId);

        long publishBy = videoPost.getPublishBy();
        String publishByStr = accountQuery.getUserIdStr(publishBy);
        VideoDetail videoDetail = new VideoDetail(videoPost, videoStatistic, publishByStr);
        List<String> tags = videoTagMapper.findVideoTags(videoId);
        videoDetail.setTags(tags);
        return videoDetail;
    }

    private String getRandomVideoId() {
        long loginUser = UserContext.getUser();
        List<Integer> userScopes = contentPermission.getUserScopes(loginUser);
        List<String> videoIds = videoRepository.getShortVideoIds(userScopes);
        if (videoIds.isEmpty()) {
            return null;
        }

        int min = 0;
        int size = videoIds.size();
        int randomIdx = min + random.nextInt(size-1 - min);
        return videoIds.get(randomIdx);
    }

    private PageList<VideoCard> getVideoCardsByUserGroup(VideoQuery videoQuery, int pageNumber) {
        int total = videoCategoryPostMapper.countByCriteria(videoQuery);
        if (total > pageSize*100) {
            total = pageSize*100;
            if (pageNumber > 100) {
                pageNumber = 100;
            }
        } else if (total == 0) {
            return PageList.empty();
        }

        Page page = new Page(pageNumber, pageSize);
        List<VideoCategoryPost> list0 = videoCategoryPostMapper.findVideoCategoryPostByPage(page, videoQuery);
        List<String> videoIds = list0.stream().map(VideoCategoryPost::getVideoId).collect(Collectors.toList());
        List<VideoPostCard> list = videoPostMapper.findVideoCardByVideoIds(videoIds);
        List<VideoCard> list1 = list.stream()
                .map(videoPostCard -> getVideoCard(videoPostCard, true))
                .collect(Collectors.toList());
        return PageList.pageList(pageNumber, pageSize, total, list1);
    }

    @Override
    public PageList<VideoCard> getTagVideos(String tag, int pn) {
        VideoTag videoTag = videoTagMapper.findByName(tag);
        if (videoTag == null) {
            return PageList.empty();
        }

        long loginUser = UserContext.getUser();
        List<Integer> userScopes = contentPermission.getUserScopes(loginUser);
        String tagId = videoTag.getTagId();
        int total = videoPostTagMapper.countVideosByTag(tagId, userScopes);
        Page page = new Page(pn, pageSize);
        List<String> videoIds = videoPostTagMapper.findVideosByPage(page, tagId, userScopes);
        List<VideoPostCard> list = videoPostMapper.findVideoCardByVideoIds(videoIds);
        List<VideoCard> list1 = list.stream()
                .map(videoPostCard -> getVideoCard(videoPostCard, true))
                .collect(Collectors.toList());

        return PageList.pageList(pn, pageSize, total, list1);
    }

    public PageList<VideoCard> getUserVideos(long userId, int page) {
        VideoQuery videoQuery;
        long loginUser = UserContext.getUser();
        if (loginUser == userId) {
            videoQuery = new VideoQuery.Builder().status(getVideoStatusList()).userId(userId).build();
        } else {
            List<Integer> scopes = contentPermission.getUserScopes();
            videoQuery = new VideoQuery.Builder().scope(scopes).userId(userId).build();
        }

        return getVideoCards(videoQuery, page, false);
    }

    private List<Integer> getVideoStatusList() {
        List<Integer> list = new ArrayList<>();
        for (VideoStatus videoStatus : VideoStatus.values()) {
            list.add(videoStatus.getCode());
        }

        return list;
    }

    private PageList<VideoCard> getVideoCards(VideoQuery videoQuery, int page, boolean user) {
        int total = videoPostMapper.countByCriteria(videoQuery);
        Page page1 = new Page(page, pageSize);
        List<VideoPostCard> list = videoPostMapper.findVideoCardByPage(page1, videoQuery);
        List<VideoCard> list1 = list.stream()
                .map(videoPostCard -> getVideoCard(videoPostCard, user))
                .collect(Collectors.toList());

        return PageList.pageList(page, pageSize, total, list1);
    }

    public VideoCard getVideoCard(VideoPostCard videoPostCard, boolean user) {
        UserCard userCard = null;
        if (user) {
            long userId = videoPostCard.getPublishBy();
            userCard = userService.getUserAvatar(userId);
        }

        String publishAtStr = StringUtil.getPubDateStr(videoPostCard.getPublishAt());
        String durationStr = StringUtil.getTimeStr(videoPostCard.getDuration());
        boolean cached = videoPostCard.getStatus() == VideoStatus.publish.getCode();
        return new VideoCard(videoPostCard, durationStr, cached, publishAtStr, userCard);
    }

    public String getVideoPostData(String videoId) {
        VideoPost videoPost = videoPostMapper.findByVideoId(videoId);
        if (videoPost == null) {
            return WebResult.notFound();
        }

        int status = videoPost.getStatus();
        if (status != VideoStatus.publish.getCode() && status != VideoStatus.noVideoFile.getCode()) {
            return WebResult.notFound();
        }

        long loginUser = UserContext.getUser();
        long owner = videoPost.getPublishBy();
        int scope = videoPost.getScope();
        if (scope == PostScope.PRIVATE.getCode() && owner != loginUser) {
            return WebResult.notFound();
        }

        boolean hasPermission = contentPermission.hasPermission(owner, scope, loginUser);
        if (!hasPermission) {
            return WebResult.failWithMsg("permission denied");
        }

        long publishBy = videoPost.getPublishBy();
        String publishByStr = accountQuery.getUserIdStr(publishBy);
        VideoStatistic videoStatistic = videoStatisticMapper.findByVideoId(videoId);
        VideoDetail videoDetail = new VideoDetail(videoPost, videoStatistic, publishByStr);
        List<String> tags = videoTagMapper.findVideoTags(videoId);
        videoDetail.setTags(tags);
        return WebResult.success(videoDetail);
    }

    public UserVideoPost getUserVideoPost(VideoPost videoPost) {
        String videoId = videoPost.getVideoId();
        String title = videoPost.getTitle();
        String description = videoPost.getDescription();
        String coverUrl = videoPost.getCoverUrl();
        LocalDateTime pubDate = videoPost.getPublishAt();
        int scope = videoPost.getScope();
        int status = videoPost.getStatus();
        int duration = videoPost.getDuration();
        String quality = "";
        String direction = videoPost.getHorizontal() ? "横屏" : "竖屏";
        String codec = "";
        return new UserVideoPost(videoId, title, description, coverUrl, pubDate, scope, status, duration, quality, direction, codec);
    }

    public List<BannerVideoVO> getBannerVideos() {
        List<BannerVideoVO> list = bannerVideoMapper.findBannerVideos();
        return list;
    }

    public List<String> getRandomTags(int size) {
        List<String> tagIds = videoTagMapper.findRandomTags(1000);
        return tagIds;
    }

    @Override
    public List<String> getRandomVideoIds(List<Integer> userScopes, int size) {
        if (userScopes.size() == 1 && userScopes.get(0).equals(PostScope.PROTECT.getCode())) {
            return getRandomVipVideoIds();
        }

        return videoPostMapper.findRandomVideoIds(userScopes, size);
    }

    private List<String> getRandomVipVideoIds() {
        VideoQuery videoQuery = new VideoQuery.Builder()
                .status(List.of(VideoStatus.publish.getCode()))
                .scope(List.of(PostScope.PROTECT.getCode()))
                .categoryPid(11)
                .build();
        int total = videoPostMapper.countByCriteria(videoQuery);
        Page page1 = new Page(1, Math.min(total, 100_000));
        List<String> videoIds = videoPostMapper.findVideoPostByPage(page1, videoQuery).stream()
                .map(VideoPost::getVideoId)
                .collect(Collectors.toList());
        if (videoIds.isEmpty()) {
            return videoIds;
        }

        List<String> results = new ArrayList<>();
        int min = 0;
        int size = videoIds.size();
        for (int i = 0; i < pageSize*10; i++) {
            int randomIdx = min + random.nextInt(size-1 - min);
            results.add(videoIds.get(randomIdx));
        }

        return results;
    }

    public List<VideoInfo> getVideoResource(String videoId) {
        VideoPost videoPost = videoPostMapper.findByVideoId(videoId);
        if (videoPost == null) {
            return Collections.emptyList();
        }

        int channelId = 105;
        List<VideoUrlDto> list = videoFileMapper.findVideoUrls(videoId);
        for (VideoUrlDto videoUrlDto : list) {
            String videoFileId = videoUrlDto.getObjectId();
            try {
                VideoInfo videoInfo = ossService.getVideoInfo(channelId, videoFileId);
                return videoInfo != null ? List.of(videoInfo) : Collections.emptyList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return Collections.emptyList();
    }


    /**
     * 获取用户发布的视频稿件
     *
     * @param
     * @return
     * @date 2023-11-27 11:01:22
     */
    public PageList<UserVideoPost> getUserVideoPost(int pageNumber) {
        Page page1 = new Page(pageNumber, pageSize);
        long userId = UserContext.getUser();

        VideoQuery videoQuery = new VideoQuery.Builder().status(getStatusList()).userId(userId).build();
        int total = videoPostMapper.countByCriteria(videoQuery);
        List<UserVideoPost> list = videoPostMapper.findVideoPostByPage(page1, videoQuery).stream()
                .map(this::getUserVideoPost)
                .collect(Collectors.toList());
        return PageList.pageList(pageNumber, pageSize, total, list);
    }

    private List<Integer> getStatusList() {
        List<Integer> list = new ArrayList<>();
        for (VideoStatus videoStatus : VideoStatus.values()) {
            list.add(videoStatus.getCode());
        }

        return list;
    }

    public UserVideoPost getUserVideoDetail(String videoId) {
        VideoPost videoPost = videoPostMapper.findByVideoId(videoId);
        return getUserVideoPost(videoPost);
    }
}
