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.StringUtils;
import com.ruoyi.system.domain.communityNews.CommentIndex;
import com.ruoyi.system.domain.communityNews.CommentLikes;
import com.ruoyi.system.domain.communityNews.CommunityNews;
import com.ruoyi.system.domain.communityNews.vo.CommentInteractionVo;
import com.ruoyi.system.mapper.CommentIndexMapper;
import com.ruoyi.system.mapper.CommentLikesMapper;
import com.ruoyi.system.mapper.CommunityNewsMapper;
import com.ruoyi.system.service.ICommentLikesService;
import com.ruoyi.system.service.ICommunityNewsService;
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.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

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

/**
 * 社区资讯点赞Service业务层处理
 *
 * @author boman
 * @date 2025-02-25
 */
@Service
public class CommentLikesServiceImpl implements ICommentLikesService {
    @Autowired
    private CommentLikesMapper commentLikesMapper;
    @Autowired
    private CommentIndexMapper commentIndexMapper;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private ICommunityNewsService iCommunityNewsService;
    @Resource
    private CommunityNewsMapper communityNewsMapper;

    /**
     * 查询社区资讯点赞
     *
     * @param likesId 社区资讯点赞主键
     * @return 社区资讯点赞
     */
    @Override
    public CommentLikes selectCommentLikesByLikesId(Long likesId) {
        return commentLikesMapper.selectCommentLikesByLikesId(likesId);
    }

    /**
     * 查询社区资讯点赞列表
     *
     * @param commentLikes 社区资讯点赞
     * @return 社区资讯点赞
     */
    @Override
    public List<CommentLikes> selectCommentLikesList(CommentLikes commentLikes) {
        return commentLikesMapper.selectCommentLikesList(commentLikes);
    }

    /**
     * 新增社区资讯点赞
     *
     * @param commentLikes 社区资讯点赞
     * @return 结果
     */
    @Override
    public int insertCommentLikes(CommentLikes commentLikes) {
        commentLikes.setCreateTime(DateUtils.getNowDate());
        return commentLikesMapper.insertCommentLikes(commentLikes);
    }

    /**
     * 修改社区资讯点赞
     *
     * @param commentLikes 社区资讯点赞
     * @return 结果
     */
    @Override
    public int updateCommentLikes(CommentLikes commentLikes) {
        commentLikes.setUpdateTime(DateUtils.getNowDate());
        return commentLikesMapper.updateCommentLikes(commentLikes);
    }

    /**
     * 批量删除社区资讯点赞
     *
     * @param likesIds 需要删除的社区资讯点赞主键
     * @return 结果
     */
    @Override
    public int deleteCommentLikesByLikesIds(Long[] likesIds) {
        return commentLikesMapper.deleteCommentLikesByLikesIds(likesIds);
    }

    /**
     * 删除社区资讯点赞信息
     *
     * @param likesId 社区资讯点赞主键
     * @return 结果
     */
    @Override
    public int deleteCommentLikesByLikesId(Long likesId) {
        return commentLikesMapper.deleteCommentLikesByLikesId(likesId);
    }

