package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.frog.dao.AiUserHeartbeatRankDao;
import com.sonic.frog.domain.entity.AiUserHeartbeatRank;
import com.sonic.frog.service.AiUserHeartbeatRankService;
import com.sonic.frog.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

@Slf4j
@Service
public class AiUserHeartbeatRankServiceImpl extends ServiceImpl<AiUserHeartbeatRankDao, AiUserHeartbeatRank> implements AiUserHeartbeatRankService {

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

    @Override
    public void incrementHeartbeatVal(Long userId, BigDecimal heartbeatVal) {
        //查询基础数据
        AiUserHeartbeatRank aiUserHeartbeatRank = getOne(Wrappers.<AiUserHeartbeatRank>lambdaQuery().select(AiUserHeartbeatRank::getId).eq(AiUserHeartbeatRank::getUserId, userId));
        if(aiUserHeartbeatRank == null) {
            aiUserHeartbeatRank = AiUserHeartbeatRank.builder()
                    .userId(userId)
                    .heartbeatValTotal(heartbeatVal)
                    .createTime(LocalDateTime.now())
                    .editTime(LocalDateTime.now())
                    .build();
            save(aiUserHeartbeatRank);
            return;
        }
        //更新总值
        aiUserHeartbeatRankDao.incrementHeartbeatVal(aiUserHeartbeatRank.getId(), heartbeatVal);
    }

    @Override
    public BigDecimal getCurrentUserRank(Long userId) {
        Double score = stringRedisTemplate.opsForZSet().score(redisKeyUtils.heartbeatValTotalRankKey(), userId.toString());
        if(score != null) {
            Long count = stringRedisTemplate.opsForZSet().count(redisKeyUtils.heartbeatValTotalRankKey(), 0, 1001);
            if(count == null) {
                return new BigDecimal("1");
            }
            count = score.intValue() == 1000 ? 1001 : count;
            //计算榜单的占比 保留两位小数点；百分比计算公式=（当前用户的排名绝对值/符合条件的排名用户数量）* 100%
            BigDecimal percent = new BigDecimal(score).divide(new BigDecimal(count), 4, RoundingMode.HALF_UP);
            return percent;
        }
        return new BigDecimal("1");
    }

}
