package com.ruoyi.ibs.dashboard.service;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.dashboard.domain.vo.NotificationFileVO;
import com.ruoyi.ibs.dashboard.domain.vo.NotificationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author 吴凯程
 * @Date 2025/5/29
 **/
@Service
@Slf4j
public class NotificationDownloadService {
    private static final String NOTIFICATION_FILE_DOWNLOAD = "NOTIFICATION_FILE_DOWNLOAD_";
    @Resource
    private RedisCache redisCache;

    public List<NotificationVO> getNotificationList() {
        List<NotificationVO> collect = new ArrayList<>();
        // 根据通知的键和当前用户的用户名生成一个模式字符串，用于匹配通知的键
        String filePattern = NOTIFICATION_FILE_DOWNLOAD + SecurityUtils.getUsername() + "*";
        // 从Redis缓存中获取匹配该模式的所有键
        Collection<String> fileKeys = redisCache.keys(filePattern);
        // 检查获取到的键集合是否为空，如果不为空，则进行进一步处理
        if (fileKeys != null && fileKeys.size() > 0) {
            // 使用流操作处理键集合，将每个键对应的值（通知对象）映射出来，并按读取状态排序
            for (String key : fileKeys) {
                // 从Redis缓存中获取键对应的值（通知对象）
                NotificationFileVO notificationFileVO = redisCache.getCacheObject(key);
                // 返回通知对象
                collect.add(notificationFileVO);
            }
        }
        if (collect.size() > 0){
            collect = collect.stream().sorted((Comparator.comparing(NotificationVO::getReadStatus).thenComparing(NotificationVO::getCreateTime))).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    public String createFileNotification(String toUserName) {
        String uuid = UUID.randomUUID().toString();
        String key = NOTIFICATION_FILE_DOWNLOAD + toUserName + "_" + uuid;
        NotificationFileVO notificationFileVO = new NotificationFileVO();
        notificationFileVO.setUuid(uuid);
        notificationFileVO.setContent("地图拓客任务正在导出，请稍后");
        // 设置通知的阅读状态为未读
        notificationFileVO.setReadStatus(Boolean.FALSE);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 创建 DateTimeFormatter 对象，并指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间
        String formattedTime = now.format(formatter);
        // 设置通知的创建时间
        notificationFileVO.setCreateTime(formattedTime);
        redisCache.setCacheObject(key, notificationFileVO, 24, TimeUnit.HOURS);
        log.info("发送文件下载通知：" + notificationFileVO.getContent());
        return uuid;
    }

        /**
         * @param filePath
         * @param toUserName
         */
    public void sendFileNotification(String uuid, String toUserName, String filePath) {
        String key = NOTIFICATION_FILE_DOWNLOAD + toUserName + "_" + uuid;
        if (!redisCache.hasKey(key)){
            throw new ServiceException("文件导出任务不存在");
        }
        NotificationFileVO notificationFileVO = redisCache.getCacheObject(key);
        notificationFileVO.setContent("地图拓客任务导出完成，请及时下载");
        notificationFileVO.setFilePath(filePath);
        redisCache.setCacheObject(key, notificationFileVO, 24, TimeUnit.HOURS);
        log.info("发送文件下载通知：" + notificationFileVO.getContent());
    }


}
