package com.fs.course.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.course.mapper.FsUserVideoCommentLikeMapper;
import com.fs.course.param.FsUserVideoCommentAddUParam;
import com.fs.course.param.FsUserVideoCommentDelUParam;
import com.fs.course.param.FsUserVideoCommentUParam;
import com.fs.course.service.IFsUserVideoCommentLikeService;
import com.fs.course.vo.FsUserVideoCommentListUVO;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.fs.course.mapper.FsUserVideoCommentMapper;
import com.fs.course.domain.FsUserVideoComment;
import com.fs.course.service.IFsUserVideoCommentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 课堂视频评论Service业务层处理
 *
 * @author fs
 * @date 2024-05-15
 */
@Service
public class FsUserVideoCommentServiceImpl implements IFsUserVideoCommentService
{
    @Autowired
    private FsUserVideoCommentMapper fsUserVideoCommentMapper;

    @Autowired
    private FsUserVideoCommentLikeMapper fsUserVideoCommentLikeMapper;

    @Autowired
    private IFsUserVideoCommentLikeService videoCommentLikeService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private FsUserMapper fsUserMapper;

    private static final String COMMENT_LIST_KEY_PREFIX = "comment:list:video:";
    private static final String COMMENT_HASH_KEY_PREFIX = "comment:hash:video:";
    private static final String REPLY_LIST_KEY_PREFIX = "reply:list:comment:";
    private static final String REPLY_HASH_KEY_PREFIX = "reply:hash:comment:";
    private static final String COMMENT_KEY_PREFIX = "comment:video:";
    private static final String COMMENT_CODE_INDEX_KEY_PREFIX = "comment:index:";
    private static final String REPLY_KEY_PREFIX = "reply:comment:";
    private static final String COMMENT_LIKE_KEY_PREFIX = "like:comment:";
    private static final String COMMENT_LIKE_COUNT_KEY_PREFIX = "likecount:comment:";
    private static final String COMMENT_REPLY_COUNT_KEY_PREFIX = "reply:count:comment:";
    private static final String VIDEO_COMMENT_COUNT_KEY_PREFIX = "comment:count:video:";

    /**
     * 查询课堂视频评论
     *
     * @param commentId 课堂视频评论主键
     * @return 课堂视频评论
     */
    @Override
    public FsUserVideoComment selectFsUserVideoCommentByCommentId(Long commentId)
    {
        return fsUserVideoCommentMapper.selectFsUserVideoCommentByCommentId(commentId);
    }

    /**
     * 查询课堂视频评论列表
     *
     * @param fsUserVideoComment 课堂视频评论
     * @return 课堂视频评论
     */
    @Override
    public List<FsUserVideoComment> selectFsUserVideoCommentList(FsUserVideoComment fsUserVideoComment)
    {
        return fsUserVideoCommentMapper.selectFsUserVideoCommentList(fsUserVideoComment);
    }

    /**
     * 新增课堂视频评论
     *
     * @param fsUserVideoComment 课堂视频评论
     * @return 结果
     */
    @Override
    public int insertFsUserVideoComment(FsUserVideoComment fsUserVideoComment)
    {
        fsUserVideoComment.setCreateTime(DateUtils.getNowDate());
        return fsUserVideoCommentMapper.insertFsUserVideoComment(fsUserVideoComment);
    }

    /**
     * 修改课堂视频评论
     *
     * @param fsUserVideoComment 课堂视频评论
     * @return 结果
     */
    @Override
    public int updateFsUserVideoComment(FsUserVideoComment fsUserVideoComment)
    {
        fsUserVideoComment.setUpdateTime(DateUtils.getNowDate());
        return fsUserVideoCommentMapper.updateFsUserVideoComment(fsUserVideoComment);
    }

    /**
     * 批量删除课堂视频评论
     *
     * @param commentIds 需要删除的课堂视频评论主键
     * @return 结果
     */
    @Override
    public int deleteFsUserVideoCommentByCommentIds(Long[] commentIds)
    {
        return fsUserVideoCommentMapper.deleteFsUserVideoCommentByCommentIds(commentIds);
    }

