package com.tanpu.community.manager;

import com.tanpu.community.api.beans.qo.FollowQo;
import com.tanpu.community.api.beans.req.HomePageReq;
import com.tanpu.community.dao.entity.community.HomePageEntity;
import com.tanpu.community.service.FollowRelService;
import com.tanpu.community.service.HomePageService;
import com.tanpu.community.util.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class HomePageManager {

    @Autowired
    private FollowRelService followRelService;

    @Resource
    private HomePageService homePageService;

    public  void editUserInfo(HomePageReq req,String userId) {
        HomePageEntity entity = HomePageEntity.builder()
                .userId(userId)
                .nickName(req.getNickName())
                .headImg(req.getHeadImg())
                .introduction(req.getIntroduction())
                .sex(req.getSex())
                .location(req.getLocation())
                .build();
        if(homePageService.selectByUserId(userId) == null){
            homePageService.insert(entity);
        }else {
            homePageService.update(entity);
        }

        return;
    }

    //获取用户的关注列表
    public List<FollowQo> queryIdolsByFollowerId(String followerId) {
        List<String> idolIds = followRelService.queryFansByFollowerId(followerId);
        List<HomePageEntity> list = homePageService.selectListByUserIds(idolIds);
        return list.stream().map(ConvertUtil::homePageEntity2FollowQo).collect(Collectors.toList());
    }

    //获取用户的粉丝列表
    public List<FollowQo> queryFansByIdolId(String idolId) {
        List<String> fanIds = followRelService.queryFansByIdolId(idolId);
        List<HomePageEntity> list = homePageService.selectListByUserIds(fanIds);
        return list.stream().map(ConvertUtil::homePageEntity2FollowQo).collect(Collectors.toList());
    }

    //判断返回列表中的用户是否被当前用户关注
    public List<FollowQo> judgeFollowed(List<FollowQo> followQos,String followerId){
        Set<String> idolSet = followRelService.queryFansByFollowerId(followerId).stream().collect(Collectors.toSet());
        return followQos.stream().map(o->{
            if (idolSet.contains(o.getUserId())){
                o.setFollowed(true);
            }
            return o;
        }).collect(Collectors.toList());

    }

    public void addIdol(String idolId, String followerId) {
        followRelService.addFans(idolId, followerId);
    }
}