package com.ruoyi.xq.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserStar;
import com.ruoyi.xq.dto.app.userstar.UserStarQuery;
import com.ruoyi.xq.dto.app.userstar.UserStarReq;
import com.ruoyi.xq.dto.app.userstar.vo.UserStarListVo;
import com.ruoyi.xq.mapper.UserStarMapper;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.service.UserStarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户关注Service业务层处理
 *
 * @author 77
 * @date 2024-03-17
 */
@Service
public class UserStarServiceImpl extends ServiceImpl<UserStarMapper,UserStar> implements UserStarService {
    @Autowired
    private UserService userService;
    /**
     * @Schema(description = "1-关注 2-取消关注")
     */
    @Override
    public void starUpdate(UserStarReq req) {
        User user = userService.getById(req.getUserId());
        User starUser = userService.getById(req.getStarUserId());
        if(user == null || starUser == null){
            return;
        }
        Integer star = req.getStar();
        if(star == null){
            throw new ServiceException("参数异常");
        }
        if(req.getStar().equals(1)){ // 关注
            this.remove(Wrappers.lambdaQuery(UserStar.class)
                    .eq(UserStar::getUserId, req.getUserId())
                    .eq(UserStar::getStarUserId, req.getStarUserId()));
            UserStar userStar = new UserStar();
            userStar.setUserId(user.getId());
            userStar.setUsercode(user.getUsercode());
            userStar.setStarUserId(starUser.getId());
            userStar.setStarUserCode(starUser.getUsercode());
            this.save(userStar);
        }else if(req.getStar().equals(2)){
            this.remove(Wrappers.lambdaQuery(UserStar.class)
                    .eq(UserStar::getUserId, req.getUserId())
                    .eq(UserStar::getStarUserId, req.getStarUserId()));
        }
    }

    @Override
    public Page<UserStarListVo> pageApp(PageQuery pageQuery, UserStarQuery query) {
        if(query.getQueryType() == null){
            throw new ServiceException("参数异常");
        }
        if(query.getQueryType() == 1){
            return baseMapper.selectMyStar(pageQuery.build(),query);
        }else if(query.getQueryType() == 2){
            return baseMapper.selectStarMe(pageQuery.build(),query);
        }else{
            throw new ServiceException("参数异常");
        }
    }

    @Override
    public boolean existsStar(Long userId, Long starUserId) {
        return this.exists(Wrappers.lambdaQuery(UserStar.class).eq(UserStar::getUserId, userId).eq(UserStar::getStarUserId, starUserId));
    }
}