    /**
     * 删除课堂视频评论信息
     *
     * @param commentId 课堂视频评论主键
     * @return 结果
     */
    @Override
    public int deleteFsUserVideoCommentByCommentId(Long commentId)
    {
        return fsUserVideoCommentMapper.deleteFsUserVideoCommentByCommentId(commentId);
    }

//    @Override
//    @Transactional
//    public R addComment(FsUserVideoCommentAddUParam param) {
//        FsUserVideoComment comment = new FsUserVideoComment();
//        BeanUtils.copyProperties(param, comment);
//        comment.setCreateTime(new Date());
//        String uniqueCode = UUID.randomUUID().toString();
//        comment.setCommentCode(uniqueCode);
//        comment.setSynced(false); // 设置同步标志
//        // 存入Redis
//        String listKey;
//        String hashKey;
//        if (param.getParentId() == null) {
//            // 这是一个评论
//            listKey = COMMENT_LIST_KEY_PREFIX + param.getVideoId();
//            hashKey = COMMENT_HASH_KEY_PREFIX + param.getVideoId();
//        } else {
//            // 这是一个回复
//            listKey = REPLY_LIST_KEY_PREFIX + param.getParentId();
//            hashKey = REPLY_HASH_KEY_PREFIX + param.getParentId();
//            comment.setParentId(param.getParentId());
//            // 增加父评论的回复数
//            String parentCommentKey = COMMENT_REPLY_COUNT_KEY_PREFIX + param.getParentId();
//            // 检查并初始化父评论的回复数
//            if (redisTemplate.opsForValue().get(parentCommentKey) == null) {
//                redisTemplate.opsForValue().set(parentCommentKey, 0);
//            }
//            redisTemplate.opsForValue().increment(parentCommentKey, 1);
//        }
//        // 存入Hash表
//        redisTemplate.opsForHash().put(hashKey, uniqueCode, comment);
//        // 存入列表，保持顺序
//        redisTemplate.opsForList().rightPush(listKey, uniqueCode);
//        redisTemplate.expire(listKey, 1, TimeUnit.DAYS);
//        redisTemplate.expire(hashKey, 1, TimeUnit.DAYS);
//
//        // 增加视频的评论数
//        String videoCommentCountKey = VIDEO_COMMENT_COUNT_KEY_PREFIX + param.getVideoId();
//        if (redisTemplate.opsForValue().get(videoCommentCountKey) == null) {
//            redisTemplate.opsForValue().set(videoCommentCountKey, 0);
//        }
//        redisTemplate.opsForValue().increment(videoCommentCountKey, 1);
//        return R.ok().put("data", comment);
//    }


