package com.yonge.cooleshow.bbs.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yonge.cooleshow.bbs.entity.BbsLike;
import com.yonge.cooleshow.bbs.vo.BbsLikeVo;
import com.yonge.cooleshow.bbs.dto.search.BbsLikeSearch;
import com.yonge.cooleshow.bbs.dao.BbsLikeDao;
import com.yonge.cooleshow.bbs.service.BbsLikeService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BbsLikeServiceImpl extends ServiceImpl<BbsLikeDao, BbsLike> implements BbsLikeService {
    private final static Logger log = LoggerFactory.getLogger(BbsLikeServiceImpl.class);
    private final static String LIKE = "like:";

    @Resource(name = "redis1")
    private RedisTemplate redisTemplate;

	@Override
    public BbsLikeVo detail(Long id) {
        return baseMapper.detail(id);
    }
    
     @Override
    public IPage<BbsLikeVo> selectPage(IPage<BbsLikeVo> page, BbsLikeSearch query){
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    /**
     * @Description: 点赞/取消点赞
     * @Author: cy
     * @Date: 2022/6/13
     */
    @Override
    public void dolike(Long articleId, Long userId) {
        // String key = LIKE + articleId;
        // Boolean isLike = redisTemplate.opsForSet().isMember(key, userId);
        //
        // if (isLike) {
        //     redisTemplate.opsForSet().remove(key, userId);
        // } else {
        //     redisTemplate.opsForSet().add(key, userId);
        // }

        List<BbsLike> list = this.lambdaQuery()
                                 .eq(BbsLike::getArticleId, articleId)
                                 .eq(BbsLike::getLikeUserId, userId)
                                 .list();
        if (CollectionUtils.isEmpty(list)) {
            BbsLike bbsLike = new BbsLike();
            bbsLike.setLikeUserId(userId);
            bbsLike.setArticleId(articleId);
            bbsLike.setCreatedTime(new Date());
            this.save(bbsLike);
        } else {
            this.removeByIds(list.stream().map(BbsLike::getId).collect(Collectors.toList()));
        }
    }
}