package com.ruoyi.cai.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.cai.domain.User;
import com.ruoyi.cai.domain.UserCount;
import com.ruoyi.cai.domain.UserFollow;
import com.ruoyi.cai.dto.app.query.StarQuery;
import com.ruoyi.cai.dto.app.query.StarOrVisitorReq;
import com.ruoyi.cai.dto.app.vo.user.UserBaseVo;
import com.ruoyi.cai.dto.app.vo.user.UserStarOrVisitorList;
import com.ruoyi.cai.mapper.UserFollowMapper;
import com.ruoyi.cai.notice.YunxinHttpService;
import com.ruoyi.cai.service.UserCountService;
import com.ruoyi.cai.service.UserFollowService;
import com.ruoyi.cai.service.UserMemberService;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 关注表Service业务层处理
 *
 * @author 77
 * @date 2023-12-23
 */
@RequiredArgsConstructor
@Service
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {

    @Autowired
    private UserCountService userCountService;
    @Autowired
    private UserMemberService userMemberService;
    @Autowired
    private YunxinHttpService yunxinHttpService;
    @Autowired
    private UserService userService;

    @Override
    public Long getFansNumByUserId(Long userId){
        UserCount count = userCountService.getByUserId(userId);
        return count.getFansCount();
    }

    @Override
    public boolean checkStar(Long userId,Long followUserId){
        return this.exists(Wrappers.lambdaQuery(UserFollow.class)
                .eq(UserFollow::getFollowUser, followUserId)
                .eq(UserFollow::getUserId, userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean star(StarOrVisitorReq starOrVisitorReq) {
        Long fromUserId = LoginHelper.getUserId();
        User user = userService.getById(fromUserId);
        if(user == null){
            throw new ServiceException("您的账号已被注销");
        }
        if(starOrVisitorReq.getToUserId().equals(fromUserId)){
            throw new ServiceException("不能关注自己哦");
        }
        this.remove(Wrappers.lambdaQuery(UserFollow.class)
                .eq(UserFollow::getUserId,fromUserId)
                .eq(UserFollow::getFollowUser, starOrVisitorReq.getToUserId()));
        UserFollow userFollow = new UserFollow();
        userFollow.setUserId(fromUserId);
        userFollow.setFollowUser(starOrVisitorReq.getToUserId());
        this.save(userFollow);
        userCountService.star(fromUserId, starOrVisitorReq.getToUserId());
        yunxinHttpService.followedSendMessage(starOrVisitorReq.getToUserId(), user, LocalDateTime.now());
        return true;
    }

    @Override
    public boolean unStar(StarOrVisitorReq starOrVisitorReq) {
        Long fromUserId = LoginHelper.getUserId();
        this.remove(Wrappers.lambdaQuery(UserFollow.class)
                .eq(UserFollow::getUserId,fromUserId)
                .eq(UserFollow::getFollowUser, starOrVisitorReq.getToUserId()));
        userCountService.star(fromUserId, starOrVisitorReq.getToUserId());
        return true;
    }

    @Override
    public Page<UserStarOrVisitorList> pageApp(PageQuery pageQuery, StarQuery query) {
        if(query.getType() == null){
            throw new ServiceException("参数异常");
        }
        if(query.getType() != 1 && query.getType() != 2){
            throw new ServiceException("参数异常");
        }
        query.setUserId(LoginHelper.getUserId());
        // 类型 1=查询我的关注 2=查询我的粉丝
        if(query.getType() == 1){
            return this.pageMyStarApp(pageQuery,query);
        }else{
            return this.pageMyFansApp(pageQuery,query);
        }
    }

    /**
     * 查询我的关注
     */
    private Page<UserStarOrVisitorList> pageMyStarApp(PageQuery pageQuery, StarQuery query){
        Page<UserStarOrVisitorList> page = baseMapper.pageMyStarApp(pageQuery.build(), query);
        List<UserStarOrVisitorList> records = page.getRecords();
        if(!CollectionUtils.isEmpty(records)){
            List<Long> userIds = records.stream().map(UserBaseVo::getUserId).collect(Collectors.toList());
            // 我关注的人ID
            if(!CollectionUtils.isEmpty(userIds)){
                List<UserFollow> list = this.list(Wrappers.lambdaQuery(UserFollow.class)
                        .select(UserFollow::getUserId,UserFollow::getFollowUser)
                        .in(UserFollow::getUserId, userIds)
                        .eq(UserFollow::getFollowUser, query.getUserId()));
                Set<Long> callBackUserIds = list.stream().map(UserFollow::getUserId).collect(Collectors.toSet());
                List<Long> vipUserIds = userMemberService.checkUserIsMember(userIds);
                for (UserStarOrVisitorList record : records) {
                    record.setCallBackStar(callBackUserIds.contains(record.getUserId())?1:0);
                    record.setIsVip(vipUserIds.contains(record.getUserId())?1:0);
                }
            }
        }
        return page;
    }

    /**
     * 查询我的粉丝
     */
    private Page<UserStarOrVisitorList> pageMyFansApp(PageQuery pageQuery, StarQuery query){
        Page<UserStarOrVisitorList> page = baseMapper.pageMyFansApp(pageQuery.build(), query);
        List<UserStarOrVisitorList> records = page.getRecords();
        if(!CollectionUtils.isEmpty(records)){
            // 我的粉丝ID
            List<Long> userIds = records.stream().map(UserBaseVo::getUserId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(userIds)){
                List<UserFollow> list = this.list(Wrappers.lambdaQuery(UserFollow.class)
                        .select(UserFollow::getUserId,UserFollow::getFollowUser)
                        .eq(UserFollow::getUserId, query.getUserId())
                        .in(UserFollow::getFollowUser, userIds));
                Set<Long> callBackUserIds = list.stream().map(UserFollow::getFollowUser).collect(Collectors.toSet());
                List<Long> vipUserIds = userMemberService.checkUserIsMember(userIds);
                for (UserStarOrVisitorList record : records) {
                    record.setCallBackStar(callBackUserIds.contains(record.getUserId())?1:0);
                    record.setIsVip(vipUserIds.contains(record.getUserId())?1:0);
                }
            }
        }
        return page;
    }
}
