package com.luojia_channel.modules.post.algorithm;

import cn.hutool.core.bean.BeanUtil;
import com.luojia_channel.common.utils.RedisUtil;
import com.luojia_channel.modules.post.dto.resp.PostBasicInfoDTO;
import com.luojia_channel.modules.post.entity.Comment;
import com.luojia_channel.modules.post.entity.Post;
import com.luojia_channel.modules.post.mapper.CommentMapper;
import com.luojia_channel.modules.post.mapper.PostMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;


@Component
@RequiredArgsConstructor
public class PostSelector {

    private final PostMapper postMapper;
    private final CommentMapper commentMapper;
    private final RedisUtil redisUtil;

    public void calculatePostScore(Post post){
        long hours = calculateHoursSince(post.getCreateTime());

        double likes = post.getLikeCount();
        double comments = post.getCommentCount();
        double favorites = post.getFavoriteCount();

        double newScore = (1 + likes + comments*0.7 + favorites*0.5)
                / Math.pow(1 + hours/24.0, 1.8);

        redisUtil.zAdd("post:hot:"+post.getCategoryId(), post.getId(), newScore);
        redisUtil.zAdd("post:hot:all", post.getId(), newScore);
    }

    public void calculateCommentScore(Comment comment){
        long hours = calculateHoursSince(comment.getCreateTime());

        double likes = comment.getLikeCount();
        double replies = comment.getReplyCount();
        double newScore = (1 + likes + replies*0.7)
                / Math.pow(1 + hours/24.0, 1.8);

        if(comment.getId().equals(comment.getTopId())) {
            redisUtil.zAdd("post:comment_by_hot:" + comment.getPostId(), comment.getId(), newScore);
        } else {
            redisUtil.zAdd("comment:reply_by_hot:" + comment.getTopId(), comment.getId(), newScore);
        }
    }

    // 更新帖子热度分数
    public void updatePostScore(Long postId) {
        Post post = postMapper.selectById(postId);
        if (post == null) return;
        calculatePostScore(post);
    }

    // 更新评论热度分数
    public void updateCommentScore(Long commentId) {
        Comment comment = commentMapper.selectById(commentId);
        if(comment == null) return;
        calculateCommentScore(comment);
    }

    // 计算从指定时间到现在经过的小时数
    public long calculateHoursSince(LocalDateTime startTime) {
        if (startTime == null) {
            return 0;
        }

        Instant startInstant = startTime.atZone(ZoneId.systemDefault()).toInstant();
        Instant nowInstant = Instant.now();

        long millisDiff = Duration.between(startInstant, nowInstant).toMillis();
        return TimeUnit.HOURS.convert(millisDiff, TimeUnit.MILLISECONDS);
    }

    // TODO 自定义首页帖子算法

}

