package com.sonic.frog.job;


import com.sonic.common.client.JobmanClient;
import com.sonic.common.utils.LogUtils;
import com.sonic.frog.dao.AiUserHeartbeatRankDao;
import com.sonic.frog.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 计算心动总分值榜单
 */
@Slf4j
@Component
public class CalcHeartbeatValTotalRankJob {

    @Autowired
    private JobmanClient jobmanClient;
    @Autowired
    private AiUserHeartbeatRankDao aiUserHeartbeatRankDao;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /** 每1小时执行一次 */
    @Scheduled(cron = "0 0 * * * ?")
    public void calcHeartbeatValTotalRankSchedule() {
        // 锁 1 分钟过期
        jobmanClient.run("calcHeartbeatValTotalRankJob", TimeUnit.MINUTES.toSeconds(2), this::calcHeartbeatValTotalRankJob);
    }

    protected JobmanClient.JobResult calcHeartbeatValTotalRankJob(JobmanClient.JobContext jobContext) {
        try {
            LogUtils.setTraceId();
            log.info("===> calcHeartbeatValTotalRankJob start !!!");
            //获取榜单的 top 1000出来，放到redis中去
            List<Long> userIdList = aiUserHeartbeatRankDao.getAiUserHeartbeatRankList(1000);
            Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();
            int i = 1;
            for (Long userId : userIdList) {
                ZSetOperations.TypedTuple<String> tuple = new DefaultTypedTuple<>(userId.toString(), (double) i); // 修复点：使用 Double 类型
                tuples.add(tuple);
                i++;
            }
            //存储到redis中去
            stringRedisTemplate.opsForZSet().add(redisKeyUtils.heartbeatValTotalRankKey(), tuples);
            //设置过期时间 10天
            stringRedisTemplate.expire(redisKeyUtils.heartbeatValTotalRankKey(), 10, TimeUnit.DAYS);
            log.info("===> calcHeartbeatValTotalRankJob count : {} end !!!", 0);
            return JobmanClient.JobResult.success(0);
        } finally {
            LogUtils.removeTraceId();
        }
    }

}