package com.quinn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quinn.common.QuinnConstant;
import com.quinn.pojo.Blog;
import com.quinn.mapper.BlogMapper;
import com.quinn.pojo.BlogWithUser;
import com.quinn.service.BlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quinn.utils.RedisUtils;
import com.quinn.vo.MyPageParam;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author limqsh
 * @since 2020-06-29
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Resource
    BlogMapper blogMapper;
    @Resource
    RedisUtils redisUtils;

    @Override
    public List<Blog> getTopBlog(){
        List<Blog> topBlog = blogMapper.getTopBlog();
        if (!CollectionUtils.isEmpty(topBlog)){
            topBlog.forEach(x->{
                x.setContent("");
            });
        }
        return topBlog;
    }

    @Override
    public List<BlogWithUser> getBlogWithUserOrderBySort(String userId,MyPageParam myPageParam) {
        int count = blogMapper.getBlogWithUserOrderBySortCount(userId);
        myPageParam.setTotal(count);
        return blogMapper.getBlogWithUserOrderBySort(userId,myPageParam);
    }

    @Override
    public List<BlogWithUser> getMyBlogs(String userId, MyPageParam myPageParam) {
        int count = count(new QueryWrapper<Blog>().eq("author_id",userId));
        myPageParam.setTotal(count);
        return blogMapper.getMyBlogs(userId,myPageParam);
    }

    @Override
    public void addRecord(Blog blog, String sessionId) {
        String value = redisUtils.get(sessionId + blog.getBid());
        if (!QuinnConstant.SESSION_VIEW_KEY.equals(value)){
            blog.setViews(blog.getViews()+1);
            redisUtils.set(sessionId + blog.getBid(),QuinnConstant.SESSION_VIEW_KEY,QuinnConstant.SESSION_TIME_OUT);
            updateById(blog);
        }
    }

}
