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

import cn.reghao.file.api.dto.JobInfo;
import cn.reghao.file.api.iface.FileService;
import cn.reghao.file.api.iface.OssService;
import cn.reghao.jutil.jdk.web.db.Page;
import cn.reghao.jutil.jdk.web.db.PageList;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.tnb.content.app.vod.model.dto.VideoUrlDto;
import cn.reghao.tnb.content.api.constant.PostScope;
import cn.reghao.tnb.content.api.dto.*;
import cn.reghao.tnb.content.app.vod.db.mapper.SiteNoticeMapper;
import cn.reghao.tnb.content.app.vod.db.mapper.VideoPostMapper;
import cn.reghao.tnb.content.app.vod.db.repository.VideoRepository;
import cn.reghao.tnb.content.app.vod.model.dto.CategoryAdd;
import cn.reghao.tnb.content.app.vod.model.dto.NoticeAdd;
import cn.reghao.tnb.content.app.vod.model.po.BannerVideo;
import cn.reghao.tnb.content.app.vod.model.po.SiteNotice;
import cn.reghao.tnb.content.app.vod.model.po.VideoPost;
import cn.reghao.tnb.content.app.vod.model.query.VideoQuery;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2024-07-06 22:16:55
 */
@Service
public class AdminVodService {
    @DubboReference(check = false)
    private OssService ossService;
    @DubboReference(check = false)
    private FileService fileService;

    private int pageSize = 100;
    private RabbitTemplate rabbitTemplate;
    private SiteNoticeMapper siteNoticeMapper;
    private VideoPostMapper videoPostMapper;
    private VideoPostQuery videoPostQuery;
    private VideoRepository videoRepository;
    private CategoryService categoryService;

    public AdminVodService(RabbitTemplate rabbitTemplate, SiteNoticeMapper siteNoticeMapper, VideoPostMapper videoPostMapper,
                           VideoPostQuery videoPostQuery, VideoRepository videoRepository, CategoryService categoryService) {
        this.rabbitTemplate = rabbitTemplate;
        this.siteNoticeMapper = siteNoticeMapper;
        this.videoPostMapper = videoPostMapper;
        this.videoPostQuery = videoPostQuery;
        this.videoRepository = videoRepository;
        this.categoryService = categoryService;
    }

    public void setSiteNotice(NoticeAdd noticeAdd) {
        long createBy = 10001;
        SiteNotice siteNotice = new SiteNotice(noticeAdd.getContent(), createBy);
        siteNoticeMapper.save(siteNotice);
    }

    public String getSiteNotice() {
        SiteNotice siteNotice = siteNoticeMapper.findLatest();
        return siteNotice != null ? siteNotice.getContent() : "N/A";
    }

    public PageList<UserVideoPost> getUserVideoPosts(VideoSearch videoSearch) {
        PageList<UserVideoPost> pageList = getVideoPosts(videoSearch);
        return pageList;
    }

    public List<VideoRegion> getVideoCategories() {
        return Collections.emptyList();
    }

    public PageList<JobInfo> getJobs() {
        PageList<JobInfo> pageList = fileService.getJobs(1, 10);
        return pageList;
    }

    public List<VideoRegion> getVideoRegions() {
        return categoryService.getCategories(true);
    }

    public PageList<UserVideoPost> getVideoPosts(VideoSearch videoSearch) {
        int pageNumber = videoSearch.getPageNumber();
        int pageSize = videoSearch.getPageSize();
        Page page = new Page(pageNumber, pageSize);
        String content = videoSearch.getContent();

        VideoQuery videoQuery = new VideoQuery.Builder()
                .status(null)
                .scope(null)
                .title(content)
                .orderBy(videoSearch.getOrderBy())
                .orderDirection(videoSearch.getOrderDirection())
                .build();
        int total = videoPostMapper.countAdminVideo(videoQuery);
        List<UserVideoPost>list = videoPostMapper.findAdminVideoByPage(page, videoQuery).stream()
                .map(videoPostQuery::getUserVideoPost)
                .collect(Collectors.toList());
        return PageList.pageList(pageNumber, 20, total, list);
    }

    @Deprecated
    public void setHotVideo() {
        String routeKey = "tnb.data";
        List<BannerVideo> list = new ArrayList<>();
        rabbitTemplate.convertAndSend(routeKey, JsonConverter.objectToJson(list));
    }

    public VideoUrls getVideoUrl(String videoId) {
        double currentTime = 0.0;
        VideoPost videoPost = videoPostMapper.findByVideoId(videoId);
        if (videoPost == null) {
            return new VideoUrls();
        }

        List<VideoUrlDto> list = videoRepository.getVideoUrls(videoId);
        if (list.isEmpty()) {
            return new VideoUrls();
        }

        String urlType = list.get(0).getType();
        int scope = videoPost.getScope();
        if (scope != PostScope.PUBLIC.getCode()) {
            try {
                List<VideoUrl> urls = list.stream().map(videoUrlDto -> {
                    try {
                        int channelCode = videoUrlDto.getChannelCode();
                        String quality = videoUrlDto.getQuality();
                        String signedUrl = ossService.getSignedUrl(videoUrlDto.getObjectId(), null);
                        return new VideoUrl(quality, signedUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }).filter(Objects::nonNull).collect(Collectors.toList());
                return new VideoUrls(currentTime, urlType, urls);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new VideoUrls();
        } else {
            List<VideoUrl> urls = list.stream().map(videoUrlDto -> {
                String quality = videoUrlDto.getQuality();
                String url = videoUrlDto.getUrl();
                return new VideoUrl(quality, url);
            }).collect(Collectors.toList());
            return new VideoUrls(currentTime, urlType, urls);
        }
    }

    public Long getImageAlbum(String objectId) {
        return null;
    }

    public void addConvertedVideo(VideoConvertedDto videoConvertedDto) {
        /*String uploadId = videoConvertedDto.getUploadId();
        int channelCode = videoConvertedDto.getChannelCode();
        try {
            VideoInfo videoInfo = ossService.getVideoInfo(uploadId);
            if (videoInfo == null) {
                String errMsg = String.format("视频文件 %s 在 oss 中不存在", uploadId);
                log.info(errMsg);
                return;
            }

            String videoFileId = videoConvertedDto.getVideoFileId();
            VideoPost videoPost = videoRepository.getVideoPostByFileId(videoFileId);
            int scope = videoPost.getScope();
            if (scope != ObjectScope.PRIVATE.getCode()) {
                ossService.setObjectScope(channelCode, uploadId, scope);
            }

            String videoId = videoPost.getVideoId();
            VideoFile videoFile = new VideoFile(videoId, videoFileId, channelCode, videoInfo);
            videoRepository.updateVideoPublish(videoId, videoFile);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    public void addVideoCategory(CategoryAdd categoryAdd) {
        categoryService.addVideoCategory(categoryAdd);
    }
}
