package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.communityNews.CommentContent;
import com.ruoyi.system.domain.communityNews.CommentIndex;
import com.ruoyi.system.domain.communityNews.CommunityNews;
import com.ruoyi.system.domain.communityNews.vo.CommentChildrenVo;
import com.ruoyi.system.domain.communityNews.vo.CommentIndexShVo;
import com.ruoyi.system.domain.communityNews.vo.CommentIndexVo;
import com.ruoyi.system.mapper.CommentContentMapper;
import com.ruoyi.system.mapper.CommentIndexMapper;
import com.ruoyi.system.mapper.CommunityNewsMapper;
import com.ruoyi.system.service.ICommentIndexService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.ruoyi.common.constant.Constants.*;

/**
 * 社区资讯评论Service业务层处理
 *
 * @author boman
 * @date 2025-02-25
 */
@Service
public class CommentIndexServiceImpl implements ICommentIndexService {
    @Autowired
    private CommentIndexMapper commentIndexMapper;
    @Resource
    private CommentContentMapper commentContentMapper;
    @Resource
    private CommunityNewsMapper communityNewsMapper;

    @Resource
    private RedisCache redisCache;

    /**
     * 查询社区资讯评论
     *
     * @param commentId 社区资讯评论主键
     * @return 社区资讯评论
     */
    @Override
    public CommentIndex selectCommentIndexByCommentId(Long commentId) {
        return commentIndexMapper.selectCommentIndexByCommentId(commentId);
    }

    /**
     * 查询社区资讯评论列表
     *
     * @param commentIndex 社区资讯评论
     * @return 社区资讯评论
     */
    @Override
    public List<CommentIndex> selectCommentIndexList(CommentIndex commentIndex) {
        return commentIndexMapper.selectCommentIndexList(commentIndex);
    }

    /**
     * 查询社区资讯评论审核列表
     */
    @Override
    public List<CommentIndexShVo> commentSh(CommentIndexShVo commentIndexShVo) {
        return commentIndexMapper.commentSh(commentIndexShVo);
    }

    /**
     * 新增社区资讯评论
     *
     * @param commentIndex 社区资讯评论
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCommentIndex(CommentIndex commentIndex) {
        int result = 1;
        //有社区资讯ID才能新增评论
        Long communityId = commentIndex.getCommunityId();
        if (communityId != null) {
            Long userId = commentIndex.getUserId();
            //需要插入评论内容表
            CommentContent commentContent = new CommentContent();
            commentContent.setUserId(userId);
            commentContent.setCommentContent(commentIndex.getCommentContent());
            commentContentMapper.insertCommentContent(commentContent);
            commentIndex.setCreateTime(DateUtils.getNowDate());
            commentIndex.setContentId(commentContent.getContentId());
            result = commentIndexMapper.insertCommentIndex(commentIndex);
            //再把评论内容表更新上资讯评论表id
            commentContent.setCommentId(commentIndex.getCommentId());
            commentContentMapper.updateCommentContent(commentContent);
            //记录该社区资讯评论的数量
            String communityCommentCountKey = COMMUNITY_COMMENT_COUNT + communityId;
            Integer communityCommentCount = redisCache.getCacheObject(communityCommentCountKey);
            if (communityCommentCount == null) {
                redisCache.setCacheObject(communityCommentCountKey, 1);
            } else {
                //评论数量+1
                redisCache.setCacheObject(communityCommentCountKey, communityCommentCount + 1);
            }
        }
        return result;
    }

    /**
     * 修改社区资讯评论
     *
     * @param commentIndex 社区资讯评论
     * @return 结果
     */
    @Override
    public int updateCommentIndex(CommentIndex commentIndex) {
        commentIndex.setUpdateTime(DateUtils.getNowDate());
        return commentIndexMapper.updateCommentIndex(commentIndex);
    }

    /**
     * 批量删除社区资讯评论
     *
     * @param commentIds 需要删除的社区资讯评论主键
     * @return 结果
     */
    @Override
    public int deleteCommentIndexByCommentIds(Long[] commentIds) {
        return commentIndexMapper.deleteCommentIndexByCommentIds(commentIds);
    }

