package com.mmc.csf.release.service.impl;

import com.mmc.csf.common.util.page.PageResult;
import com.mmc.csf.common.util.web.ResultBody;
import com.mmc.csf.release.forum.vo.CommentAndReplyVO;
import com.mmc.csf.release.forum.vo.CommentVO;
import com.mmc.csf.release.forum.vo.DynamicVO;
import com.mmc.csf.release.forum.vo.MediaVO;
import com.mmc.csf.release.dao.CommentDAO;
import com.mmc.csf.release.dao.DynamicDAO;
import com.mmc.csf.release.dao.LikeDAO;
import com.mmc.csf.release.entity.ForumDynamicDO;
import com.mmc.csf.release.entity.ForumImageDO;
import com.mmc.csf.release.entity.ForumVideoDO;
import com.mmc.csf.release.service.DynamicService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author LW
 * @date 2023/5/15 10:29
 * 概要：动态信息实现层
 */
@Service
public class DynamicServiceImpl implements DynamicService {

    @Resource
    private DynamicDAO dynamicDAO;
    @Resource
    private LikeDAO likeDAO;
    @Resource
    private CommentDAO commentDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody insertDynamic(DynamicVO dynamicVO) {
        // 插入动态基本信息
        ForumDynamicDO forumDynamicDO = new ForumDynamicDO(dynamicVO);
        dynamicDAO.insertDynamic(forumDynamicDO);
        // 插入动态图片或视频
        MediaVO mediaVO = dynamicVO.getMediaVO();
        // 插入图片
        if (CollectionUtils.isNotEmpty(mediaVO.getPicture())) {
            for (String url : mediaVO.getPicture()) {
                dynamicDAO.insertPicture(forumDynamicDO.getId(), url);
            }
        }
        // 插入视频
        if (mediaVO.getVideoUrl() != null) {
            dynamicDAO.insertVideo(forumDynamicDO.getId(), mediaVO.getVideoUrl());
        }
        return ResultBody.success("动态发布成功");
    }

    @Override
    public ResultBody likeDynamic(Integer userId, Integer dynamicId) {
        // 获取动态信息
        ForumDynamicDO forumDynamicDO = dynamicDAO.getDynamicInfo(dynamicId);
        if (!likeDAO.isLiked(userId, dynamicId)) {
            likeDAO.insertLike(userId, dynamicId);
            dynamicDAO.updateDynamicLikeCount(dynamicId, forumDynamicDO.getPid());
        } else {
            likeDAO.deleteLike(userId, dynamicId);
            dynamicDAO.updateSubDynamicLikeCount(dynamicId, forumDynamicDO.getPid());
        }
        return ResultBody.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody commentDynamic(CommentVO commentVO) {
        ForumDynamicDO forumDynamicDO = dynamicDAO.getDynamicInfo(commentVO.getDynamicId());
        if (forumDynamicDO == null) {
            return ResultBody.error("动态不存在或已删除");
        }
        if (commentVO.getParentId() == null) {
            commentDAO.insertComment(commentVO.getUserId(), commentVO.getDynamicId(), commentVO.getContent());
        } else {
            commentDAO.insertReplyComment(commentVO.getUserId(), commentVO.getDynamicId(), commentVO.getContent(), commentVO.getParentId());
        }
        dynamicDAO.updateDynamicCommentCount(commentVO.getDynamicId(), forumDynamicDO.getPid());
        return ResultBody.success();
    }

    @Override
    public ResultBody deleteComment(Integer id) {
        commentDAO.deleteComment(id);
        return ResultBody.success();
    }

    @Override
    public List<CommentAndReplyVO> getCommentAndReply(int dynamicId) {
        // 获取评论列表
        List<CommentAndReplyVO> commentList = commentDAO.selectCommentList(dynamicId);
        List<CommentAndReplyVO> topLevelComment = new ArrayList<>();
        Map<Integer, CommentAndReplyVO> commentMap = new HashMap<>();
        // 将每个数据模型对象添加到Map中，以便在递归过程中查找它们的父母
        for (CommentAndReplyVO comment : commentList) {
            comment.setChildren(new ArrayList<>());
            commentMap.put(comment.getId(), comment);
        }
        // 构建树结构
        for (CommentAndReplyVO comment : commentList) {
            if (comment.getParentId() == 0) {
                topLevelComment.add(comment);
            } else {
                CommentAndReplyVO parent = commentMap.get(comment.getParentId());
                parent.getChildren().add(comment);
            }
        }
        return topLevelComment;
    }

    @Override
    public PageResult dynamicList(Integer pageNo, Integer pageSize, Integer userId) {
        int count = dynamicDAO.countDynamicList();
        if (count == 0) {
            return PageResult.buildPage(pageNo, pageSize, 0);
        }
        int itemIndex = (pageNo - 1) * pageSize;
        List<ForumDynamicDO> forumDynamicList = dynamicDAO.dynamicList(itemIndex, pageSize);
        // 动态id集合
        List<Integer> ids = forumDynamicList.stream().map(ForumDynamicDO::getId).collect(Collectors.toList());
        // 根据id集合查询图片
        List<ForumImageDO> forumImageList = dynamicDAO.listDynamicPicture(ids);
        Map<Integer, List<ForumImageDO>> ImageMap = forumImageList.stream().collect(Collectors.groupingBy(ForumImageDO::getDynamicId));
        // 获取视频信息
        List<ForumVideoDO> forumVideoList = dynamicDAO.listDynamicVideo(ids);
        List<DynamicVO> dynamicVOList = forumDynamicList.stream()
                .map(d -> {
                    MediaVO mediaVO = new MediaVO();
                    if (CollectionUtils.isNotEmpty(ImageMap.get(d.getId()))) {
                        mediaVO.setPicture(ImageMap.get(d.getId()).stream().map(ForumImageDO::getUrl).collect(Collectors.toList()));
                    }
                    for (ForumVideoDO forumVideoDO : forumVideoList) {
                        if (forumVideoDO.getDynamicId().equals(d.getId())) {
                            mediaVO.setVideoUrl(forumVideoDO.getUrl());
                            break;
                        }
                    }
                    DynamicVO dynamicVO = d.buildDynamicVO();
                    dynamicVO.setMediaVO(mediaVO);
                    // 设置是否点赞
                    boolean liked = likeDAO.isLiked(userId, d.getId());
                    dynamicVO.setLikes(liked);
                    return dynamicVO;
                }).collect(Collectors.toList());
        return PageResult.buildPage(pageNo, pageSize, count, dynamicVOList);
    }
}
