package com.sonic.cow.job;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sonic.common.client.JobmanClient;
import com.sonic.common.utils.LogUtils;
import com.sonic.cow.service.VoiceChatService;
import com.sonic.cow.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;


/**
 * 用户离开3分钟后，如果语音通话未结束，停止语音通话
 *
 * @author code
 */
@Slf4j
@Component
public class VoiceChatUserLeaveHandler {

    @Autowired
    private JobmanClient jobmanClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private VoiceChatService voiceChatService;

    /**
     * 用户离开3分钟后，如果语音通话未结束，停止语音通话
     */
    private static final Long LEAVE_TIME = 1 * 60 * 1000L;

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

    protected JobmanClient.JobResult voiceChatUserLeaveJob(JobmanClient.JobContext jobContext) {
        try {
            LogUtils.setTraceId();
            String voiceChatUserLeaveRoomKey = redisKeyUtils.voiceChatUserLeaveRoomKey();
            Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().rangeWithScores(voiceChatUserLeaveRoomKey, 0, -1);
            if (CollectionUtils.isNotEmpty(typedTuples)) {
                for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                    //score为离开时的时间戮
                    Double score = typedTuple.getScore();
                    //value为用户id
                    String userId = typedTuple.getValue();
                    log.info("voiceChatUserLeaveJob userId:{}", userId);
                    if (StringUtils.isEmpty(userId) || score == null) {
                        continue;
                    }
                    //离开的时间戮
                    Long timestamp = score.longValue();
                    if (Long.valueOf(timestamp) + LEAVE_TIME > System.currentTimeMillis()) {
                        continue;
                    }
                    Boolean isStop = voiceChatService.stopVoiceChat(Long.valueOf(userId));
                    if (isStop) {
                        //清理掉已处理的redis数据
                        stringRedisTemplate.opsForZSet().remove(voiceChatUserLeaveRoomKey, userId);
                    }
                }
            }
            return JobmanClient.JobResult.success(0);
        } catch (Exception e) {
            log.error("voiceChatUserLeaveJob error", e);
        } finally {
            LogUtils.removeTraceId();
        }
        return JobmanClient.JobResult.success(0);
    }
}