package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.entity.Announcement;
import com.zhentao.mapper.AnnouncementMapper;
import com.zhentao.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 公告服务实现类
 */
@Service
public class AnnouncementServiceImpl implements AnnouncementService {
    
    @Autowired
    private AnnouncementMapper announcementMapper;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String ANNOUNCEMENT_CACHE_KEY = "announcement:active";
    private static final long CACHE_EXPIRE_SECONDS = 300; // 5分钟缓存
    
    @Override
    public List<Announcement> getActiveAnnouncements() {
        // 先从缓存获取
        try {
            Object cached = redisTemplate.opsForValue().get(ANNOUNCEMENT_CACHE_KEY);
            if (cached instanceof List) {
                @SuppressWarnings("unchecked")
                List<Announcement> cachedList = (List<Announcement>) cached;
                return cachedList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 缓存不存在，从数据库查询
        List<Announcement> announcements = queryActiveAnnouncements();
        
        // 存入缓存
        try {
            redisTemplate.opsForValue().set(
                ANNOUNCEMENT_CACHE_KEY, 
                announcements, 
                CACHE_EXPIRE_SECONDS, 
                TimeUnit.SECONDS
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return announcements;
    }
    
    @Override
    public void clearAnnouncementCache() {
        try {
            redisTemplate.delete(ANNOUNCEMENT_CACHE_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 从数据库查询有效的公告
     */
    private List<Announcement> queryActiveAnnouncements() {
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        
        wrapper.eq(Announcement::getStatus, 1)
               .and(w -> w.isNull(Announcement::getStartTime)
                         .or()
                         .le(Announcement::getStartTime, now))
               .and(w -> w.isNull(Announcement::getEndTime)
                         .or()
                         .ge(Announcement::getEndTime, now))
               .orderByDesc(Announcement::getPriority)
               .orderByDesc(Announcement::getCreateTime);
        
        return announcementMapper.selectList(wrapper);
    }
    
    /**
     * 处理公告更新消息（由Redis监听器调用）
     */
    public void handleAnnouncementUpdate(String message) {
        // 接收到公告更新消息，清除缓存
        System.out.println("收到公告更新通知，清除缓存: " + message);
        clearAnnouncementCache();
    }
}

