package com.pig4cloud.pig.statistics.Util;


import com.pig4cloud.pig.statistics.api.entity.ConfigItem;
import com.pig4cloud.pig.statistics.mapper.StatConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wcl
 * @date 2025/8/19 10:51
 * @description: 配置缓存工具类
 */
@Component
@Slf4j
public class ConfigUtils {

	private static StatConfigMapper statConfigMapper;
	private static RedisTemplate<String, Object> redisTemplate;
	private static final String CONFIG_CACHE_PREFIX = "sys_config:";

	@Autowired
	public ConfigUtils(StatConfigMapper statConfigMapper, RedisTemplate<String, Object> redisTemplate) {
		ConfigUtils.statConfigMapper = statConfigMapper;
		ConfigUtils.redisTemplate = redisTemplate;
	}

	/**
	 * 获取配置项
	 * @param configKey 配置项key
	 * @return 配置项
	 */
	public static List<ConfigItem> getConfigValues(String configKey) {
		try {
			String cacheKey = CONFIG_CACHE_PREFIX + configKey;
			
			// 尝试从缓存获取
			List<ConfigItem> cached = (List<ConfigItem>) redisTemplate.opsForValue().get(cacheKey);
			if (cached != null) {
				log.debug("从缓存获取配置: {}", configKey);
				return cached;
			}
			
			// 从数据库查询
			List<ConfigItem> list = statConfigMapper.selectByConfigKey(configKey);
			if (list != null && !list.isEmpty()) {
				try {
					// 尝试存入缓存
					redisTemplate.opsForValue().set(cacheKey, list, 24, TimeUnit.HOURS);
					log.debug("配置已存入缓存: {}", configKey);
				} catch (Exception e) {
					log.warn("配置缓存失败，但不影响业务: {}", configKey, e);
				}
			}
			
			return list != null ? list : new ArrayList<>();
		} catch (Exception e) {
			log.error("获取配置失败: {}", configKey, e);
			// 降级处理：直接查询数据库
			try {
				return statConfigMapper.selectByConfigKey(configKey);
			} catch (Exception dbEx) {
				log.error("数据库查询也失败: {}", configKey, dbEx);
				return new ArrayList<>();
			}
		}
	}

	public static void clearConfigCache(String configKey) {
		try {
			redisTemplate.delete(CONFIG_CACHE_PREFIX + configKey);
			log.debug("配置缓存已清除: {}", configKey);
		} catch (Exception e) {
			log.warn("清除配置缓存失败: {}", configKey, e);
		}
	}

	/**
	 * 获取一条配置
	 * @param configKey 配置键
	 * @param configValue 配置值
	 * @return 配置项
	 */
	public static ConfigItem getConfigValue(String configKey, String configValue) {
		try {
			List<ConfigItem> configValues = getConfigValues(configKey);
			
			if (configValues != null && !configValues.isEmpty()) {
				for (ConfigItem item : configValues) {
					if (item.getValue() != null && item.getValue().equals(configValue)) {
						return item;
					}
				}
			}
			
			// 如果没有找到匹配的配置，返回默认值
			ConfigItem defaultItem = new ConfigItem();
			defaultItem.setName(configKey);
			defaultItem.setValue(configValue);
			defaultItem.setLabel("未知配置");
			return defaultItem;
		} catch (Exception e) {
			log.error("获取配置值失败: key={}, value={}", configKey, configValue, e);
			// 返回默认值
			ConfigItem defaultItem = new ConfigItem();
			defaultItem.setName(configKey);
			defaultItem.setValue(configValue);
			defaultItem.setLabel("配置获取失败");
			return defaultItem;
		}
	}
}
