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.system.domain.communityNews.CommentStars;
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.ICommentStarsService;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

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

/**
 * 社区资讯收藏Service业务层处理
 *
 * @author boman
 * @date 2025-02-25
 */
@Service
public class CommentStarsServiceImpl implements ICommentStarsService {
    @Autowired
    private CommentStarsMapper commentStarsMapper;
    @Autowired
    private CommunityNewsMapper communityNewsMapper;
    @Resource
    private RedisCache redisCache;

    @Resource
    private ICommunityNewsService iCommunityNewsService;

    /**
     * 查询社区资讯收藏
     *
     * @param starsId 社区资讯收藏主键
     * @return 社区资讯收藏
     */
    @Override
    public CommentStars selectCommentStarsByStarsId(Long starsId) {
        return commentStarsMapper.selectCommentStarsByStarsId(starsId);
    }

    /**
     * 查询社区资讯收藏列表
     *
     * @param commentStars 社区资讯收藏
     * @return 社区资讯收藏
     */
    @Override
    public List<CommentStars> selectCommentStarsList(CommentStars commentStars) {
        return commentStarsMapper.selectCommentStarsList(commentStars);
    }

    /**
     * 新增社区资讯收藏
     *
     * @param commentStars 社区资讯收藏
     * @return 结果
     */
    @Override
    public int insertCommentStars(CommentStars commentStars) {
        return commentStarsMapper.insertCommentStars(commentStars);
    }

    /**
     * 修改社区资讯收藏
     *
     * @param commentStars 社区资讯收藏
     * @return 结果
     */
    @Override
    public int updateCommentStars(CommentStars commentStars) {
        commentStars.setUpdateTime(DateUtils.getNowDate());
        return commentStarsMapper.updateCommentStars(commentStars);
    }

    /**
     * 批量删除社区资讯收藏
     *
     * @param starsIds 需要删除的社区资讯收藏主键
     * @return 结果
     */
    @Override
    public int deleteCommentStarsByStarsIds(Long[] starsIds) {
        return commentStarsMapper.deleteCommentStarsByStarsIds(starsIds);
    }

    /**
     * 删除社区资讯收藏信息
     *
     * @param starsId 社区资讯收藏主键
     * @return 结果
     */
    @Override
    public int deleteCommentStarsByStarsId(Long starsId) {
        return commentStarsMapper.deleteCommentStarsByStarsId(starsId);
    }

    /**
     * 社区资讯收藏或取消收藏
     */
    @Override
    public AjaxResult getStars(CommentStars commentStars) {
        //当有人收藏了，需要记录到redis作为未读信息，需要统计未读的总数，需要在文章列表也给对应是否有未读标识
        Long userId = commentStars.getUserId();
        //收藏或者取消收藏判断用户是否收藏过，收藏过就取消收藏
        Long targetId = commentStars.getTargetId();
        String starsCommunityKey = STARS_COMMUNITY + targetId;
        //该资讯收藏数量的key
        String starsUserCountKey = STARS_USER_COUNT + targetId;
        List<Long> userIdList = redisCache.getCacheList(starsCommunityKey);
        Integer starsCount = 0;
        CommentInteractionVo commentInteractionVo = new CommentInteractionVo();
        commentInteractionVo.setType(ONE);
        if (userIdList != null && userIdList.size() > 0) {
            //判断该用户是否收藏过
            if (userIdList.contains(userId)) {
                commentInteractionVo.setType(TWO);
                //说明收藏过则-----取消收藏
                userIdList.remove(userId);
                if (userIdList.size() == 0) {
                    redisCache.deleteObject(starsCommunityKey);
                } else {
                    redisCache.deleteObject(starsCommunityKey);
                    redisCache.setCacheList(starsCommunityKey, userIdList);
                }
                //收藏数量-1
                starsCount = redisCache.getCacheObject(starsUserCountKey);
                redisCache.setCacheObject(starsUserCountKey, Math.max(starsCount - 1,0));
                commentStars.setDelFlag("Y");
                //更新数据库
                commentStarsMapper.updateCommentStarsByUserIdAndCommunityId(commentStars);
            } else {
                //则-------收藏
                userIdList.add(userId);
                redisCache.setCacheList(starsCommunityKey, userIdList);
                //收藏数量+1
                starsCount = redisCache.getCacheObject(starsUserCountKey);
                redisCache.setCacheObject(starsUserCountKey, starsCount + 1);
                //收藏表新增数据
                commentStarsMapper.insertCommentStars(commentStars);
            }
        } else {
            //----------第一次有人收藏
            userIdList = new ArrayList<>();
            userIdList.add(userId);
            redisCache.setCacheList(starsCommunityKey, userIdList);
            starsCount = 1;
            //收藏数量+1
            redisCache.setCacheObject(starsUserCountKey, starsCount);
            //收藏表新增数据
            commentStarsMapper.insertCommentStars(commentStars);
        }
        //更新资讯表中数量
        communityNewsMapper.updateCommunityNewsStars(targetId, starsCount.toString());


        //------设置未读收藏，在redis中新增一条未读的互动--------
        commentInteractionVo.setTargetType(THR);
        //根据targetId获取该资讯的内容
        CommunityNews communityNews = communityNewsMapper.selectCommunityNewsByCommunityId(targetId);
        commentInteractionVo.setTargetUserId(communityNews.getUserId());
        commentInteractionVo.setTargetTitle(commentStars.getTargetTitle());
        commentInteractionVo.setUserId(userId);
        commentInteractionVo.setAvatar(commentStars.getAvatar());
        commentInteractionVo.setNickName(commentStars.getNickName());
        commentInteractionVo.setCreateTime(DateUtils.getNowDate());
        commentInteractionVo.setTargetId(commentStars.getTargetId());
        iCommunityNewsService.setCommentInteraction(commentInteractionVo);
        //----------------------设置未读互动完成--------
        return AjaxResult.success();
    }