    @Override
    public R addComment(FsUserVideoCommentAddUParam param) {
        FsUserVideoComment comment = new FsUserVideoComment();
        BeanUtils.copyProperties(param, comment);
        comment.setCreateTime(new Date());
        String uniqueCode = UUID.randomUUID().toString();
        comment.setCommentCode(uniqueCode);
        if (param.getParentId()!=null) {
            comment.setParentId(param.getParentId());
        }
        if (fsUserVideoCommentMapper.insertFsUserVideoComment(comment)>0){
            return R.ok().put("data",comment);
        };
        return R.error("新增评论失败");
    }

//    @Override
//    public List<FsUserVideoCommentListUVO> getComments(FsUserVideoCommentUParam param) {
//        String listKey = COMMENT_LIST_KEY_PREFIX + param.getVideoId();
//        String hashKey = COMMENT_HASH_KEY_PREFIX + param.getVideoId();
//        Long start = (param.getPageNum() - 1L) * param.getPageSize();
//        Long end = start + param.getPageSize() - 1;
//
//        List<FsUserVideoCommentListUVO> comments = new ArrayList<>();
//        List<Object> commentCodes = redisTemplate.opsForList().range(listKey, start, end);
//
//        if (commentCodes == null || commentCodes.isEmpty()) {
//            comments = fsUserVideoCommentMapper.selectFsUserVideoCommentListByVideoId(param.getVideoId());
//            if (comments != null && !comments.isEmpty()) {
//                for (FsUserVideoCommentListUVO comment : comments) {
//                    FsUserVideoComment commentEntity = convertToEntity(comment);
//                    commentEntity.setSynced(true); // 标记为已同步
//                    redisTemplate.opsForHash().put(hashKey, comment.getCommentCode(), commentEntity);
//                    redisTemplate.opsForList().rightPush(listKey, comment.getCommentCode());
//                }
//                redisTemplate.expire(listKey, 1, TimeUnit.DAYS);
//                redisTemplate.expire(hashKey, 1, TimeUnit.DAYS);
//            }
//        } else {
//            List<Object> commentsFromRedis = redisTemplate.opsForHash().multiGet(hashKey, commentCodes);
//            comments = commentsFromRedis.stream()
//                    .filter(obj -> obj instanceof FsUserVideoComment)
//                    .map(obj -> (FsUserVideoComment) obj)
//                    .map(this::convertToUVO)
//                    .collect(Collectors.toList());
//        }
//
//
//        if (param.getUserId() != null) {
//            Long userId = param.getUserId();
//            List<String> codes = comments.stream().map(FsUserVideoCommentListUVO::getCommentCode).collect(Collectors.toList());
//            // 批量查询Redis中的点赞信息
//            List<String> likeKeys = codes.stream()
//                    .map(commentCode -> COMMENT_LIKE_KEY_PREFIX + commentCode + ":user:" + userId)
//                    .collect(Collectors.toList());
//            List<Object> redisLikesObjects = redisTemplate.opsForValue().multiGet(likeKeys);
//            List<Boolean> redisLikes = redisLikesObjects.stream()
//                    .map(obj -> obj != null && (Boolean) obj)
//                    .collect(Collectors.toList());
//
//            // 设置点赞信息
//            for (int i = 0; i < comments.size(); i++) {
//                FsUserVideoCommentListUVO comment = comments.get(i);
//                String commentCode = comment.getCommentCode();
//                if (i < redisLikes.size() && redisLikes.get(i) != null) {
//                    comment.setLiked(redisLikes.get(i) ? 1 : 0);
//                } else {
//                    boolean isLiked = videoCommentLikeService.isCommentLiked(commentCode, userId);
//                    comment.setLiked(isLiked ? 1 : 0);
//                }
//
//                // 查询并设置点赞数
//                String likeCountKey = COMMENT_LIKE_COUNT_KEY_PREFIX + commentCode;
//                Object likeCountObj = redisTemplate.opsForValue().get(likeCountKey);
//                Long likeCount;
//                if (likeCountObj instanceof Integer) {
//                    likeCount = ((Integer) likeCountObj).longValue();
//                } else if (likeCountObj instanceof Long) {
//                    likeCount = (Long) likeCountObj;
//                } else {
//                    likeCount = fsUserVideoCommentLikeMapper.getCommentLikeCount(commentCode).longValue();
//                    redisTemplate.opsForValue().set(likeCountKey, likeCount, 1, TimeUnit.DAYS);
//                }
//                comment.setLikes(likeCount);
//
//                // 查询并设置回复数
//                String replyCountKey = COMMENT_REPLY_COUNT_KEY_PREFIX + commentCode;
//                Object replyCountObj = redisTemplate.opsForValue().get(replyCountKey);
//                Long replyCount;
//                if (replyCountObj instanceof Integer) {
//                    replyCount = ((Integer) replyCountObj).longValue();
//                } else if (replyCountObj instanceof Long) {
//                    replyCount = (Long) replyCountObj;
//                } else {
//                    replyCount = fsUserVideoCommentMapper.getCommentReplyCount(commentCode).longValue();
//                    redisTemplate.opsForValue().set(replyCountKey, replyCount, 1, TimeUnit.DAYS);
//                }
//                comment.setReplyCount(replyCount);
//            }
//        }
//
//        addUserDetailsToComments(comments);
//        return comments;
//    }
    @Override
    public List<FsUserVideoCommentListUVO> getComments(FsUserVideoCommentUParam param){
        List<FsUserVideoCommentListUVO> comments =fsUserVideoCommentMapper.selectFsUserVideoCommentListByVideoId(param.getVideoId());
        if (param.getUserId() != null) {
            Long userId = param.getUserId();
            List<Long> commentIds = comments.stream().map(FsUserVideoCommentListUVO::getCommentId).collect(Collectors.toList());
            // 批量查询Redis中的点赞信息
            List<String> likeKeys = commentIds.stream()
                    .map(commentId -> COMMENT_LIKE_KEY_PREFIX + commentId + ":user:" + userId)
                    .collect(Collectors.toList());
            List<Object> redisLikesObjects = redisTemplate.opsForValue().multiGet(likeKeys);
            List<Boolean> redisLikes = redisLikesObjects.stream()
                    .map(obj -> obj != null && (Boolean) obj)
                    .collect(Collectors.toList());

            // 设置点赞信息
            for (int i = 0; i < comments.size(); i++) {
                FsUserVideoCommentListUVO comment = comments.get(i);
                Long commentId = comment.getCommentId();
                if (i < redisLikes.size() && redisLikes.get(i) != null) {
                    comment.setLiked(redisLikes.get(i) ? 1 : 0);
                } else {
                    boolean isLiked = videoCommentLikeService.isCommentLiked(commentId.toString(), userId);
                    comment.setLiked(isLiked ? 1 : 0);
                }

            }
        }
        for (FsUserVideoCommentListUVO vo : comments){
            Long commentId = vo.getCommentId();
            // 查询并设置点赞数
            String likeCountKey = COMMENT_LIKE_COUNT_KEY_PREFIX + commentId;
            Object likeCountObj = redisTemplate.opsForValue().get(likeCountKey);
            Integer likeCount;
            if (likeCountObj instanceof Integer) {
                likeCount = (Integer) likeCountObj;
            }  else {
                likeCount = fsUserVideoCommentLikeMapper.getCommentLikeCount(commentId.toString());
                redisTemplate.opsForValue().set(likeCountKey, likeCount, 1, TimeUnit.DAYS);
            }
            vo.setLikes(likeCount.longValue());

            // 查询并设置回复数
            Long replyCount = fsUserVideoCommentMapper.getCommentReplyCount(commentId.toString());
            vo.setReplyCount(replyCount);
        }
        return comments;
    }

