package cn.reghao.tnb.user.app.rpc;

import cn.reghao.tnb.auth.api.iface.AccountQuery;
import cn.reghao.tnb.user.api.dto.UserCard;
import cn.reghao.tnb.user.api.iface.UserService;
import cn.reghao.tnb.user.app.db.mapper.UserContactMapper;
import cn.reghao.tnb.user.app.model.vo.MyVip;
import cn.reghao.tnb.user.app.service.UserRelationService;
import cn.reghao.tnb.user.app.service.UserProfileService;
import cn.reghao.tnb.user.app.service.UserVipService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-04-12 14:16:39
 */
@DubboService
@Service
public class UserServiceImpl implements UserService {
    @DubboReference(check = false, retries = 0)
    private AccountQuery accountQuery;

    private final UserRelationService userRelationService;
    private final UserVipService userVipService;
    private final UserProfileService userProfileService;
    private final UserContactMapper userContactMapper;

    public UserServiceImpl(UserRelationService userRelationService, UserVipService userVipService,
                           UserProfileService userProfileService, UserContactMapper userContactMapper) {
        this.userRelationService = userRelationService;
        this.userVipService = userVipService;
        this.userProfileService = userProfileService;
        this.userContactMapper = userContactMapper;
    }

    @Override
    public UserCard getUserAvatar(long userId) {
        return userProfileService.getUserCard(userId);
    }

    @Override
    public List<Long> getFollowingIds(long userId) {
        return userRelationService.getFollowingCards(userId).stream()
                .map(userCard -> {
                    String userIdStr = userCard.getUserId();
                    return accountQuery.getUserIdLong(userIdStr);
                })
                .collect(Collectors.toList());
    }

    @Override
    public boolean isVip(long userId) {
        return userVipService.isVip(userId);
    }

    @Override
    public int getRecommendMode(long userId) {
        MyVip myVip = userVipService.getMyVip(userId);
        return myVip != null ? myVip.getRcmdMode() : 0;
    }

    @Override
    public boolean setRecommendMode(long userId, int mode) {
        boolean changed = true;
        MyVip myVip = userVipService.getMyVip(userId);
        if (!myVip.isVip()) {
            return false;
        }

        int currentMode = myVip.getRcmdMode();
        if (currentMode != mode) {
            userVipService.updateRcmdMode(userId, mode);
        } else {
            changed = false;
        }

        return changed;
    }

    @Override
    public boolean contactContain(long userId, long friendId) {
        return userContactMapper.findByOwnerAndFriendId(userId, friendId) != null;
    }
}