    /**
     * 党建收藏或取消收藏
     *
     * @param commentStars
     * @return
     */
    @Override
    public AjaxResult getPartyNewsStars(CommentStars commentStars) {
        Long userId = commentStars.getUserId();
        //收藏或者取消收藏判断用户是否收藏过，收藏过就取消收藏
        Long targetId = commentStars.getTargetId();
        String partyKey = STARS_PARTY_NEWS + userId;
        List<Long> partyIdList = redisCache.getCacheList(partyKey);
        int starsCount = 0;
        Object starsPartyNewsCount = redisCache.getCacheObject(STARS_PARTY_NEWS_COUNT + targetId);
        if (partyIdList != null && partyIdList.size() > 0) {
            if (partyIdList.contains(targetId)) {
                //说明该党建资讯该用户收藏过     取消收藏
                partyIdList.remove(targetId);
                if (partyIdList.size() == 0) {
                    redisCache.deleteObject(partyKey);
                } else {
                    redisCache.deleteObject(partyKey);
                    redisCache.setCacheList(partyKey, partyIdList);
                }
                commentStarsMapper.updateCommentStarsByUserIdAndCommunityId(commentStars);
                if (ObjectUtils.isNotEmpty(starsPartyNewsCount)) {
                    redisCache.setCacheObject(STARS_PARTY_NEWS_COUNT + targetId, Math.max(Integer.parseInt(starsPartyNewsCount.toString()) - 1,0));
                }
            } else {
                //则收藏
                partyIdList.add(targetId);
                redisCache.setCacheList(partyKey, partyIdList);
                //收藏表新增数据
                commentStarsMapper.insertCommentStars(commentStars);
                //收藏数量+1
                if (ObjectUtils.isNotEmpty(starsPartyNewsCount)) {
                    starsCount = Integer.parseInt(starsPartyNewsCount.toString()) + 1;
                    redisCache.setCacheObject(STARS_PARTY_NEWS_COUNT + targetId, starsCount);
                }
            }
        } else {
            partyIdList = new ArrayList<>();
            //则第一个收藏
            partyIdList.add(targetId);
            redisCache.setCacheList(partyKey, partyIdList);
            //收藏表新增数据
            commentStarsMapper.insertCommentStars(commentStars);
            //收藏数量+1
            redisCache.setCacheObject(STARS_PARTY_NEWS_COUNT + targetId, 1);

        }
        return AjaxResult.success();
    }
}
