package com.quinn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quinn.common.Category;
import com.quinn.pojo.Star;
import com.quinn.mapper.StarMapper;
import com.quinn.pojo.StarWithTopic;
import com.quinn.service.StarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quinn.utils.QuinnUtils;
import com.quinn.vo.MyPageParam;
import com.quinn.vo.StarValue;
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 2022-05-08
 */
@Service
public class StarServiceImpl extends ServiceImpl<StarMapper, Star> implements StarService {

    @Resource
    StarMapper starMapper;

    @Override
    public StarValue starTopic(String topicId, String userId, Category category) {
        StarValue starValue = new StarValue();
        starValue.setStar(false);
        List<Star> list = list(new QueryWrapper<Star>()
                .eq("user_id", userId)
                .eq("topic_category",category.name())
                .eq("topic_id", topicId));
        if (!CollectionUtils.isEmpty(list)){
            list.forEach(x->{
                removeById(x);
            });
            starValue.setStar(false);
        } else {
            Star blogStar = new Star();
            blogStar.setTopicId(topicId);
            blogStar.setUserId(userId);
            blogStar.setTopicCategory(category.name());
            blogStar.setGmtCreate(QuinnUtils.getTime());
            save(blogStar);
            starValue.setStar(true);
        }
        starValue.setTotal(getTotalStar(topicId,category));
        return starValue;
    }

    @Override
    public StarValue isStar(String topicId, String userId, Category category) {
        StarValue starValue = new StarValue();
        starValue.setStar(false);
        if (!StringUtils.isEmpty(userId)){
            List<Star> stars = list(new QueryWrapper<Star>()
                    .eq("topic_category",category.name())
                    .eq("user_id", userId).eq("topic_id",topicId));
            if (!CollectionUtils.isEmpty(stars)){
                starValue.setStar(true);
            }
        }
        starValue.setTotal(getTotalStar(topicId,category));
        return starValue;
    }

    private int getTotalStar(String topicId,Category category){
        return count(new QueryWrapper<Star>()
                .eq("topic_category",category.name())
                .eq("topic_id",topicId));
    }

    @Override
    public List<StarWithTopic> listStars(String userId, MyPageParam myPageParam) {
        int count = count(new QueryWrapper<Star>().eq("user_id",userId));
        myPageParam.setTotal(count);
        return starMapper.listStars(userId,myPageParam);
    }
}