    @Override
    public List<FsUserVideoCommentListUVO> getReplies(FsUserVideoCommentUParam param){
        List<FsUserVideoCommentListUVO> replies = fsUserVideoCommentMapper.selectFsUserVideoCommentListByParentId(param.getParentId());
        if (param.getUserId() != null) {
            Long userId = param.getUserId();
            List<Long> commentIds = replies.stream().map(FsUserVideoCommentListUVO::getCommentId).collect(Collectors.toList());

            // 批量查询Redis中的点赞信息
            List<String> likeKeys = commentIds.stream()
                    .map(commentId -> COMMENT_LIKE_KEY_PREFIX + commentId + ":user:" + userId)
                    .collect(Collectors.toList());
            List<Object> redisLikesObjects = redisTemplate.opsForValue().multiGet(likeKeys);
            List<Boolean> redisLikes = redisLikesObjects.stream()
                    .map(obj -> obj != null && (Boolean) obj)
                    .collect(Collectors.toList());

            // 设置点赞信息
            for (int i = 0; i < replies.size(); i++) {
                FsUserVideoCommentListUVO reply = replies.get(i);
                String commentId = reply.getCommentId().toString();
                if (i < redisLikes.size()&&redisLikes.get(i) != null) {
                    reply.setLiked(redisLikes.get(i) ? 1 : 0);
                } else {
                    boolean isLiked =videoCommentLikeService.isCommentLiked(commentId, userId);
                    reply.setLiked(isLiked ? 1 : 0);
                }

            }
        }
        for (FsUserVideoCommentListUVO vo : replies){
            Long commentId = vo.getCommentId();
            // 查询并设置点赞数
            String likeCountKey = COMMENT_LIKE_COUNT_KEY_PREFIX + commentId;
            Object likeCountObj = redisTemplate.opsForValue().get(likeCountKey);
            Integer likeCount;
            if (likeCountObj instanceof Integer) {
                likeCount = (Integer) likeCountObj;
            }  else {
                likeCount = fsUserVideoCommentLikeMapper.getCommentLikeCount(commentId.toString());
                redisTemplate.opsForValue().set(likeCountKey, likeCount, 1, TimeUnit.DAYS);
            }
            vo.setLikes(likeCount.longValue());
        }
        return replies;
    }

//    @Override
//    public List<FsUserVideoCommentListUVO> getReplies(FsUserVideoCommentUParam param) {
//        String listKey = REPLY_LIST_KEY_PREFIX + param.getParentId();
//        String hashKey = REPLY_HASH_KEY_PREFIX + param.getParentId();
//
//        Long start = (param.getPageNum() - 1L) * param.getPageSize();
//        Long end = start + param.getPageSize() - 1;
//
//        List<FsUserVideoCommentListUVO> replies = new ArrayList<>();
//        List<Object> commentCodes = redisTemplate.opsForList().range(listKey, start, end);
//
//        if (commentCodes == null || commentCodes.isEmpty()) {
//            replies = fsUserVideoCommentMapper.selectFsUserVideoCommentListByParentId(param.getParentId());
//            if (replies != null && !replies.isEmpty()) {
//                for (FsUserVideoCommentListUVO comment : replies) {
//                    redisTemplate.opsForHash().put(hashKey, comment.getCommentCode(), comment);
//                    redisTemplate.opsForList().rightPush(listKey, comment.getCommentCode());
//                }
//                redisTemplate.expire(listKey, 1, TimeUnit.DAYS);
//                redisTemplate.expire(hashKey, 1, TimeUnit.DAYS);
//            }
//        } else {
//            List<Object> repliesFromRedis = redisTemplate.opsForHash().multiGet(hashKey, commentCodes);
//            replies = repliesFromRedis.stream()
//                    .filter(obj -> obj instanceof FsUserVideoComment)
//                    .map(obj -> (FsUserVideoComment) obj)
//                    .map(this::convertToUVO)
//                    .collect(Collectors.toList());
//        }
//
//        if (param.getUserId() != null) {
//            Long userId = param.getUserId();
//            List<String> codes = replies.stream().map(FsUserVideoCommentListUVO::getCommentCode).collect(Collectors.toList());
//
//            // 批量查询Redis中的点赞信息
//            List<String> likeKeys = codes.stream()
//                    .map(commentCode -> COMMENT_LIKE_KEY_PREFIX + commentCode + ":user:" + userId)
//                    .collect(Collectors.toList());
//            List<Object> redisLikesObjects = redisTemplate.opsForValue().multiGet(likeKeys);
//            List<Boolean> redisLikes = redisLikesObjects.stream()
//                    .map(obj -> obj != null && (Boolean) obj)
//                    .collect(Collectors.toList());
//
//            // 设置点赞信息
//            for (int i = 0; i < replies.size(); i++) {
//                FsUserVideoCommentListUVO reply = replies.get(i);
//                String commentCode = reply.getCommentCode();
//                if (i < redisLikes.size()&&redisLikes.get(i) != null) {
//                    reply.setLiked(redisLikes.get(i) ? 1 : 0);
//                } else {
//                    boolean isLiked =videoCommentLikeService.isCommentLiked(commentCode, userId);
//                    reply.setLiked(isLiked ? 1 : 0);
//                }
//                // 查询并设置点赞数
//                String likeCountKey = COMMENT_LIKE_COUNT_KEY_PREFIX + commentCode;
//                Long likeCount = (Long) redisTemplate.opsForValue().get(likeCountKey);
//                if (likeCount == null) {
//                    likeCount = fsUserVideoCommentLikeMapper.getCommentLikeCount(commentCode);
//                    redisTemplate.opsForValue().set(likeCountKey, likeCount, 1, TimeUnit.DAYS);
//                }
//                reply.setLikes(likeCount);
//            }
//        }
//        addUserDetailsToComments(replies);
//        return replies;
//    }

