package com.ai.da.service.impl;

import com.ai.da.common.constant.CommonConstant;
import com.ai.da.common.context.UserContext;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.UserFollowMapper;
import com.ai.da.mapper.primary.entity.UserFollow;
import com.ai.da.model.dto.GetFollowListDTO;
import com.ai.da.model.vo.AccountFollowVO;
import com.ai.da.service.UserFollowService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {

    private final MinioUtil minioUtil;

    public Long getFolloweeCount(Long accountId) {
        QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follower_id", accountId).select("followee_id");
        return baseMapper.selectCount(queryWrapper);
    }

    // 获取某个用户的关注列表 + 按名字查询
    public List<AccountFollowVO> getFolloweeList(GetFollowListDTO getFollowListDTO) {
        Long accountId = UserContext.getUserHolder().getId();
        // 1、判断是否有按用户名查询
        List<AccountFollowVO> followeeList;
        if (!StringUtil.isNullOrEmpty(getFollowListDTO.getSearchByName())) {
            followeeList = baseMapper.getFolloweeListByName(getFollowListDTO.getSearchByName(), accountId);
        } else {
            // 2、查全部 分页查询
            String order = StringUtil.isNullOrEmpty(getFollowListDTO.getOrder()) ? "DESC" : getFollowListDTO.getOrder().equals("DESC") ? "DESC" : "ASC";
            Integer limit = getFollowListDTO.getSize() > 0 ? getFollowListDTO.getSize() : 20;
            Integer offset = getFollowListDTO.getPage() > 0 ? (getFollowListDTO.getPage() - 1) * getFollowListDTO.getSize() : 0;
            followeeList = baseMapper.getFolloweeListByFollower(accountId, limit, offset, order);
        }

        if (!followeeList.isEmpty()) {
            followeeList.forEach(followee -> {
                String avatar = StringUtil.isNullOrEmpty(followee.getAvatar()) ? CommonConstant.DEFAULT_AVATAR : followee.getAvatar();
                followee.setAvatar(minioUtil.getPreSignedUrl(avatar, CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
            });
            return followeeList;
        }
        return new ArrayList<>();
    }

    public Long getFollowerCount(Long accountId) {
        QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("followee_id", accountId).select("follower_id");
        return baseMapper.selectCount(queryWrapper);
    }

    // 获取某个用户的粉丝列表 + 按名字查询 需返回是否关注该粉丝
    public List<AccountFollowVO> getFollowerList(GetFollowListDTO getFollowListDTO) {
        Long accountId = UserContext.getUserHolder().getId();

        // 获取当前用户的所有粉丝
        QueryWrapper<UserFollow> qw = new QueryWrapper<>();
        qw.eq("follower_id", accountId).select("followee_id", "create_time");
        List<UserFollow> userFollows = baseMapper.selectList(qw);
        Map<Long, LocalDateTime> followeeMap = userFollows.stream().collect(Collectors.toMap(UserFollow::getFolloweeId, UserFollow::getCreateTime));

        List<AccountFollowVO> followerList;
        // 1、判断是否有按用户名查询粉丝
        if (!StringUtil.isNullOrEmpty(getFollowListDTO.getSearchByName())) {
            followerList = baseMapper.getFollowerListByName(getFollowListDTO.getSearchByName(), accountId);
        } else {
            // 2、查全部 分页查询
            String order = StringUtil.isNullOrEmpty(getFollowListDTO.getOrder()) ? "DESC" : getFollowListDTO.getOrder().equals("DESC") ? "DESC" : "ASC";
            Integer limit = getFollowListDTO.getSize() > 0 ? getFollowListDTO.getSize() : 20;
            Integer offset = getFollowListDTO.getPage() > 0 ? (getFollowListDTO.getPage() - 1) * getFollowListDTO.getSize() : 0;
            followerList = baseMapper.getFollowerListByFollowee(accountId, limit, offset, order);
        }

        if (!followerList.isEmpty()) {
            // 判断当前用户是否与粉丝互关
            followerList.forEach(follower -> {
                String avatar = StringUtil.isNullOrEmpty(follower.getAvatar()) ? CommonConstant.DEFAULT_AVATAR : follower.getAvatar();
                follower.setAvatar(minioUtil.getPreSignedUrl(avatar, CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
                follower.setIsFollow(Objects.isNull(followeeMap.get(follower.getSenderId())) ? 0 : 1);
//                follower.setFollowTime(followeeMap.get(follower.getUserId()));
            });
            return followerList;
        }
        return new ArrayList<>();
    }

    public Integer getIfFollowed(Long followeeId, Long followerId) {
        // 设置当前用户是否关注了所查看作品的作者
        QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("followee_id", followeeId).eq("follower_id", followerId);
        UserFollow userFollow = baseMapper.selectOne(queryWrapper);
        return Objects.isNull(userFollow) ? 0 : 1;
    }

    /**
     * 获取关注列表
     *
     * @param accountId
     * @return
     */
    public List<Long> getFolloweeList(Long accountId) {
        QueryWrapper<UserFollow> qw = new QueryWrapper<>();
        qw.eq("follower_id", accountId).select("followee_id");

        List<UserFollow> userFollows = baseMapper.selectList(qw);
        return userFollows.stream().map(UserFollow::getFolloweeId).collect(Collectors.toList());
    }
}
