package com.sonic.frog.job;


import com.alibaba.fastjson.JSONObject;
import com.sonic.common.client.JobmanClient;
import com.sonic.common.utils.LogUtils;
import com.sonic.frog.service.AiUserHeartbeatRelationService;
import com.sonic.frog.service.impl.AiUserStatServiceImpl;
import com.sonic.frog.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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.Set;
import java.util.concurrent.TimeUnit;

/**
 * 聊天次数未达到20次的定时刷新到数据库
 *
 * @author mzc
 */
@Slf4j
@Component
public class UpdateAiUserChatNumJob {

    @Autowired
    private JobmanClient jobmanClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private AiUserStatServiceImpl aiUserStatService;

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

    protected JobmanClient.JobResult updateAiUserChatNumJob(JobmanClient.JobContext jobContext) {
        try {
            LogUtils.setTraceId();
            log.info("===> updateAiUserChatNumJob start !!!");
            //从zset中取数据
            String aiChatNumKey = redisKeyUtils.aiChatNumKey();
            Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().rangeWithScores(aiChatNumKey, 0, -1);
            log.info("===> updateAiUserChatNumJob typedTuples:{}", JSONObject.toJSONString(typedTuples));
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                //聊天数
                Double score = typedTuple.getScore();
                Integer chatNum = score != null ? Double.valueOf(score).intValue() : 0;
                //Ai的Id
                Long aiId = Long.valueOf(typedTuple.getValue());
                //刷新到数据库
                aiUserStatService.increaseChatNum(aiId, chatNum);
                //刷新完后，删除该ai的聊天数量
                stringRedisTemplate.opsForZSet().remove(aiChatNumKey, aiId.toString());
            }
            log.info("===> updateAiUserChatNumJob end !!!");
            return JobmanClient.JobResult.success(0);
        } finally {
            LogUtils.removeTraceId();
        }
    }
}