package com.fs.course.task;

import cn.hutool.json.JSONUtil;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.*;
import com.fs.course.mapper.*;
import com.fs.course.service.IFsUserVideoCommentService;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
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.*;

@Component("videoTask")
public class VideoTask {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String YL_SECRET_ID = "AKIDiMq9lDf2EOM9lIfqqfKo7FNgM5meD0sT";
    private static final String YL_SECRET_KEY = "u5SuS80342xzx8FRBukza9lVNHKNMSaB";
    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;
    @Autowired
    private FsUserCourseVideoMapper courseVideoMapper;
    @Autowired
    private FsCourseRedPacketLogMapper redPacketLogMapper;

    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();
    }

    @Autowired
    private FsUserMapper fsUserMapper;

    //会员到期任务
    public void vipExpiration() {
        List<FsUser> list = fsUserMapper.selectFsUserIsVip();
        LocalDate today = LocalDate.now();

        for (FsUser user : list) {
            LocalDate vipEndDate = user.getVipEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            if (vipEndDate.isBefore(today) || vipEndDate.isEqual(today)) {
                FsUser userMap = new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setIsVip(0);
                userMap.setVipStatus(2);
                fsUserMapper.updateFsUser(userMap);
                // 添加日志记录
                logger.info("User ID: " + user.getUserId() + " VIP status updated.");
            }
        }
    }

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

    @Autowired
    private FsCourseWatchLogMapper courseWatchLogMapper;

    public void findWatchLogsExitAndWatching() {

        List<FsCourseWatchLog> watchingLogs = courseWatchLogMapper.findWatchLogsExitAndWatching();
        for (FsCourseWatchLog log : watchingLogs) {
            FsCourseWatchLog log1 = new FsCourseWatchLog();
            log1.setLogType(2);
            log1.setLogId(log.getLogId());
            courseWatchLogMapper.updateFsCourseWatchLog(log1);
        }
    }



    public void getFileSize() {
        List<FsUserCourseVideo> videos  = courseVideoMapper.selectVideoIsPrivate();
        for (FsUserCourseVideo video : videos){
            // 1 初始化用户身份信息(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials(YL_SECRET_ID, YL_SECRET_KEY);
            // 2 设置bucket的区域,
            ClientConfig clientConfig = new ClientConfig(new Region("ap-chongqing"));
            // 3 生成cos客户端
            COSClient cosclient = new COSClient(cred, clientConfig);

            int index = video.getVideoUrl().indexOf("com/");
            if (index != -1) {
                String subString = video.getVideoUrl().substring(index + 4); // Adding 4 to skip "com/"
                ObjectMetadata objectMetadata = cosclient.getObjectMetadata("hylj-1323137866", subString);
                video.setFileSize(objectMetadata.getContentLength());
                video.setFileKey(subString);
                video.setLineOne("https://rttcpv.ylrzcloud.com/"+subString);
                video.setLineTwo("https://rtctev.ylrzcloud.com/"+subString);
                video.setVideoUrl("https://rttcpv.ylrzcloud.com/"+subString);
                courseVideoMapper.updateFsUserCourseVideo(video);
            }


        }
    }
}
