package com.fs.course.task;

import com.fs.common.core.redis.RedisCache;
import com.fs.course.domain.FsUserVideo;
import com.fs.course.domain.FsUserVideoFavorite;
import com.fs.course.domain.FsUserVideoLike;
import com.fs.course.mapper.FsUserVideoCommentMapper;
import com.fs.course.mapper.FsUserVideoFavoriteMapper;
import com.fs.course.mapper.FsUserVideoLikeMapper;
import com.fs.course.mapper.FsUserVideoMapper;
import com.fs.course.service.IFsUserVideoCommentService;
import com.fs.store.domain.FsUser;
import com.fs.store.mapper.FsUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Component("videoTask")
public class VideoTask {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String LIKE_KEY_PREFIX = "like:video:";
    private static final String UNLIKE_KEY_PREFIX = "unlike:video:";
    private static final String FAVORITE_KEY_PREFIX = "favorite:video:";
    private static final String NO_FAVORITE_KEY_PREFIX = "nofavorite:video:";
    private static final String COMMENT_KEY_PREFIX = "comment:video:";
    private static final String VIDEO_COMMENT_COUNT_KEY_PATTERN = "comment:count:video:*";
    private static final String COMMENT_REPLY_COUNT_KEY_PATTERN = "reply:count:comment:*";
    @Autowired
    private FsUserVideoMapper videoMapper;
    @Autowired
    private FsUserVideoLikeMapper videoLikeMapper;
    @Autowired
    private FsUserVideoFavoriteMapper videoFavoriteMapper;
    @Autowired
    private FsUserVideoCommentMapper videoCommentMapper;
    @Autowired
    private IFsUserVideoCommentService videoCommentService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void autoNotShowVideo() {
        List<Long> list = videoMapper.selectNotAuditVideo();
        for (Long videoId : list){
            FsUserVideo video = new FsUserVideo();
            video.setVideoId(videoId);
            video.setStatus(0);
            video.setIsAudit(-1);
            video.setAuditTime(new Date());
            videoMapper.updateFsUserVideo(video);
        }
    }

    //同步点赞到数据库
    public void syncLikesToDatabase() {
        Collection<String> keys = redisCache.keys(LIKE_KEY_PREFIX + "*:user:*");
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String[] parts = key.split(":");
                Long videoId = Long.parseLong(parts[2]);
                long userId = Long.parseLong(parts[4]);
                //判断是否存在数据库
                int check = videoLikeMapper.checkLike(videoId, userId);
                if (check==0){
                    FsUserVideoLike map=new FsUserVideoLike();
                    map.setVideoId(videoId);
                    map.setUserId(userId);
                    map.setCreateTime(new Date());
                    videoLikeMapper.insertFsUserVideoLike(map);
                }
                //删除key
                redisCache.deleteObject(key);
            }
        }
    }

    //同步取消点赞到数据库
    public void syncUnlikesToDatabase() {
        Collection<String> keys = redisCache.keys(UNLIKE_KEY_PREFIX + "*:user:*");
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String[] parts = key.split(":");
                Long videoId = Long.parseLong(parts[2]);
                long userId = Long.parseLong(parts[4]);

                // 从数据库中删除点赞记录
                videoLikeMapper.deleteLike(videoId, userId);

                // 从Redis中删除记录
                redisCache.deleteObject(key);
            }
        }
    }

    //同步收藏到数据库
    public void syncFavoritesToDatabase() {
        Collection<String> keys = redisCache.keys(FAVORITE_KEY_PREFIX + "*:user:*");
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String[] parts = key.split(":");
                Long videoId = Long.parseLong(parts[2]);
                long userId = Long.parseLong(parts[4]);
                //判断是否存在数据库
                int check = videoFavoriteMapper.checkFavorite(videoId, userId);
                if (check==0){
                    FsUserVideoFavorite map=new FsUserVideoFavorite();
                    map.setVideoId(videoId);
                    map.setUserId(userId);
                    map.setCreateTime(new Date());
                    videoFavoriteMapper.insertFsUserVideoFavorite(map);
                }
                //删除key
                redisCache.deleteObject(key);
            }
        }
    }

    //同步取消收藏到数据库
    public void syncUnFavoritesToDatabase() {
        Collection<String> keys = redisCache.keys(NO_FAVORITE_KEY_PREFIX + "*:user:*");
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String[] parts = key.split(":");
                Long videoId = Long.parseLong(parts[2]);
                long userId = Long.parseLong(parts[4]);

                // 从数据库中删除点赞记录
                videoFavoriteMapper.deleteFavorite(videoId, userId);

                // 从Redis中删除记录
                redisCache.deleteObject(key);
            }
        }
    }

    //同步评论数量
    public void syncCommentCountToDatabase() {
        Set<String> keys = redisTemplate.keys(VIDEO_COMMENT_COUNT_KEY_PATTERN);
        if (keys != null) {
            for (String key : keys) {
                String videoIdStr = key.split(":")[3];
                Long videoId = Long.parseLong(videoIdStr);
                Integer commentCount = (Integer) redisTemplate.opsForValue().get(key);
                if (commentCount != null) {
                    videoMapper.updateCommentCount(videoId, commentCount);
                    redisTemplate.delete(key);
                }
            }
        }
    }

    //同步评论
    public void syncCommentsToDatabase() {
        videoCommentService.syncCommentsToDatabase();
        videoCommentService.syncRepliesToDatabase();
    }



    public boolean isSameYearMonthDay(LocalDate date1, LocalDate date2) {
        return date1.isEqual(date2);
    }


}
