package com.ruoyi.cms.util.sensitiveWord;

import com.ruoyi.cms.domain.SensitiveWordData;
import com.ruoyi.cms.mapper.SensitiveWordDataMapper;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class SensitiveWordChecker {

    @Autowired
    private SensitiveWordDataMapper sensitiveWordDataMapper;

    @Autowired
    private SensitiveWordTrie trie; // 注入前缀树
    // 缓存键常量
    private static final String SENSITIVE_WORD_CACHE_KEY = "sensitive:words";
    @Autowired
    private RedisCache redisCache;

    /**
     * 项目启动时初始化敏感词库到前缀树
     */
    @PostConstruct
    public void init() {
        List<String> sensitiveWords = getSensitiveWordsFromCache();
        if (sensitiveWords.isEmpty()) {
            // 缓存未命中，从数据库加载
            sensitiveWords = loadSensitiveWordsFromDbAndCache();
        }
        // 初始化前缀树
        trie.batchAddWords(sensitiveWords);
    }

    /**
     * 检测文本中的敏感词
     * @param text 待检测文本（如job.getDescription()）
     * @return 敏感词列表（空列表表示无敏感词）
     */
    public List<String> checkSensitiveWords(String text) {
        return trie.findAllSensitiveWords(text);
    }

    /**
     * 从缓存获取敏感词列表
     */
    @Cacheable(value = SENSITIVE_WORD_CACHE_KEY)
    public List<String> getSensitiveWordsFromCache() {
        // 从Redis获取
        Object cachedWords = redisCache.getCacheObject(SENSITIVE_WORD_CACHE_KEY);
        if (cachedWords instanceof List<?>) {
            return ((List<?>) cachedWords).stream()
                    .filter(obj -> obj instanceof String)
                    .map(obj -> (String) obj)
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 从数据库加载敏感词并更新缓存
     */
    public List<String> loadSensitiveWordsFromDbAndCache() {
        List<SensitiveWordData> wordList = sensitiveWordDataMapper.selectSensitiveworddataList(new SensitiveWordData());
        List<String> sensitiveWords = wordList.stream()
                .map(SensitiveWordData::getSensitiveWord)
                .collect(Collectors.toList());
        // 缓存有效期设置为24小时，可根据实际需求调整
        redisCache.setCacheObject(SENSITIVE_WORD_CACHE_KEY, sensitiveWords, 24, TimeUnit.HOURS);
        return sensitiveWords;
    }

    /**
     * 敏感词更新时清除缓存（需在敏感词管理服务中调用）
     */
    @CacheEvict(value = SENSITIVE_WORD_CACHE_KEY, allEntries = true)
    public void clearSensitiveWordCache() {
        // 清除缓存后可重新加载
        loadSensitiveWordsFromDbAndCache();
        // 重新初始化前缀树
        trie.clear();
        init();
    }

    /**
     * 新增/修改敏感词后更新缓存和前缀树
     */
    public void updateCacheAfterModify() {
        // 1. 清除旧缓存
        redisCache.deleteObject(SENSITIVE_WORD_CACHE_KEY);
        // 2. 从数据库重新加载最新数据并更新缓存
        List<String> latestWords = loadSensitiveWordsFromDbAndCache();
        // 3. 重建前缀树
        trie.clear();
        trie.batchAddWords(latestWords);
    }
}