package com.aps.common.util;

import com.aps.entity.StrategyScheduling;
import com.aps.entity.ConfigSetting;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 增强版JSON转换工具类，支持字段映射配置
 */
public class EnhancedJsonConversionUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(EnhancedJsonConversionUtil.class);
    
    // 字段映射配置
    private static final Map<String, String> FIELD_MAPPINGS = new ConcurrentHashMap<>();
    
    static {
        // 初始化字段映射
        FIELD_MAPPINGS.put("_X_ROW_KEY", "rowKey");
        FIELD_MAPPINGS.put("row_key", "rowKey");
        FIELD_MAPPINGS.put("ROW_KEY", "rowKey");
        // 可以添加更多映射
    }
    
    /**
     * 添加自定义字段映射
     */
    public static void addFieldMapping(String sourceField, String targetField) {
        FIELD_MAPPINGS.put(sourceField, targetField);
    }
    
    /**
     * 转换JSON数组到实体列表，支持字段映射
     */
    public static <T> List<T> convertJsonToEntities(String jsonArray, 
                                                   Map<String, String> customMappings,
                                                   Class<T> targetType) {
        if (jsonArray == null || jsonArray.trim().isEmpty()) {
            return Collections.emptyList();
        }
        
        try {
            ObjectMapper mapper = new ObjectMapper();
            // 忽略未知属性
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            List<Map<String, Object>> rawList = mapper.readValue(
                jsonArray, 
                new com.fasterxml.jackson.core.type.TypeReference<List<Map<String, Object>>>() {}
            );
            
            List<T> result = new ArrayList<>();
            for (Map<String, Object> rawMap : rawList) {
                T entity = convertMapToEntity(rawMap, customMappings, targetType);
                if (entity != null) {
                    result.add(entity);
                }
            }
            
            return result;
            
        } catch (Exception e) {
            logger.error("JSON转换失败", e);
            return Collections.emptyList();
        }
    }
    
    /**
     * 转换Map到实体，应用字段映射
     */
    private static <T> T convertMapToEntity(Map<String, Object> sourceMap, 
                                          Map<String, String> customMappings,
                                          Class<T> targetType) {
        if (sourceMap == null) {
            return null;
        }
        
        try {
            // 合并映射配置
            Map<String, String> allMappings = new HashMap<>(FIELD_MAPPINGS);
            if (customMappings != null) {
                allMappings.putAll(customMappings);
            }
            
            // 创建目标Map（应用字段映射）
            Map<String, Object> targetMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
                String targetField = allMappings.getOrDefault(entry.getKey(), entry.getKey());
                targetMap.put(targetField, entry.getValue());
            }
            
            // 转换为实体
            ObjectMapper mapper = new ObjectMapper();
            // 忽略未知属性
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.convertValue(targetMap, targetType);
            
        } catch (Exception e) {
            logger.error("Map转换实体失败", e);
            return null;
        }
    }
    
    /**
     * 批量转换（性能优化版）
     */
    public static <T> List<T> batchConvert(List<Map<String, Object>> sourceList, Class<T> targetType) {
        if (sourceList == null || sourceList.isEmpty()) {
            return Collections.emptyList();
        }
        
        List<T> result = new ArrayList<>(sourceList.size());
        ObjectMapper mapper = new ObjectMapper();
        // 忽略未知属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
        for (Map<String, Object> sourceMap : sourceList) {
            try {
                // 应用字段映射
                Map<String, Object> processedMap = processFieldMappings(sourceMap);
                T entity = mapper.convertValue(processedMap, targetType);
                result.add(entity);
            } catch (Exception e) {
                logger.warn("跳过转换失败的数据: {}", sourceMap);
            }
        }
        
        return result;
    }
    
    /**
     * 处理字段映射
     */
    private static Map<String, Object> processFieldMappings(Map<String, Object> sourceMap) {
        Map<String, Object> result = new HashMap<>();
        
        for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            
            // 应用映射规则
            String mappedKey = FIELD_MAPPINGS.getOrDefault(key, key);
            result.put(mappedKey, value);
        }
        
        return result;
    }
    
    // 为了向后兼容，保留原有的方法
    public static List<StrategyScheduling> convertJsonToEntities(String jsonArray, 
                                                                 Map<String, String> customMappings) {
        return convertJsonToEntities(jsonArray, customMappings, StrategyScheduling.class);
    }
}