package com.gameplatform.server.service.admin;

import com.gameplatform.server.mapper.admin.SystemConfigMapper;
import com.gameplatform.server.model.entity.admin.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Service
public class SystemConfigService {
    
    @Autowired
    private SystemConfigMapper systemConfigMapper;
    
    // 配置缓存：key -> ConfigEntry(value, cachedTime)
    private final ConcurrentMap<String, ConfigEntry> configCache = new ConcurrentHashMap<>();
    
    // 缓存TTL（毫秒）：5分钟
    private static final long CACHE_TTL_MS = 5 * 60 * 1000L;
    
    /**
     * 配置缓存条目
     */
    private static class ConfigEntry {
        final String value;
        final long cachedAtMs;
        
        ConfigEntry(String value, long cachedAtMs) {
            this.value = value;
            this.cachedAtMs = cachedAtMs;
        }
        
        boolean isExpired() {
            return System.currentTimeMillis() - cachedAtMs > CACHE_TTL_MS;
        }
    }
    
    public SystemConfig getConfigByKey(String configKey) {
        return systemConfigMapper.findByKey(configKey);
    }
    
    /**
     * 获取配置值（带缓存）
     * 注意：此方法被频繁调用（尤其在响应式流中），必须使用缓存避免连接泄漏
     */
    public String getConfigValue(String configKey, String defaultValue) {
        // 先检查缓存
        ConfigEntry cached = configCache.get(configKey);
        if (cached != null && !cached.isExpired()) {
            return cached.value;
        }
        
        // 缓存未命中或过期，查询数据库
        SystemConfig config = systemConfigMapper.findByKey(configKey);
        String value = config != null ? config.getConfigValue() : defaultValue;
        
        // 更新缓存
        configCache.put(configKey, new ConfigEntry(value, System.currentTimeMillis()));
        
        return value;
    }
    
    /**
     * 清除指定配置的缓存（用于配置更新后）
     */
    public void clearCache(String configKey) {
        configCache.remove(configKey);
    }
    
    /**
     * 清除所有配置缓存
     */
    public void clearAllCache() {
        configCache.clear();
    }
    
