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

import cn.reghao.jutil.jdk.db.PageList;
import cn.reghao.jutil.tool.id.SnowFlake;
import cn.reghao.tnb.account.api.iface.AccountQuery;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.api.dto.comment.CommentData;
import cn.reghao.tnb.content.app.vod.db.mapper.VideoPostMapper;
import cn.reghao.tnb.content.app.vod.db.mongo.UserCommentMongo;
import cn.reghao.tnb.content.app.vod.model.po.UserComment;
import cn.reghao.tnb.content.app.vod.model.po.VideoPost;
import cn.reghao.tnb.user.api.dto.UserCard;
import cn.reghao.tnb.user.api.dto.UserMessageDto;
import cn.reghao.tnb.user.api.iface.UserService;
import cn.reghao.tnb.content.api.dto.comment.CommentSbtDto;
import cn.reghao.tnb.content.api.dto.comment.ReplyUser;
import cn.reghao.tnb.content.api.dto.comment.UserReply;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-06-16 16:34:29
 */
@Service
public class CommentService {
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private UserService userService;
    @DubboReference(check = false, retries = 0, timeout = 60_000)
    private AccountQuery accountQuery;

    private final SnowFlake idGenerator;
    private final UserCommentMongo userCommentMongo;
    private final VideoPostMapper videoPostMapper;

    public CommentService(UserCommentMongo userCommentMongo, VideoPostMapper videoPostMapper) {
        this.idGenerator = new SnowFlake(1L, 1L);
        this.userCommentMongo = userCommentMongo;
        this.videoPostMapper = videoPostMapper;
    }

    public void saveComment(CommentSbtDto commentSbtDto) {
        long commentId = idGenerator.nextId();
        CommentData commentData = commentSbtDto.getNewComment();
        String userIdStr = commentData.getUser().getUserId();
        long userId = accountQuery.getUserIdLong(userIdStr);
        String postId = commentData.getPostId();

        CommentData parent = commentSbtDto.getParent();
        long parentId = 0;
        if (parent != null) {
            parentId = parent.getId();
        }

        String imageUrl = commentData.getImageUrl();
        if (imageUrl != null) {
            commentData.getImageUrls().add(imageUrl);
        }

        UserComment userComment = new UserComment(commentId, commentData, parentId);
        userCommentMongo.save(userComment);

        VideoPost videoPost = videoPostMapper.findByVideoId(postId);
        if (videoPost != null) {
            long publishBy = videoPost.getPublishBy();
            String title = "新评论";
            String content = "发表了新评论";
            UserMessageDto userMessageDto = new UserMessageDto(title, content, publishBy);
            userService.sendUserMessage(userMessageDto);
        }
    }

    @Deprecated
    public void saveBiliComment(CommentSbtDto commentSbtDto) {
        long commentId = commentSbtDto.getNewComment().getId();
        UserComment userComment = userCommentMongo.findByCommentId(commentId);
        if (userComment != null) {
            return;
        }

        CommentData commentData = commentSbtDto.getNewComment();
        long parentId = commentSbtDto.getParent().getId();
        userComment = new UserComment(parentId, commentId, commentData);
        userCommentMongo.save(userComment);
    }

    public PageList<UserReply> getUserComment(String videoId, int pageNumber) {
        long total = userCommentMongo.countByPostId(videoId);
        int pageSize = 10;
        List<UserReply> list = userCommentMongo.findByPostId(videoId, pageNumber).stream()
                .map(userComment -> {
                    long commentId = userComment.getCommentId();
                    UserReply commentVo = getCommentVo(userComment);
                    long total1 = userCommentMongo.countChildComment(commentId);
                    commentVo.setTotal(total1);
                    List<UserReply> childComments = userCommentMongo.findByParentId(commentId, 1, pageSize).stream()
                            .map(this::getCommentVo)
                            .collect(Collectors.toList());
                    commentVo.setChildren(childComments);
                    return commentVo;
                })
                .collect(Collectors.toList());
        return PageList.pageList(pageNumber, pageSize, (int) total, list);
    }

    private UserReply getCommentVo(UserComment userComment) {
        Long commentId = userComment.getCommentId();
        Long userId = userComment.getPublishBy();
        String userIdStr = accountQuery.getUserIdStr(userId);
        String postId = userComment.getPostId();
        String content = userComment.getContent();
        Long createAt = userComment.getPublishAt();
        String imgSrc = userComment.getImgSrc();
        List<String> images = userComment.getCommentImages();

        ReplyUser commentUser = new ReplyUser();
        commentUser.setUserId(userIdStr);
        UserCard userCard = userService.getUserAvatar(userId);
        if (userCard != null) {
            commentUser.setName(userCard.getScreenName());
            commentUser.setAvatar(userCard.getAvatarUrl());
        } else {
            commentUser.setName("哈哈");
            commentUser.setAvatar("avatar.jpg");
        }

        long loginUser = UserContext.getUserId();
        if (loginUser == userId) {
            commentUser.setAuthor(true);
        }

        UserReply commentVo = new UserReply();
        /*commentVo.setVideoId(postId);
        commentVo.setCommentId(commentId);*/
        commentVo.setId(commentId);
        commentVo.setContent(content);
        commentVo.setImgSrc(imgSrc);
        commentVo.setCreateAt(createAt);
        commentVo.setUser(commentUser);
        commentVo.setLikes(userComment.getLikes());
        commentVo.setLiked(false);

        if (images != null && !images.isEmpty()) {
            commentVo.setImgSrc(images.get(0));
        }

        return commentVo;
    }

    public PageList<UserReply> getChildComment(long commentId, int pageNumber) {
        int pageSize = 10;
        Long total = userCommentMongo.countChildComment(commentId);
        List<UserReply> list = userCommentMongo.findByParentId(commentId, pageNumber, pageSize).stream()
                .map(this::getCommentVo)
                .collect(Collectors.toList());
        return PageList.pageList(pageNumber, 10, total.intValue(), list);
    }

    public long countPostComment(String videoId) {
        return userCommentMongo.countByPostId(videoId);
    }
}
