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.common.utils.StringUtils;
import com.ruoyi.system.domain.communityNews.CommunityNews;
import com.ruoyi.system.domain.communityNews.vo.CommentInteractionVo;
import com.ruoyi.system.mapper.CommentStarsMapper;
import com.ruoyi.system.mapper.CommunityNewsMapper;
import com.ruoyi.system.service.ICommunityNewsService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

/**
 * 社区资讯Service业务层处理
 *
 * @author boman
 * @date 2025-02-14
 */
@Service
public class CommunityNewsServiceImpl implements ICommunityNewsService {
    @Autowired
    private CommunityNewsMapper communityNewsMapper;
    @Autowired
    private CommentStarsMapper commentStarsMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询社区资讯
     *
     * @param communityId 社区资讯主键
     * @return 社区资讯
     */
    @Override
    public CommunityNews selectCommunityNewsByCommunityId(Long communityId) {
        CommunityNews communityNews = communityNewsMapper.selectCommunityNewsByCommunityId(communityId);
        communityNews.setIsStar("N");
        communityNews.setIsLike("N");
        Long userId = SecurityUtils.getUserId();
        String likeOneKey = ONE_LIKE + communityId;
        List<Long> userIdList = redisCache.getCacheList(likeOneKey);
        if (userIdList != null && userIdList.size() > 0) {
            if (userIdList.contains(userId)) {
                communityNews.setIsLike("Y");
            }
        }
        //该资讯收藏人员的key
        String starsCommunityKey = STARS_COMMUNITY + communityId;
        List<Long> userIdListStars = redisCache.getCacheList(starsCommunityKey);
        if (userIdListStars != null && userIdListStars.size() > 0) {
            //判断该用户是否收藏过
            if (userIdListStars.contains(userId)) {
                communityNews.setIsStar("Y");
            }
        }
        //查询redis中的点赞数量，收藏数量，评论数量
        Object likeCount = redisCache.getCacheObject(ONE_LIKE_COUNT + communityId);
        if (ObjectUtils.isNotEmpty(likeCount)) {
            communityNews.setUserLikes(likeCount.toString());
        }
        //收藏
        Object startCount = redisCache.getCacheObject(STARS_USER_COUNT + communityId);
        if (ObjectUtils.isNotEmpty(startCount)) {
            communityNews.setUserStars(startCount.toString());
        }
        //评论
        Object communityCommentCount = redisCache.getCacheObject(COMMUNITY_COMMENT_COUNT + communityId);
        if (ObjectUtils.isNotEmpty(communityCommentCount)) {
            communityNews.setUserComment(communityCommentCount.toString());
        }
        return communityNews;
    }

    /**
     * 查询社区资讯列表
     *
     * @param communityNews 社区资讯
     * @return 社区资讯
     */
    @Override
    public List<CommunityNews> selectCommunityNewsList(CommunityNews communityNews) {
        Long userId = SecurityUtils.getUserId();
        List<CommunityNews> communityNewsList = communityNewsMapper.selectCommunityNewsList(communityNews);
        //设置是否有未读互动
        if (communityNewsList != null && communityNewsList.size() > 0) {
            for (CommunityNews news : communityNewsList) {
                news.setIsInteraction("N");
                //key=comment_interaction_community_user_count:{userId} hkey = {community_id} value = 资讯下有多少个未读的互动(点赞，收藏，回复)
                if (redisCache.hasCacheMapKey(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + userId, news.getCommunityId().toString())) {
                    news.setIsInteraction("Y");
                }
            }
        }
        return communityNewsList;
    }

    /**
     * 新增社区资讯
     *
     * @param communityNews 社区资讯
     * @return 结果
     */
    @Override
    public int insertCommunityNews(CommunityNews communityNews) {
        communityNews.setUserId(SecurityUtils.getUserId());
        communityNews.setCreateTime(DateUtils.getNowDate());
        return communityNewsMapper.insertCommunityNews(communityNews);
    }

    /**
     * 修改社区资讯
     *
     * @param communityNews 社区资讯
     * @return 结果
     */
    @Override
    public int updateCommunityNews(CommunityNews communityNews) {
        communityNews.setUpdateTime(DateUtils.getNowDate());
        return communityNewsMapper.updateCommunityNews(communityNews);
    }

    /**
     * 批量删除社区资讯 等于把资讯关闭status = 2
     *
     * @param communityIds 需要删除的社区资讯主键
     * @return 结果
     */
    @Override
    public int deleteCommunityNewsByCommunityIds(Long[] communityIds) {
        return communityNewsMapper.updateCommunityNewsStarsByCommunityId(communityIds);
    }

    /**
     * 删除社区资讯信息
     *
     * @param communityId 社区资讯主键
     * @return 结果
     */
    @Override
    public int deleteCommunityNewsByCommunityId(Long communityId) {
        return communityNewsMapper.deleteCommunityNewsByCommunityId(communityId);
    }