    /**
     * 进行点赞操作
     * //点赞数据存储到redis,设置redis过期key监听，继承onMessage类把数据更新到数据库中
     * //点赞目标id + 目标类型 + 用户信息组装成CommentLikes写入数据库
     * //文章需要统计点赞的数量和当前登录用户是否已经点赞
     * //点赞之前应该去查一遍该文章或者回复的点赞key,value应该是点赞的人员id判断用户是否已经点赞过了，点赞过了就取消，没点赞过就加入
     * //还需要同步到数据库，需要一个完整的点赞key 一个设置过期时间的监听key
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult giveTheThumbs(CommentLikes commentLikes) {
        String targetType = commentLikes.getTargetType();
        Long targetId = commentLikes.getTargetId();
        Long userId = commentLikes.getUserId();
        //保存点赞信息
        //根据点赞目标id' 点赞目标类型（1：资讯 2：回复） 用户id查询是否已经点赞过
        CommentLikes commentLikesOld = commentLikesMapper.selectCommentLikes(commentLikes);
        if (commentLikesOld != null) {
            commentLikesOld.setDelFlag("Y");
            commentLikesMapper.updateCommentLikes(commentLikesOld);
        } else {
            commentLikesMapper.insertCommentLikes(commentLikes);
        }
        if (StringUtils.isNotBlank(targetType)) {
            //设置未读点赞互动的方法
            setCommentInteractionVo(commentLikes);
            if (ONE.equals(targetType)) {
                // 社区资讯文章点赞的人员集合的key key = LIKE_ONE:{targetId} value = [userId,userId];
                String likeOneKey = ONE_LIKE + targetId;
                //社区资讯文章点赞的数量数据库同步的key
                String likeOneCountTimeKey = ONE_LIKE_COUNT_TIME + targetId;
                //文章永久点赞的数量key
                String likeOneCountKey = ONE_LIKE_COUNT + targetId;
                //先去查看key对应的value集合 value = 点赞人员的id集合
                List<Long> userIdListValue = redisCache.getCacheList(likeOneKey);
                //该用户点赞文章的key
                String myLikeOneKey = ONE_MY_LIKE + userId;
                List<Long> communityIdList = redisCache.getCacheList(myLikeOneKey);
                if (userIdListValue != null && userIdListValue.size() > 0) {
                    //说明该文章被点过赞
                    //判断该用户是否点过赞
                    if (userIdListValue.contains(userId)) {
                        //进行取消点赞
                        return unLike(commentLikes);
                    } else {
                        //新增点赞信息
                        return isLike(commentLikes);
                    }
                } else {
                    //该文章没有被点过赞直接新增
                    userIdListValue = new ArrayList<>();
                    userIdListValue.add(userId);
                    redisCache.setCacheList(likeOneKey, userIdListValue);
                    //给数据库同步数据在 redis中增加一个有过期时间的key 1分钟过期时间  key=like_one_count_time:{文章id}#{数量}
                    redisCache.setCacheObject(likeOneCountTimeKey + "#" + 1, 1, 1, TimeUnit.MINUTES);
                    //给该用户点赞文章的key添加值
                    communityIdList.add(targetId);
                    redisCache.setCacheList(myLikeOneKey, communityIdList);
                    //给该文章永久点赞数量的key添加值
                    redisCache.setCacheObject(likeOneCountKey, 1);
                    return AjaxResult.success();
                }
            } else {
                //对回复进行点赞
                // 社区资讯回复点赞的人员集合的key key = LIKE_ONE:{targetId} value = [userId,userId];
                String likeTwoKey = TWO_LIKE + targetId;
                //社区资讯回复点赞的数量数据库同步的key
                String likeTwoCountTimeKey = TWO_LIKE_COUNT_TIME + targetId;
                //回复永久点赞的数量key
                String likeTwoCountKey = TWO_LIKE_COUNT + targetId;
                //先去查看key对应的value集合 value = 点赞人员的id集合
                List<Long> userIdListValue = redisCache.getCacheList(likeTwoKey);
                //该用户点赞回复的key
                String myLikeTwoKey = TWO_MY_LIKE + userId;
                List<Long> communityIdList = redisCache.getCacheList(myLikeTwoKey);
                if (userIdListValue != null && userIdListValue.size() > 0) {
                    //说明该回复被点过赞
                    //判断该用户是否点过赞
                    if (userIdListValue.contains(userId)) {
                        //进行取消点赞
                        return unLike(commentLikes);
                    } else {
                        //新增点赞信息
                        return isLike(commentLikes);
                    }
                } else {
                    //该回复没有被点过赞直接新增
                    userIdListValue = new ArrayList<>();
                    userIdListValue.add(userId);
                    redisCache.setCacheList(likeTwoKey, userIdListValue);
                    //给数据库同步数据在 redis中增加一个有过期时间的key 1分钟过期时间
                    redisCache.setCacheObject(likeTwoCountTimeKey + "#" + 1, 1, 1, TimeUnit.MINUTES);
                    //给该用户点赞回复的key添加值
                    communityIdList.add(targetId);
                    redisCache.setCacheList(myLikeTwoKey, communityIdList);
                    //给该回复永久点赞数量的key添加值
                    redisCache.setCacheObject(likeTwoCountKey, 1);
                    return AjaxResult.success();
                }
            }
        }
        return AjaxResult.error("点赞失败");
    }

    /**
     * 用户点赞，但不是第一次点赞的方法
     *
     * @param commentLikes
     * @return
     */
    public AjaxResult isLike(CommentLikes commentLikes) {
        String targetType = commentLikes.getTargetType();
        Long targetId = commentLikes.getTargetId();
        Long userId = commentLikes.getUserId();
        if (ONE.equals(targetType)) {
            // 社区资讯文章点赞的人员集合的key key = ONE_LIKE:{targetId} value = [userId,userId];
            String likeOneKey = ONE_LIKE + targetId;
            //社区资讯文章点赞的数量数据库同步的key
            String likeOneCountTimeKey = ONE_LIKE_COUNT + targetId;
            //文章永久点赞的数量key
            String likeOneCountKey = ONE_LIKE_COUNT + targetId;
            //先去查看key对应的value集合 value = 点赞人员的id集合
            List<Long> userIdListValue = redisCache.getCacheList(likeOneKey);
            //该用户点赞文章的key
            String myLikeOneKey = ONE_MY_LIKE + userId;
            List<Long> communityIdList = redisCache.getCacheList(myLikeOneKey);
            //新增点赞信息
            // 新增社区资讯文章点赞的人员集合
            userIdListValue.add(userId);
            redisCache.setCacheList(likeOneKey, userIdListValue);
            //新增该用户点赞文章
            communityIdList.add(targetId);
            redisCache.setCacheList(myLikeOneKey, communityIdList);
            //新增文章永久点赞数量的key更新值
            Integer likeOneCount = redisCache.getCacheObject(likeOneCountKey);
            likeOneCount = likeOneCount + 1;
            redisCache.setCacheObject(likeOneCountKey, likeOneCount);
            //新增数据库同步数据在 redis中增加一个有过期时间的key 1分钟过期时间
            redisCache.setCacheObject(likeOneCountTimeKey + "#" + likeOneCount, likeOneCount, 1, TimeUnit.MINUTES);
            return AjaxResult.success();
        } else {
            // 社区资讯文章回复的人员集合的key key = TWO_LIKE:{targetId} value = [userId,userId];
            String likeTwoKey = TWO_LIKE + targetId;
            //社区资讯文章回复的数量数据库同步的key
            String likeTwoCountTimeKey = TWO_LIKE_COUNT_TIME + targetId;
            //文章永久回复的数量key
            String likeTwoCountKey = TWO_LIKE_COUNT + targetId;
            //先去查看key对应的value集合 value = 点赞人员的id集合
            List<Long> userIdListValue = redisCache.getCacheList(likeTwoKey);
            //该用户点赞回复的key
            String myLikeTwoKey = TWO_MY_LIKE + userId;
            List<Long> communityIdList = redisCache.getCacheList(myLikeTwoKey);
            //新增点赞信息
            // 新增社区资讯回复点赞的人员集合
            userIdListValue.add(userId);
            redisCache.setCacheList(likeTwoKey, userIdListValue);
            //新增该用户点赞回复
            communityIdList.add(targetId);
            redisCache.setCacheList(myLikeTwoKey, communityIdList);
            //新增回复永久点赞数量的key更新值
            Integer likeTwoCount = redisCache.getCacheObject(likeTwoCountKey);
            likeTwoCount = likeTwoCount + 1;
            redisCache.setCacheObject(likeTwoCountKey, likeTwoCount);
            //新增数据库同步数据在 redis中增加一个有过期时间的key 1分钟过期时间
            redisCache.setCacheObject(likeTwoCountTimeKey + "#" + likeTwoCount, likeTwoCount, 1, TimeUnit.MINUTES);
            return AjaxResult.success();
        }
    }

