package com.wzj.soopin.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzj.soopin.content.domain.po.Vlog;
import com.wzj.soopin.content.service.IVlogPushService;
import com.wzj.soopin.content.service.VlogService;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.service.IMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.mq.domain.MQMessage;
import org.dromara.common.mq.utils.MqUtil;
import org.dromara.common.redis.redis.RedisCache;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.wzj.soopin.content.domain.base.BaseInfoProperties.REDIS_VLOG_BE_LIKED_COUNTS;
import static org.dromara.common.core.constant.GlobalConstants.HOT_VLOG_TAG;

@Service
@AllArgsConstructor
@Slf4j
public class VlogPushServiceImpl implements IVlogPushService {

    private final RedisCache redisCache;
    private final VlogService vlogService;

    private final IMemberService memberService;

    @Override
    public boolean cacheTopLikedVlogs(int limit ) {
        try {

        } catch (Exception e) {
            log.error("缓存点赞最多视频到Redis失败", e);
        }
        return true;
    }

    @Override
    public boolean pushVlogToMq(int count,String tag ) {

        if(tag.equals(HOT_VLOG_TAG)){
            // 1. 获取 ZSet 中所有成员（按分数升序排列）
            // 这里我们只关心成员(member)，不关心分数(score)，所以使用 range(key, start, end)
            log.info("开始查询点赞最多的{}条视频", count);
            Set<String> rankSet = redisCache.zSetRange(REDIS_VLOG_BE_LIKED_COUNTS, 0, count);
            if (rankSet == null ||rankSet.isEmpty()) {
                return false;
            }
            if(rankSet!=null&&rankSet.size()<count){
                //从数据库中获取差量数据
                Page<Vlog> vlogPage = new Page<>(1, count-rankSet.size());
                vlogPage = vlogService.page(vlogPage, new LambdaQueryWrapper<Vlog>()
                    .orderByDesc(Vlog::getLikeCounts));
                Set<String> vlogIds = vlogPage.getRecords().stream().map(vlog -> vlog.getId()).collect(Collectors.toSet());
                rankSet.addAll(vlogIds);
            }
            // 3. 将 Set 转换为 List 以便打乱顺序
            List<String> vlogList = new ArrayList<>(rankSet);

            // 4. 使用 Collections.shuffle 打乱 List 的顺序
            Collections.shuffle(vlogList);
            vlogList.stream().forEach(vlogId -> {

                //将数据发送的mq的热点数据队列
                MQMessage message = MQMessage.builder()
                    .topic("MEMBER_VLOG_MSG")
                    .tag(HOT_VLOG_TAG)
                    .messageType("json")
                    .data(vlogId)
                    .source("vlog_service")
                    .sendTime(LocalDateTime.now())
                    .build();
                MqUtil.sendMessage("MEMBER_VLOG_MSG",HOT_VLOG_TAG, message);
            });

        }else{
            IPage<String> vlogPage=vlogService.getVlogForUser(new Page<>(1, 100), Long.parseLong(tag));
            if(CollectionUtils.isEmpty(vlogPage.getRecords())){
                return false;
            }
            vlogPage.getRecords().stream().forEach(vlogId -> {
                //将数据发送的mq的热点数据队列
                MQMessage message = MQMessage.builder()
                    .topic("MEMBER_VLOG_MSG")
                    .tag(tag)
                    .messageType("json")
                    .data(vlogId)
                    .source("vlog_service")
                    .sendTime(LocalDateTime.now())
                    .build();
                MqUtil.sendMessage("MEMBER_VLOG_MSG"+":"+tag, message);
            });
        }


        return true;
    }


    @Override
    public void syncVlog() {

    }
}