    /**
     * 设置未读互动
     *
     * @return
     */
    @Override
    public void setCommentInteraction(CommentInteractionVo commentInteractionVo) {
        //把对应用户的未读互动存储到redis 还需要记录数量
        //目标用户id
        Long targetUserId = commentInteractionVo.getTargetUserId();
        String targetType = commentInteractionVo.getTargetType();
        String type = commentInteractionVo.getType();
        Long targetId = commentInteractionVo.getTargetId();
        /* 社区资讯ID 当是点赞回复的时候有值 */
        Long communityId = commentInteractionVo.getTargetId();
        //判断是否是点赞回复
        if (targetType.equals(FIV)) {
            communityId = commentInteractionVo.getCommunityId();
        }
        //-------------------获取设置用户的未读互动数量----------------
        String commentInteractionUserCountKey = COMMENT_INTERACTION_USER_COUNT + targetUserId;
        Object commentInteractionUserCount = redisCache.getCacheObject(commentInteractionUserCountKey);
        if (commentInteractionUserCount != null) {
            //判断是删除还是新增
            if (ONE.equals(type)) {
                redisCache.setCacheObject(commentInteractionUserCountKey, Integer.parseInt(commentInteractionUserCount.toString()) + 1);
            } else {
                redisCache.setCacheObject(commentInteractionUserCountKey, Math.max(Integer.parseInt(commentInteractionUserCount.toString()) - 1, 0));
            }
        } else {
            if (ONE.equals(type)) {
                redisCache.setCacheObject(commentInteractionUserCountKey, 1);
            }
        }
        //-------------------设置用户的未读互动数量结束----------------
        //-------------------设置用户的未读资讯的id和该资讯下一共有多少未读互动数量----------------
        //key=comment_interaction_community_user_count:{userId} hkey = {community_id} value = 资讯下有多少个未读的互动(点赞，收藏，回复)
        String commentInteractionCommunityUserCount = redisCache.getCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + targetUserId, communityId.toString());
        //判断是删除还是新增
        if (ONE.equals(type)) {
            //新增
            if (StringUtils.isNotBlank(commentInteractionCommunityUserCount)) {
                redisCache.setCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + targetUserId, communityId.toString(), String.valueOf(Integer.parseInt(commentInteractionCommunityUserCount) + 1));
            } else {
                redisCache.setCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + targetUserId, communityId.toString(), ONE);
            }
        } else {
            //删除
            if (StringUtils.isNotBlank(commentInteractionCommunityUserCount)) {
                int commentInteractionCommunityUserCountResult = Integer.parseInt(commentInteractionCommunityUserCount) - 1;
                if (commentInteractionCommunityUserCountResult <= 0) {
                    redisCache.deleteCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + targetUserId, communityId.toString());
                } else {
                    redisCache.setCacheMapValue(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + targetUserId, communityId.toString(), commentInteractionCommunityUserCountResult);
                }
            }
        }
        //-------------------设置用户的未读资讯的id和该资讯下一共有多少未读互动数量结束----------------
        //-------------------存储用户的未读资讯数据----------------
        String commentInteractionUserKey = COMMENT_INTERACTION_USER + targetUserId;
        Map<String, Object> commentInteractionUserMap = redisCache.getCacheMap(commentInteractionUserKey);
        //hKey={targetType:targetId}
        String hKey = targetType + ":" + targetId;
        if (ONE.equals(type)) {
            //新增/追加一条数据
            redisCache.setCacheMapValue(commentInteractionUserKey, hKey, commentInteractionVo);
        } else {
            //删除
            if (commentInteractionUserMap != null && commentInteractionUserMap.size() > 0) {
                //删除一条数据
                redisCache.deleteCacheMapValue(commentInteractionUserKey, hKey);
            }
        }
        //-------------------存储用户的未读资讯数据结束----------------
    }

    /**
     * 获取未读互动列表
     */
    @Override
    public AjaxResult getCommentInteraction(CommentInteractionVo commentInteractionVo) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> resultMap = new HashMap<>();
        String commentInteractionUserCountKey = COMMENT_INTERACTION_USER_COUNT + userId;
        Object commentInteractionUserCount = redisCache.getCacheObject(commentInteractionUserCountKey);
        int commentInteractionUserCountInt = 0;
        if (ObjectUtils.isNotEmpty(commentInteractionUserCount)) {
            commentInteractionUserCountInt = Integer.parseInt(commentInteractionUserCount.toString());
        }
        resultMap.put("total", commentInteractionUserCountInt);
        //-------------------存储用户的未读资讯数据----------------
        String commentInteractionUserKey = COMMENT_INTERACTION_USER + userId;
        Map<String, Object> commentInteractionUserMap = redisCache.getCacheMap(commentInteractionUserKey);
        List<Object> resultList = new ArrayList<>();
        if (commentInteractionUserMap != null && commentInteractionUserMap.size() > 0) {
            resultList.addAll(commentInteractionUserMap.values());
        }
        resultMap.put("list", resultList);
        //清空未读key
        redisCache.deleteObject(commentInteractionUserCountKey);
        redisCache.deleteObject(commentInteractionUserKey);
        redisCache.deleteObject(COMMENT_INTERACTION_COMMUNITY_USER_COUNT + userId);
        return AjaxResult.success(resultMap);
    }

    /**
     * 获取未读互动数量
     */
    @Override
    public AjaxResult getCommentInteractionCount(CommentInteractionVo commentInteractionVo) {
        Long userId = SecurityUtils.getUserId();
        String commentInteractionUserCountKey = COMMENT_INTERACTION_USER_COUNT + userId;
        Object commentInteractionUserCount = redisCache.getCacheObject(commentInteractionUserCountKey);
        int commentInteractionUserCountInt = 0;
        if (ObjectUtils.isNotEmpty(commentInteractionUserCount)) {
            commentInteractionUserCountInt = Integer.parseInt(commentInteractionUserCount.toString());
        }
        return AjaxResult.success(commentInteractionUserCountInt);
    }
}