    private void addUserDetailsToComments(List<FsUserVideoCommentListUVO> comments) {
        if (CollectionUtils.isNotEmpty(comments)) {
            List<Long> userIds = comments.stream().map(FsUserVideoCommentListUVO::getUserId).collect(Collectors.toList());
            List<FsUser> users = fsUserMapper.findUsersByIds(userIds);
            Map<Long, FsUser> userMap = users.stream().collect(Collectors.toMap(FsUser::getUserId, user -> user));
            for (FsUserVideoCommentListUVO comment : comments) {
                FsUser user = userMap.get(comment.getUserId());
                if (user != null) {
                    comment.setNickName(user.getNickName());
                    comment.setAvatar(user.getAvatar());
                }
            }
        }
    }

    private FsUserVideoCommentListUVO convertToUVO(FsUserVideoComment comment) {
        FsUserVideoCommentListUVO uvo = new FsUserVideoCommentListUVO();
        BeanUtils.copyProperties(comment, uvo);
        return uvo;
    }

    private FsUserVideoComment convertToEntity(FsUserVideoCommentListUVO uvo) {
        FsUserVideoComment comment = new FsUserVideoComment();
        BeanUtils.copyProperties(uvo, comment);
        return comment;
    }

//    @Override
//    public int updateLikes(String commentCode, Integer type) {
//        if (type == 1){
//            return fsUserVideoCommentMapper.addLikes(commentCode);
//        }else {
//            return fsUserVideoCommentMapper.minusLikes(commentCode);
//        }
//    }