    public Integer getConfigValueAsInt(String configKey, Integer defaultValue) {
        String value = getConfigValue(configKey, null);
        if (value == null) return defaultValue;
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
    
    public Boolean getConfigValueAsBoolean(String configKey, Boolean defaultValue) {
        String value = getConfigValue(configKey, null);
        if (value == null) return defaultValue;
        return Boolean.parseBoolean(value);
    }
    
    public List<SystemConfig> getAllConfigs(int size, int offset) {
        return systemConfigMapper.findAll(size, offset);
    }
    
    public long getConfigCount() {
        return systemConfigMapper.countAll();
    }
    
    public List<SystemConfig> getConfigsByType(String configType) {
        return systemConfigMapper.findByType(configType);
    }
    
    public boolean createConfig(SystemConfig systemConfig) {
        boolean result = systemConfigMapper.insert(systemConfig) > 0;
        if (result && systemConfig.getConfigKey() != null) {
            clearCache(systemConfig.getConfigKey());
        }
        return result;
    }
    
    public boolean updateConfig(SystemConfig systemConfig) {
        boolean result = systemConfigMapper.update(systemConfig) > 0;
        if (result && systemConfig.getConfigKey() != null) {
            // 配置更新后清除缓存，确保下次读取最新值
            clearCache(systemConfig.getConfigKey());
        }
        return result;
    }
    
    public boolean deleteConfig(Long id) {
        boolean result = systemConfigMapper.deleteById(id) > 0;
        if (result) {
            // 删除后清除所有缓存（因为不知道具体 key）
            clearAllCache();
        }
        return result;
    }
    
    public boolean deleteConfigByKey(String configKey) {
        boolean result = systemConfigMapper.deleteByKey(configKey) > 0;
        if (result) {
            clearCache(configKey);
        }
        return result;
    }
    
    // 获取链接相关的默认配置
    public Integer getDefaultQuantity() {
        return getConfigValueAsInt("link.default_quantity", 50);
    }
    
    public Integer getRefreshInterval() {
        return getConfigValueAsInt("link.refresh_interval", 300);
    }
    
    public Integer getQrExpireTime() {
        return getConfigValueAsInt("link.qr_expire_time", 600);
    }
    
    // 获取链接倍数配置
    public Integer getLinkScaled() {
        return getConfigValueAsInt("link.scaled", 1);
    }
    

    

    
    public String getScriptServerUrl() {
        return getConfigValue("script.server_url", "http://36.138.184.60:12345");
    }
    
    public String getQrPathTemplate() {
        return getConfigValue("script.qr_path_template", "/{machineId}/二维码.png");
    }
    
    // 获取用户端相关配置
    public Integer getUserQrExpireSeconds() {
        return getConfigValueAsInt("user.qr_expire_seconds", 60);
    }
    
    public Integer getUserRefreshWaitSeconds() {
        return getConfigValueAsInt("user.refresh_wait_seconds", 10);
    }
    
    public Integer getUserLinkExpireHours() {
        return getConfigValueAsInt("user.link_expire_hours", 24);
    }
    
    public String getUserAssetsBaseUrl() {
        return getConfigValue("user.assets_base_url", "http://36.138.184.60:12345");
    }
    
    // 获取设备检测相关配置
    public String getDeviceIdleStatus() {
        return getConfigValue("device.idle_status", "空的");
    }
    
    // 获取首次选区后链接过期时间（秒）
    public Integer getFirstRegionExpireSeconds() {
        return getConfigValueAsInt("link.first_region_expire", 600);
    }
    
    // 获取用户进度显示格式（percent 或 ratio）
    public String getProgressDisplayFormat() {
        return getConfigValue("user.progress_display_format", "percent");
    }
    
    // 获取用户端自定义扫码内容
    public String getCustomScanContent() {
        return getConfigValue("user.custom_scan_content", "");
    }
    
    // 获取设备优先前缀列表（逗号分隔），返回List
    public List<String> getDevicePriorityPrefixes() {
        String value = getConfigValue("device.priority_prefixes", "");
        if (value == null || value.trim().isEmpty()) {
            return List.of();
        }
        // 按逗号分隔，去除空白，过滤空字符串
        return java.util.Arrays.stream(value.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(java.util.stream.Collectors.toList());
    }
    
    // 批量更新配置
    public boolean updateConfigs(List<SystemConfig> configs) {
        if (configs == null || configs.isEmpty()) {
            return false;
        }
        
        int successCount = 0;
        for (SystemConfig config : configs) {
            if (config.getId() != null) {
                if (systemConfigMapper.update(config) > 0) {
                    successCount++;
                }
            } else if (config.getConfigKey() != null) {
                // 根据key更新
                SystemConfig existing = systemConfigMapper.findByKey(config.getConfigKey());
                if (existing != null) {
                    config.setId(existing.getId());
                    config.setIsSystem(existing.getIsSystem()); // 保留原有的 isSystem 值
                    if (systemConfigMapper.update(config) > 0) {
                        successCount++;
                    }
                }
            }
        }
        
        return successCount > 0;
    }
    
    // 根据key批量更新配置值
    public boolean updateConfigValueByKey(String configKey, String configValue) {
        SystemConfig config = systemConfigMapper.findByKey(configKey);
        if (config == null) {
            return false;
        }
        config.setConfigValue(configValue);
        return systemConfigMapper.update(config) > 0;
    }
    
    // 验证配置值的格式是否正确
    public boolean validateConfigValue(String configType, String configValue) {
        if (configValue == null || configValue.trim().isEmpty()) {
            return false;
        }
        
        try {
            switch (configType.toUpperCase()) {
                case "INTEGER":
                    Integer.parseInt(configValue);
                    return true;
                case "BOOLEAN":
                    String lowerValue = configValue.toLowerCase();
                    return "true".equals(lowerValue) || "false".equals(lowerValue);
                case "JSON":
                    // 简单的JSON格式验证
                    String trimmed = configValue.trim();
                    return (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
                           (trimmed.startsWith("[") && trimmed.endsWith("]"));
                case "STRING":
                default:
                    return true;
            }
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