    /**
     * 删除社区资讯评论信息
     *
     * @param commentId 社区资讯评论主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteCommentIndexByCommentId(Long commentId) {
        //todo 管理员能删除评论
        //只能删除自己的评论
        CommentIndex commentIndex = commentIndexMapper.selectCommentIndexByCommentId(commentId);
        int result = 0;
        int communityCommentCount = 0;
        //查找出所有parent_id = commentId的commentId
        if (commentIndex != null && commentIndex.getUserId().equals(SecurityUtils.getUserId())) {
            //社区资讯id
            Long communityId = commentIndex.getCommunityId();
            result = commentIndexMapper.updateCommentIndexByCommentId(commentId);
            //删除评论内容表数据
            commentContentMapper.updateCommentContentByContentId(commentId);
            //如果是根评论删除，删除所有子评论
            if (1 == commentIndex.getIsRoot()) {
                //查找出所有parent_id = commentId的commentId
                //commentIdList = commentIndexMapper.selectCommentIdListByCommentId(commentId);
                int i = commentIndexMapper.updateCommentIndexByParentId(commentId);
                result = result + i;
                //删除评论内容表子集数据
                commentContentMapper.deleteCommentContentByCommentId(commentId);
            }
            //删除该资讯的评论数量
            String communityCommentCountKey = COMMUNITY_COMMENT_COUNT + communityId;
            communityCommentCount = redisCache.getCacheObject(communityCommentCountKey);
            if (communityCommentCount != 0) {
                //删除所有的评论数量 = 根评论数量+子评论数量
                communityCommentCount = communityCommentCount - result;
                if (communityCommentCount < 0) {
                    communityCommentCount = 0;
                }
                redisCache.setCacheObject(communityCommentCountKey, communityCommentCount);
            }
            //删除社区资讯评论点赞的数量永久key key=two_like_count:{评论id} value = 该评论的点赞数量
            redisCache.deleteObject(TWO_LIKE_COUNT + commentId);
            //社区资讯回复点赞的人员集合的key
            redisCache.deleteObject(TWO_LIKE + commentId);
            //对应用户点赞的回复key=two_my_like:{用户id} value = [评论id]
            Long userId = SecurityUtils.getUserId();
            List<Long> commentIdList = redisCache.getCacheList(TWO_MY_LIKE + userId);
            if (commentIdList != null && commentIdList.size() > 0) {
                commentIdList.remove(commentId);
            }
            redisCache.deleteObject(TWO_MY_LIKE + userId);
            if (commentIdList != null && commentIdList.size() > 0) {
                redisCache.setCacheList(TWO_MY_LIKE + userId, commentIdList);
            }
/*            //删除该资讯点赞的数量需要知道所有评论的id
            //首先获取该文章资讯的总点赞数量
            Integer likeCount = redisCache.getCacheObject(ONE_LIKE_COUNT + communityId);
            //再获取删除的评论的点赞数量
            Integer commentLikeCount = redisCache.getCacheObject(TWO_LIKE_COUNT + commentId);
            //所有子集的点赞数量
            int commentLikeChildrenCount = 0;
            if (commentIdList.size() > 0) {
                //说明删除了子集、获取所有子集的点赞数量
                for (Long commentIdChildren : commentIdList) {
                    String commentLikeChildrenCountString = redisCache.getCacheObject(TWO_LIKE_COUNT + commentIdChildren);
                    if (StringUtils.isNotBlank(commentLikeChildrenCountString)) {
                        commentLikeChildrenCount = commentLikeChildrenCount + Integer.parseInt(commentLikeChildrenCountString);
                    }
                }
            }
            if (commentLikeCount == null){
                commentLikeCount = 0;
            }
            if (likeCount == null){
                likeCount = 0;
            }
            //把删除后点赞数量写入到redis
            likeCount = likeCount - commentLikeCount - commentLikeChildrenCount;
            if (likeCount < 0){
                likeCount = 0;
            }
            redisCache.setCacheObject(ONE_LIKE_COUNT + communityId, likeCount);*/
            //删除评论需要根据这个评论是根评论还子评论，根评论删除对应资讯发布人的未读互动里面对应的值(如果有)根评论还会删除所有子评论，子评论删除评论对象的未读互动
            Integer isRoot = commentIndex.getIsRoot();
            if (1 == isRoot) {
                //如果是根评论先查询是否有子集评论
                List<CommentIndex> commentIndexList = commentIndexMapper.selectCommentIdListByCommentId(commentId);
                if (commentIndexList != null && commentIndexList.size() > 0) {
                    for (CommentIndex index : commentIndexList) {
                        //删除未读互动中的子评论相关信息
                        deleteCommentChildren(index);
                    }
                }
                //删除根评论相关信息
                //根据资讯id查询资讯发布人的id
                CommunityNews communityNews = communityNewsMapper.selectCommunityNewsByCommunityId(communityId);
                Long toUserId = communityNews.getUserId();
                String commentInteractionUserKey = COMMENT_INTERACTION_USER + toUserId;
                //hKey={targetType:targetId}
                String hKey = ONE + ":" + commentId;
                if (redisCache.hasCacheMapKey(commentInteractionUserKey, hKey)) {
                    //说明有对应的未读互动删除对应的key
                    redisCache.deleteCacheMapValue(commentInteractionUserKey, hKey);
                    //目标人员的未读数量-1
                    String commentInteractionUserCountKey = COMMENT_INTERACTION_USER_COUNT + toUserId;
                    Object commentInteractionUserCount = redisCache.getCacheObject(commentInteractionUserCountKey);
                    if (ObjectUtils.isNotEmpty(commentInteractionUserCount)) {
                        redisCache.setCacheObject(commentInteractionUserCountKey, Math.max(Integer.parseInt(commentInteractionUserCount.toString()) - 1, 0));
                    }
                    //对应资讯下的未读数量-1
                    Object communityUserCount = redisCache.getCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + toUserId, communityId.toString());
                    if (ObjectUtils.isNotEmpty(communityUserCount)) {
                        redisCache.setCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + toUserId, communityId.toString(), Math.max(Integer.parseInt(communityUserCount.toString()) - 1, 0));
                    }
                }
            } else {
                //删除未读互动中的子评论相关信息
                deleteCommentChildren(commentIndex);
            }
        }
        return result;
    }

    /**
     * 删除未读互动中的子评论相关信息
     *
     * @param commentIndex
     */
    public void deleteCommentChildren(CommentIndex commentIndex) {
        Long commentId = commentIndex.getCommentId();
        Long communityId = commentIndex.getCommunityId();
        //子评论
        //获取到回复的人的id
        Long toUserId = commentIndex.getToUserId();
        //判断该用户是否有未读的子评论互动
        String commentInteractionUserKey = COMMENT_INTERACTION_USER + toUserId;
        //hKey={targetType:targetId}
        String hKey = FOR + ":" + commentId;
        if (redisCache.hasCacheMapKey(commentInteractionUserKey, hKey)) {
            //说明有对应的未读互动删除对应的key
            redisCache.deleteCacheMapValue(commentInteractionUserKey, hKey);
            //目标人员的未读数量-1
            String commentInteractionUserCountKey = COMMENT_INTERACTION_USER_COUNT + toUserId;
            Object commentInteractionUserCount = redisCache.getCacheObject(commentInteractionUserCountKey);
            if (ObjectUtils.isNotEmpty(commentInteractionUserCount)) {
                redisCache.setCacheObject(commentInteractionUserCountKey, Math.max(Integer.parseInt(commentInteractionUserCount.toString()) - 1, 0));
            }
            //对应资讯下的未读数量-1
            Object communityUserCount = redisCache.getCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + toUserId, communityId.toString());
            if (ObjectUtils.isNotEmpty(communityUserCount)) {
                redisCache.setCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + toUserId, communityId.toString(), Math.max(Integer.parseInt(communityUserCount.toString()) - 1, 0));
            }
        }
    }

    /**
     * 根据parent_id查询所有评论组装成前端所需要的子集数据结构 带分页
     *
     * @param commentIndex
     * @return
     */
    @Override
    public AjaxResult getParentComment(CommentIndex commentIndex) {
        Long userId = SecurityUtils.getUserId();
        List<CommentChildrenVo> allComment = commentIndexMapper.getParentComment(commentIndex);
        //要判断所有评论当前人员是否点赞过
        if (allComment != null && allComment.size() > 0) {
            //要判断所有评论当前人员是否点赞过
            //该用户点赞回复的key
            String myLikeTwoKey = TWO_MY_LIKE + userId;
            List<Long> communityIdList = redisCache.getCacheList(myLikeTwoKey);
            if (communityIdList != null && communityIdList.size() > 0) {
                for (CommentChildrenVo commentChildrenVo : allComment) {
                    if (communityIdList.contains(commentChildrenVo.getId())) {
                        commentChildrenVo.setIsLike("Y");
                    }
                }
            }
            for (CommentChildrenVo commentChildrenVo : allComment) {
                //是否是自己的评论
                if (commentChildrenVo.getCommentUser().getId().equals(userId)) {
                    commentChildrenVo.setIsMyself("Y");
                }
            }
        }
        return AjaxResult.success(allComment);
    }

    /**
     * 根据查询所有一级评论组带子集总数组装成前端所需要的数据结构 带分页
     *
     * @param commentIndex
     * @return
     */
    @Override
    public List<CommentIndexVo> getRootComment(CommentIndex commentIndex) {
        Long userId = SecurityUtils.getUserId();
        List<CommentIndexVo> rootComment = commentIndexMapper.getRootComment(commentIndex);
        if (rootComment != null && rootComment.size() > 0) {
            //要判断所有评论当前人员是否点赞过
            //该用户点赞回复的key
            String myLikeTwoKey = TWO_MY_LIKE + userId;
            List<Long> communityIdList = redisCache.getCacheList(myLikeTwoKey);
            if (communityIdList != null && communityIdList.size() > 0) {
                for (CommentIndexVo commentIndexVo : rootComment) {
                    if (communityIdList.contains(commentIndexVo.getId())) {
                        commentIndexVo.setIsLike("Y");
                    }
                }
            }
            for (CommentIndexVo commentIndexVo : rootComment) {
                //是否是自己的评论
                if (commentIndexVo.getCommentUser().getId().equals(userId)) {
                    commentIndexVo.setIsMyself("Y");
                }
            }
        }
        return rootComment;
    }
}
