package org.dromara.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.domain.communityNews.CommentStars;
import org.dromara.domain.communityNews.CommunityNews;
import org.dromara.domain.communityNews.bo.CommentStarsBo;
import org.dromara.domain.communityNews.vo.CommentInteractionVo;
import org.dromara.domain.communityNews.vo.CommentStarsVo;
import org.dromara.mapper.CommentStarsMapper;
import org.dromara.mapper.CommunityNewsMapper;
import org.dromara.service.ICommentStarsService;
import org.dromara.service.ICommunityNewsService;
import org.springframework.stereotype.Service;

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

import static org.dromara.common.core.constant.Constants.*;

/**
 * 社区资讯收藏Service业务层处理
 *
 * @author boman
 * @date 2025-04-11
 */
@RequiredArgsConstructor
@Service
public class CommentStarsServiceImpl implements ICommentStarsService {

    private final CommentStarsMapper baseMapper;
    private final CommunityNewsMapper communityNewsMapper;
    private final ICommunityNewsService communityNewsService;

    /**
     * 查询社区资讯收藏
     *
     * @param starsId 主键
     * @return 社区资讯收藏
     */
    @Override
    public CommentStarsVo queryById(Long starsId){
        return baseMapper.selectVoById(starsId);
    }

    /**
     * 分页查询社区资讯收藏列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 社区资讯收藏分页列表
     */
    @Override
    public TableDataInfo<CommentStarsVo> queryPageList(CommentStarsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CommentStars> lqw = buildQueryWrapper(bo);
        Page<CommentStarsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的社区资讯收藏列表
     *
     * @param bo 查询条件
     * @return 社区资讯收藏列表
     */
    @Override
    public List<CommentStarsVo> queryList(CommentStarsBo bo) {
        LambdaQueryWrapper<CommentStars> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CommentStars> buildQueryWrapper(CommentStarsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CommentStars> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(CommentStars::getStarsId);
        lqw.eq(bo.getTargetId() != null, CommentStars::getTargetId, bo.getTargetId());
        lqw.eq(StringUtils.isNotBlank(bo.getTargetType()), CommentStars::getTargetType, bo.getTargetType());
        lqw.eq(StringUtils.isNotBlank(bo.getTargetTitle()), CommentStars::getTargetTitle, bo.getTargetTitle());
        lqw.eq(bo.getUserId() != null, CommentStars::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), CommentStars::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), CommentStars::getAvatar, bo.getAvatar());
        return lqw;
    }

    /**
     * 新增社区资讯收藏
     *
     * @param bo 社区资讯收藏
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(CommentStarsBo bo) {
        CommentStars add = MapstructUtils.convert(bo, CommentStars.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setStarsId(add.getStarsId());
        }
        return flag;
    }

    /**
     * 修改社区资讯收藏
     *
     * @param bo 社区资讯收藏
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CommentStarsBo bo) {
        CommentStars update = MapstructUtils.convert(bo, CommentStars.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CommentStars entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除社区资讯收藏信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
    /**
     * 社区资讯收藏或取消收藏
     */
    @Override
    public R<Void> 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 = RedisUtils.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.isEmpty()) {
                    RedisUtils.deleteObject(starsCommunityKey);
                } else {
                    RedisUtils.deleteObject(starsCommunityKey);
                    RedisUtils.setCacheList(starsCommunityKey, userIdList);
                }
                //收藏数量-1
                starsCount = RedisUtils.getCacheObject(starsUserCountKey);
                RedisUtils.setCacheObject(starsUserCountKey, Math.max(starsCount - 1,0));
                commentStars.setDelFlag("Y");
                //更新数据库
                baseMapper.updateCommentStarsByUserIdAndCommunityId(commentStars);
            } else {
                //则-------收藏
                userIdList.add(userId);
                RedisUtils.setCacheList(starsCommunityKey, userIdList);
                //收藏数量+1
                starsCount = RedisUtils.getCacheObject(starsUserCountKey);
                RedisUtils.setCacheObject(starsUserCountKey, starsCount + 1);
                //收藏表新增数据
                baseMapper.insert(commentStars);
            }
        } else {
            //----------第一次有人收藏
            userIdList = new ArrayList<>();
            userIdList.add(userId);
            RedisUtils.setCacheList(starsCommunityKey, userIdList);
            starsCount = 1;
            //收藏数量+1
            RedisUtils.setCacheObject(starsUserCountKey, starsCount);
            //收藏表新增数据
            baseMapper.insert(commentStars);
        }
        //更新资讯表中数量
        communityNewsMapper.updateCommunityNewsStars(targetId, starsCount.toString());


        //------设置未读收藏，在redis中新增一条未读的互动--------
        commentInteractionVo.setTargetType(THR);
        //根据targetId获取该资讯的内容
        CommunityNews communityNews = communityNewsMapper.selectById(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());
        communityNewsService.setCommentInteraction(commentInteractionVo);
        //----------------------设置未读互动完成--------
        return R.ok();
    }
    /**
     * 党建收藏或取消收藏
     *
     * @param commentStars
     * @return
     */
    @Override
    public R<Void> getPartyNewsStars(CommentStars commentStars) {
        Long userId = commentStars.getUserId();
        //收藏或者取消收藏判断用户是否收藏过，收藏过就取消收藏
        Long targetId = commentStars.getTargetId();
        String partyKey = STARS_PARTY_NEWS + userId;
        List<Long> partyIdList = RedisUtils.getCacheList(partyKey);
        int starsCount = 0;
        Object starsPartyNewsCount = RedisUtils.getCacheObject(STARS_PARTY_NEWS_COUNT + targetId);
        if (partyIdList != null && partyIdList.size() > 0) {
            if (partyIdList.contains(targetId)) {
                //说明该党建资讯该用户收藏过     取消收藏
                partyIdList.remove(targetId);
                if (partyIdList.size() == 0) {
                    RedisUtils.deleteObject(partyKey);
                } else {
                    RedisUtils.deleteObject(partyKey);
                    RedisUtils.setCacheList(partyKey, partyIdList);
                }
                baseMapper.updateCommentStarsByUserIdAndCommunityId(commentStars);
                if (ObjectUtils.isNotEmpty(starsPartyNewsCount)) {
                    RedisUtils.setCacheObject(STARS_PARTY_NEWS_COUNT + targetId, Math.max(Integer.parseInt(starsPartyNewsCount.toString()) - 1,0));
                }
            } else {
                //则收藏
                partyIdList.add(targetId);
                RedisUtils.setCacheList(partyKey, partyIdList);
                //收藏表新增数据
                baseMapper.insert(commentStars);
                //收藏数量+1
                if (ObjectUtils.isNotEmpty(starsPartyNewsCount)) {
                    starsCount = Integer.parseInt(starsPartyNewsCount.toString()) + 1;
                    RedisUtils.setCacheObject(STARS_PARTY_NEWS_COUNT + targetId, starsCount);
                }
            }
        } else {
            partyIdList = new ArrayList<>();
            //则第一个收藏
            partyIdList.add(targetId);
            RedisUtils.setCacheList(partyKey, partyIdList);
            //收藏表新增数据
            baseMapper.insert(commentStars);
            //收藏数量+1
            RedisUtils.setCacheObject(STARS_PARTY_NEWS_COUNT + targetId, 1);

        }
        return R.ok();
    }
}
