package cn.com.poc.meeting.cache;


import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.utils.SpringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 关键词计数器
 */
public class KeyWordCounter {

    private final static String REDIS_PREFIX = "MEETING_KEY_WORD_COUNT:";

    /**
     * 关键词计数统计
     *
     * @param content  文本
     * @param keywords 关键词
     * @return 关键词:数量
     */
    public static Map<String, Integer> keywordCount(String content, List<String> keywords) {
        Map<String, Integer> resMap = new LinkedHashMap<>();
        for (String keyword : keywords) {
            Pattern compile = Pattern.compile(keyword);
            Matcher matcher = compile.matcher(content);
            int count = 0;
            while (matcher.find()) {
                count++;
            }
            if (count == 0) {
                continue;
            }
            resMap.put(keyword, count);
        }
        Map<String, Integer> sortedMap = getSortedMap(resMap);
        return sortedMap;
    }

    /**
     * 提取关键词与文本中匹配的句子
     *
     * @param content  文本
     * @param keywords 关键词
     */
    public static Map<String, List<String>> keywordMatchSentence(String content, List<String> keywords) {
        Map<String, List<String>> result = new LinkedHashMap<>();
        // 将关键词转换为正则表达式模式（注意转义特殊字符）
        for (String keyword : keywords) {
            String regexPattern = Pattern.quote(keyword);
            String sentenceRegex = "[^,，:：;；.。!?！？\\n]*" + regexPattern + "[^,，:：;；.。!?！？\\n]*[,，:：;；.。!?！？\\n]";
            Pattern pattern = Pattern.compile(sentenceRegex, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(content);
            // 查找并输出匹配的句子
            List<String> sentences = new ArrayList<>();
            while (matcher.find()) {
                sentences.add(matcher.group().trim());
            }
            result.put(keyword, sentences);
        }
        return result;
    }

    /**
     * 缓存关键词计数
     */
    public static void cacheKeyWordCount(String key, Map<String, Integer> map) {
        String redisKey = REDIS_PREFIX + key;
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        Map<String, Object> saveMap = new LinkedHashMap<>();
        for (String k : map.keySet()) {
            Integer count = map.get(k);
            saveMap.put(k, count);
        }
        redisService.hmset(redisKey, saveMap);
    }

    /**
     * 获取关键词计数缓存
     */
    public static Map<String, Integer> getKeywordCountCache(String key) {
        Map<String, Integer> resMap = new LinkedHashMap<>();
        String redisKey = REDIS_PREFIX + key;
        RedisService redisService = SpringUtils.getBean(RedisService.class);

        if (!redisService.hasKey(redisKey)) {
            return resMap;
        }
        Map<Object, Object> map = redisService.hmget(redisKey);

        for (Object k : map.keySet()) {
            Integer count = (Integer) map.get(k);
            resMap.put(String.valueOf(k), count);
        }
        return getSortedMap(resMap);
    }


    private static @NotNull Map<String, Integer> getSortedMap(Map<String, Integer> resMap) {
        // 将Map转换为List
        List<Map.Entry<String, Integer>> list = new ArrayList<>(resMap.entrySet());

        // 使用自定义Comparator按value排序
        list.sort((o1, o2) -> {
            return o2.getValue().compareTo(o1.getValue()); // 降序
        });

        // 将排序后的结果存入LinkedHashMap (可选，如果需要保持插入顺序)
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}
