package com.fs.app.controller;


import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.domain.FsUserVideoComment;
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.param.HuaweiCloudStatisticsParam;
import com.fs.course.service.IFsUserVideoCommentService;
import com.fs.course.service.IHuaweiCloudStatisticsService;
import com.fs.course.service.impl.HuaweiCloudStatisticsServiceImpl;
import com.fs.his.service.IFsUserIntegralLogsService;
import com.fs.sop.domain.QwSopLogs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Api("短视频接口")
@RestController
@RequestMapping(value="/app/videoTest")
public class VideoTestController{

    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 IFsUserVideoCommentService videoCommentService;
    @Autowired
    private FsUserVideoLikeMapper videoLikeMapper;
    @Autowired
    private FsUserVideoFavoriteMapper videoFavoriteMapper;
    @Autowired
    private FsUserVideoCommentMapper videoCommentMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //同步点赞到数据库
    @ApiOperation("同步点赞")
    @GetMapping("/syncLikes")
    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);
            }
        }
    }

    //同步取消点赞到数据库
    @GetMapping("/syncUnlikes")
    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);
            }
        }
    }

    //同步收藏到数据库
    @GetMapping("/syncFavorites")
    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);
            }
        }
    }

    //同步取消收藏到数据库
    @GetMapping("/syncUnFavorites")
    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);
            }
        }
    }

    //同步评论数量
    @GetMapping("/syncCommentCount")
    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);
                }
            }
        }
    }

    @Autowired
    private IHuaweiCloudStatisticsService huaweiCloudStatisticsService;
    @GetMapping("/testHuaweiCloud")
    public R testHuaweiCloud(HuaweiCloudStatisticsParam param) {
        return huaweiCloudStatisticsService.DomainStatistics(param);
    }


    @GetMapping("/test1")
    public R test1() {
        // 设置时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 添加两分钟
        LocalDateTime newTime = currentTime.plusMinutes(2);
        // 格式化为字符串
        String newTimeString = newTime.format(formatter);
        QwSopLogs sopLogs = new QwSopLogs();
        sopLogs.setSendTime(newTimeString);
        sopLogs.setQwUserid("111111");
        sopLogs.setCorpId("externalContact.getCorpId()");
        sopLogs.setLogType(2);
        sopLogs.setSendType(3);
        sopLogs.setSendStatus(3L);
        sopLogs.setReceivingStatus(0L);
        sopLogs.setSort(3);
        sopLogs.setCompanyId(123L);
        sopLogs.setSopId(UUID.randomUUID().toString());
        sopLogs.setExternalUserId("externalContact.getExternalUserId()");
        sopLogs.setExternalUserName("externalContact.getName()");
        sopLogs.setFsUserId(123L);
        sopLogs.setContentJson("finishTemp.getSetting()");
        redisCache.setCacheObject("course:finish:"+sopLogs.getSopId(),sopLogs);
        return R.ok();
    }

    @GetMapping("/test2")
    public R test2() {
        Collection<String> keys = redisCache.keys("course:finish:*");
        for (String key : keys) {
            QwSopLogs logs = redisCache.getCacheObject(key);
            redisCache.deleteObject(key);
        }
        return R.ok();
    }







}