    /**
     * 用户取消点赞
     *
     * @param commentLikes
     * @return
     */
    public AjaxResult unLike(CommentLikes commentLikes) {
        //用户点过赞 进行取消点赞
        String targetType = commentLikes.getTargetType();
        Long targetId = commentLikes.getTargetId();
        Long userId = commentLikes.getUserId();
        if (ONE.equals(targetType)) {
            //文章永久点赞的数量key
            String likeOneCountKey = ONE_LIKE_COUNT + targetId;
            //社区资讯文章点赞的数量数据库同步的key
            String likeOneCountTimeKey = ONE_LIKE_COUNT_TIME + targetId;
            //-------------------------删除 社区资讯文章点赞的人员集合value中的userId
            //  key = ONE_LIKE:{targetId} value = [userId,userId];
            String likeOneKey = ONE_LIKE + targetId;
            //先去查看key对应的value集合
            List<Long> userIdListValue = redisCache.getCacheList(likeOneKey);
            userIdListValue.remove(userId);
            if (userIdListValue.size() == 0) {
                redisCache.deleteObject(likeOneKey);
            } else {
                redisCache.deleteObject(likeOneKey);
                // 社区资讯文章点赞的人员集合中删除该用户
                redisCache.setCacheList(likeOneKey, userIdListValue);
            }

            //-------------------------删除 该用户点赞文章value中的文章id
            String myLikeOneKey = ONE_MY_LIKE + userId;
            List<Long> communityIdListValue = redisCache.getCacheList(myLikeOneKey);
            communityIdListValue.remove(targetId);
            if (communityIdListValue.size() == 0) {
                redisCache.deleteObject(myLikeOneKey);
            } else {
                redisCache.deleteObject(myLikeOneKey);
                redisCache.setCacheList(myLikeOneKey, communityIdListValue);
            }
            // ---------点赞数量操作------------------
            //先获取永久点赞数量的值
            Integer likeCount = redisCache.getCacheObject(likeOneCountKey);
            //更新永久点赞数量
            redisCache.setCacheObject(likeOneCountKey, Math.max(likeCount - 1,0));
            //给数据库同步数据在 redis中增加一个有过期时间的key 1分钟过期时间
            redisCache.setCacheObject(likeOneCountTimeKey + "#" + likeCount, likeCount, 1, TimeUnit.MINUTES);
            return AjaxResult.success();
        } else {
            //评论的删除
            //评论永久点赞的数量key
            String likeTwoCountKey = TWO_LIKE_COUNT + targetId;
            //社区资讯评论点赞的数量数据库同步的key
            String likeTwoCountTimeKey = TWO_LIKE_COUNT_TIME + targetId;
            //-------------------------删除 社区资讯文章评论的人员集合value中的userId
            //  key = LIKE_ONE:{targetId} value = [userId,userId];
            String likeTwoKey = TWO_LIKE + targetId;
            //先去查看key对应的value集合
            List<Long> userIdListValue = redisCache.getCacheList(likeTwoKey);
            userIdListValue.remove(userId);
            if (userIdListValue.size() == 0) {
                redisCache.deleteObject(likeTwoKey);
            } else {
                redisCache.deleteObject(likeTwoKey);
                // 社区资讯文章评论的人员集合中删除该用户
                redisCache.setCacheList(likeTwoKey, userIdListValue);
            }
            //-------------------------删除 该用户点赞评论value中的文章id
            String myLikeTwoKey = TWO_MY_LIKE + userId;
            List<Long> communityIdListValue = redisCache.getCacheList(myLikeTwoKey);
            communityIdListValue.remove(targetId);
            if (communityIdListValue.size() == 0) {
                redisCache.deleteObject(myLikeTwoKey);
            } else {
                redisCache.deleteObject(myLikeTwoKey);
                redisCache.setCacheList(myLikeTwoKey, communityIdListValue);
            }
            // ---------点赞数量操作------------------
            //先获取永久点赞数量的值
            Integer likeCount = redisCache.getCacheObject(likeTwoCountKey);
            //更新永久点赞数量
            redisCache.setCacheObject(likeTwoCountKey, Math.max(likeCount - 1,0));
            //给数据库同步数据在 redis中增加一个有过期时间的key 1分钟过期时间
            redisCache.setCacheObject(likeTwoCountTimeKey + "#" + likeCount, likeCount, 1, TimeUnit.MINUTES);
            return AjaxResult.success();
        }
    }