    @Override
    @Transactional
    public R delComment(FsUserVideoCommentDelUParam param) {
        // 更新评论数
        if (param.getParentId() == null) {
            //除数据库中的回复
            fsUserVideoCommentMapper.deleteByParentId(param.getCommentId().toString());
        }
        fsUserVideoCommentMapper.deleteByCommentId(param.getCommentId());
        return R.ok();
    }

    private int deleteReplies(String parentCommentCode) {
        String listKey = REPLY_LIST_KEY_PREFIX + parentCommentCode;
        String hashKey = REPLY_HASH_KEY_PREFIX + parentCommentCode;

        // 获取所有回复ID
        List<Object> replyCodes = redisTemplate.opsForList().range(listKey, 0, -1);
        if (replyCodes == null || replyCodes.isEmpty()) {
            return 0;
        }

        // 从Hash表中移除所有回复
        redisTemplate.opsForHash().delete(hashKey, replyCodes.toArray());

        int totalDeletedReplies = replyCodes.size();

        // 递归删除每个回复的子回复
        for (Object replyCode : replyCodes) {
            totalDeletedReplies+=deleteReplies((String)replyCode);
        }

        // 从列表中移除所有回复ID
        redisTemplate.delete(listKey);
        redisTemplate.delete(hashKey);
        return totalDeletedReplies;
    }

    @Override
    @Transactional
    public void syncCommentsToDatabase() {
        // 获取所有视频的评论列表键
        Set<String> commentListKeys = redisTemplate.keys(COMMENT_LIST_KEY_PREFIX + "*");

        if (commentListKeys != null) {
            for (String listKey : commentListKeys) {
                String videoId = listKey.substring(COMMENT_LIST_KEY_PREFIX.length());
                List<Object> commentCodes = redisTemplate.opsForList().range(listKey, 0, -1);

                if (commentCodes != null && !commentCodes.isEmpty()) {
                    String hashKey = COMMENT_HASH_KEY_PREFIX + videoId;
                    List<Object> commentsFromRedis = redisTemplate.opsForHash().multiGet(hashKey, commentCodes);
                    List<FsUserVideoComment> commentsToSync = commentsFromRedis.stream()
                            .filter(obj -> obj instanceof FsUserVideoComment)
                            .map(obj -> (FsUserVideoComment) obj)
                            .filter(comment -> !comment.getSynced())
                            .collect(Collectors.toList());

                    if (!commentsToSync.isEmpty()) {
                        fsUserVideoCommentMapper.batchInsertComments(commentsToSync);

                        // 标记已同步的评论
                        commentsToSync.forEach(comment -> comment.setSynced(true));
                        redisTemplate.opsForHash().putAll(hashKey, commentsToSync.stream().collect(Collectors.toMap(FsUserVideoComment::getCommentCode, comment -> comment)));
                    }
                }
            }
        }
    }


    @Override
    @Transactional
    public void syncRepliesToDatabase() {
        // 获取所有视频的评论列表键
        Set<String> repliesListKeys = redisTemplate.keys(REPLY_LIST_KEY_PREFIX + "*");

        if (repliesListKeys != null) {
            for (String listKey : repliesListKeys) {
                String videoId = listKey.substring(REPLY_LIST_KEY_PREFIX.length());
                List<Object> commentCodes = redisTemplate.opsForList().range(listKey, 0, -1);

                if (commentCodes != null && !commentCodes.isEmpty()) {
                    String hashKey = REPLY_HASH_KEY_PREFIX + videoId;
                    List<Object> repliesFromRedis = redisTemplate.opsForHash().multiGet(hashKey, commentCodes);
                    List<FsUserVideoComment> repliesToSync = repliesFromRedis.stream()
                            .filter(obj -> obj instanceof FsUserVideoComment)
                            .map(obj -> (FsUserVideoComment) obj)
                            .filter(comment -> !comment.getSynced())
                            .collect(Collectors.toList());

                    if (!repliesToSync.isEmpty()) {
                        fsUserVideoCommentMapper.batchInsertComments(repliesToSync);

                        // 标记已同步的评论
                        repliesToSync.forEach(comment -> comment.setSynced(true));
                        redisTemplate.opsForHash().putAll(hashKey, repliesToSync.stream().collect(Collectors.toMap(FsUserVideoComment::getCommentCode, comment -> comment)));
                    }
                }
            }
        }
    }
}
