package com.ruoyi.busi.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.member.domain.MemberUser;
import com.ruoyi.member.service.IMemberUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.busi.mapper.BusiUserLoveMapper;
import com.ruoyi.busi.domain.BusiUserLove;
import com.ruoyi.busi.service.IBusiUserLoveService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户关注Service业务层处理
 *
 * @author 朱春云
 * @date 2025-03-29
 */
@Service
public class BusiUserLoveServiceImpl extends ServiceImpl<BusiUserLoveMapper,BusiUserLove>  implements IBusiUserLoveService
{
    @Autowired
    private BusiUserLoveMapper busiUserLoveMapper;
    @Autowired
    private IMemberUserService memberUserService;

    @Override
    public IPage<BusiUserLove> queryListPage(BusiUserLove pageReqVO, Page<BusiUserLove> page) {
        return busiUserLoveMapper.queryListPage(pageReqVO, page);
    }
    /**
     * 用户关注或取消关注接口
     * @param userId 通告主id isLove 0取消关注 1 关注
     */
    @Override
    @Transactional
    public void userLoveIs(Long userId, String isLove) {
        Long nowUserId = SecurityUtils.getUserId();
        if ("0".equals(isLove)){
            //取消关注
            busiUserLoveMapper.delete(new LambdaQueryWrapper<BusiUserLove>().eq(BusiUserLove::getUserId,nowUserId).eq(BusiUserLove::getLoveUserId,userId));
        }else {
            if (busiUserLoveMapper.selectOne(new LambdaQueryWrapper<BusiUserLove>().eq(BusiUserLove::getUserId,nowUserId).eq(BusiUserLove::getLoveUserId,userId))!=null){
                //已关注
                return;
            }
            //关注
            BusiUserLove busiUserLove = new BusiUserLove();
            busiUserLove.setUserId(nowUserId);
            busiUserLove.setLoveUserId(userId);
            busiUserLove.setCreateTime(DateUtils.getNowDate());
            busiUserLove.setCreator(String.valueOf(nowUserId));
            busiUserLoveMapper.insert(busiUserLove);
        }
        LambdaQueryWrapper<BusiUserLove> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusiUserLove::getLoveUserId,userId);
        Integer loveCount = baseMapper.selectCount(queryWrapper);
        LambdaQueryWrapper<MemberUser> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(MemberUser::getUserId,userId).eq(MemberUser::getUserType,"01");
        MemberUser memberUser = memberUserService.getOne(memberWrapper);
        if (memberUser!=null){
            memberUser.setTfansNum(loveCount);
            memberUserService.updateById(memberUser);
        }
    }
}