    /**
     * 设置未读点赞互动的方法
     *
     * @param commentLikes
     */
    public void setCommentInteractionVo(CommentLikes commentLikes) {
        Long userId = commentLikes.getUserId();
        Long targetId = commentLikes.getTargetId();
        //------设置未读收藏，在redis中新增一条未读的互动--------
        CommentInteractionVo commentInteractionVo = new CommentInteractionVo();
        //先判断是资讯点赞还是回复点赞
        String targetType = commentLikes.getTargetType();
        commentInteractionVo.setTargetType(TWO);
        commentInteractionVo.setType(ONE);
        if (ONE.equals(targetType)) {
            //说明是资讯点赞
            //根据targetId获取该资讯的内容
            CommunityNews communityNews = communityNewsMapper.selectCommunityNewsByCommunityId(targetId);
            commentInteractionVo.setTargetUserId(communityNews.getUserId());
            //-------------判断是点赞还是取消点赞-------------------
            // 社区资讯文章点赞的人员集合的key key = LIKE_ONE:{targetId} value = [userId,userId];
            String likeOneKey = ONE_LIKE + targetId;
            //先去查看key对应的value集合 value = 点赞人员的id集合
            List<Long> userIdListValue = redisCache.getCacheList(likeOneKey);
            if (userIdListValue != null && userIdListValue.size() > 0) {
                //说明该文章被点过赞
                //判断该用户是否点过赞
                if (userIdListValue.contains(userId)) {
                    //设置取消点赞
                    commentInteractionVo.setType(TWO);
                }
            }
            //-------------判断是点赞还是取消点赞结束-------------------
        } else if (TWO.equals(targetType)) {
            //说明是回复点赞
            commentInteractionVo.setTargetType(FIV);
            //根据targetId获取该评论的内容
            CommentIndex commentIndex = commentIndexMapper.selectCommentIndexByCommentId(targetId);
            commentInteractionVo.setTargetUserId(commentIndex.getUserId());
            commentInteractionVo.setCommunityId(commentLikes.getCommunityId());

            //-------------判断是点赞还是取消点赞-------------------
            // 社区资讯回复点赞的人员集合的key key = LIKE_ONE:{targetId} value = [userId,userId];
            String likeTwoKey = TWO_LIKE + targetId;
            //先去查看key对应的value集合 value = 点赞人员的id集合
            List<Long> userIdListValue = redisCache.getCacheList(likeTwoKey);
            if (userIdListValue != null && userIdListValue.size() > 0) {
                //说明该回复被点过赞
                //判断该用户是否点过赞
                if (userIdListValue.contains(userId)) {
                    //设置取消点赞
                    commentInteractionVo.setType(TWO);
                }
            }
            //-------------判断是点赞还是取消点赞-------------------
        }
        commentInteractionVo.setTargetTitle(commentLikes.getTargetTitle());
        commentInteractionVo.setUserId(commentLikes.getUserId());
        commentInteractionVo.setAvatar(commentLikes.getAvatar());
        commentInteractionVo.setNickName(commentLikes.getNickName());
        commentInteractionVo.setCreateTime(DateUtils.getNowDate());
        commentInteractionVo.setTargetId(commentLikes.getTargetId());
        iCommunityNewsService.setCommentInteraction(commentInteractionVo);
        //----------------------设置未读互动完成--------
    }
}
