package com.luojia_channel.modules.interact.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luojia_channel.common.domain.UserDTO;
import com.luojia_channel.common.domain.page.PageResponse;
import com.luojia_channel.common.domain.page.ScrollPageResponse;
import com.luojia_channel.common.utils.RedisUtil;
import com.luojia_channel.common.utils.UserContext;
import com.luojia_channel.modules.interact.entity.Follow;
import com.luojia_channel.modules.interact.mapper.FollowMapper;
import com.luojia_channel.modules.interact.service.FollowService;
import com.luojia_channel.modules.post.dto.req.PostPageQueryDTO;
import com.luojia_channel.modules.post.dto.resp.PostBasicInfoDTO;
import com.luojia_channel.modules.post.entity.Post;
import com.luojia_channel.modules.post.mapper.PostMapper;
import com.luojia_channel.modules.user.entity.User;
import com.luojia_channel.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {
    private final FollowMapper followMapper;
    private final UserMapper userMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    private final RedisUtil redisUtil;
    private final PostMapper postMapper;

    @Override
    public void follow(Long followUserId, Boolean isFollow) {
        Long userId = UserContext.getUserId();
        String key = "follows:" + userId;
        if(isFollow){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            boolean isSuccess = save(follow);
            if(isSuccess){
                redisTemplate.opsForSet().add(key, followUserId);
            }
        }else{
            boolean isSuccess = followMapper.delete(userId, followUserId);
            if(isSuccess){
                redisTemplate.opsForSet().remove(key, followUserId);
            }
        }
    }

    @Override
    public boolean isFollow(Long followUserId) {
        Long userId = UserContext.getUserId();
        Integer count = followMapper.queryCount(userId, followUserId);
        return count > 0;
    }

    @Override
    public List<UserDTO> followCommons(Long id) {
        Long userId = UserContext.getUserId();
        String userKey = "follows:" + userId;
        String followKey = "follows:" + id;
        Set<Object> intersect = redisTemplate.opsForSet().intersect(userKey, followKey);
        if(intersect == null || intersect.isEmpty()){
            return Collections.emptyList();
        }

        List<Long> ids = intersect.stream().map(obj -> (Long)obj).collect(Collectors.toList());
        List<UserDTO> userDTOS = userMapper.selectBatchIds(ids).stream()
                .map(user ->  BeanUtil.copyProperties(user, UserDTO.class))
                .toList();

        return userDTOS;
    }

    @Override
    public ScrollPageResponse<PostBasicInfoDTO> queryPostFollow(PostPageQueryDTO postPageQueryDTO) {
        Long userId = UserContext.getUserId();
        String key = "post:follow_of:" + userId;
        return redisUtil.scrollPageQuery(key, PostBasicInfoDTO.class, postPageQueryDTO,
                (postIds) -> {
                    List<Post> posts = postMapper.selectBatchIds(postIds);
                    List<Long> userIds = posts.stream().map(Post::getUserId).toList();
                    List<User> users = userMapper.selectBatchIds(userIds);
                    Map<Long, User> userMap = users.stream()
                            .collect(Collectors.toMap(User::getId, user -> user));
                    List<PostBasicInfoDTO> postBasicInfoDTOS = new ArrayList<>();
                    for(Post post : posts){
                        User user = userMap.getOrDefault(post.getUserId(), new User());
                        PostBasicInfoDTO postBasicInfoDTO = BeanUtil.copyProperties(post, PostBasicInfoDTO.class);
                        postBasicInfoDTO.setUserName(user.getUsername());
                        postBasicInfoDTO.setUserAvatar(user.getAvatar());
                        postBasicInfoDTOS.add(postBasicInfoDTO);
                    }
                    // 按照发布时间倒序排序
                    postBasicInfoDTOS.sort(Comparator.comparing(PostBasicInfoDTO::getCreateTime).reversed());
                    return postBasicInfoDTOS;
                });
    }
}
