package com.aps.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 生产环境可用的深拷贝工具类
 */
public class ProductionDeepCopyUtil {
    
    private static final ObjectMapper objectMapper = createProductionObjectMapper();
    
    private static ObjectMapper createProductionObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        
        // 必须的配置
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        
        // 可选的安全配置
        mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(com.fasterxml.jackson.core.JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        
        return mapper;
    }
    
    /**
     * 安全的深拷贝（带错误处理）
     */
    public static <T> T deepCopy(T source) {
        return deepCopy(source, null);
    }
    
    /**
     * 指定类型的深拷贝
     */
    @SuppressWarnings("unchecked")
    public static <T> T deepCopy(T source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        
        try {
            Class<?> targetClass = (clazz != null) ? clazz : source.getClass();
            String json = objectMapper.writeValueAsString(source);
            return (T) objectMapper.readValue(json, targetClass);
        } catch (Exception e) {
            throw new RuntimeException("深拷贝失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 带默认值的深拷贝
     */
    public static <T> T deepCopy(T source, T defaultValue) {
        try {
            return deepCopy(source);
        } catch (Exception e) {
            System.err.println("深拷贝失败，使用默认值: " + e.getMessage());
            return defaultValue;
        }
    }
    
    /**
     * 列表深拷贝
     */
    public static <T> List<T> deepCopyList(List<T> source) {
        if (source == null) {
            return new ArrayList<>();
        }
        
        try {
            // 如果列表为空，我们无法推断类型，但仍然需要保持原来的类型信息
            if (source.isEmpty()) {
                // 返回一个新的空列表，保持相同的运行时类型
                return new ArrayList<>();
            }
            
            // 获取列表元素的类型
            Class<?> elementType = source.get(0).getClass();
            
            // 构造正确的集合类型信息
            String json = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(json, 
                objectMapper.getTypeFactory().constructCollectionType(List.class, elementType));
        } catch (Exception e) {
            throw new RuntimeException("列表深拷贝失败", e);
        }
    }
    
    /**
     * 带指定元素类型的列表深拷贝
     */
    public static <T> List<T> deepCopyList(List<T> source, Class<T> elementType) {
        if (source == null) {
            return new ArrayList<>();
        }
        
        try {
            String json = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(json, 
                objectMapper.getTypeFactory().constructCollectionType(List.class, elementType));
        } catch (Exception e) {
            throw new RuntimeException("列表深拷贝失败", e);
        }
    }


    public static <T> CopyOnWriteArrayList<T> deepCopyList(CopyOnWriteArrayList<T> source, Class<T> elementType) {
        if (source == null) {
            return new CopyOnWriteArrayList<>();
        }

        try {
            String json = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(json,
                    objectMapper.getTypeFactory().constructCollectionType(CopyOnWriteArrayList.class, elementType));
        } catch (Exception e) {
            throw new RuntimeException("列表深拷贝失败", e);
        }
    }

    public static <K, V> Map<K, V> deepCopyMap(Map<K, V> source) {
        if (source == null) {
            return new HashMap<>();
        }

        try {
            String json = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(json, new TypeReference<Map<K, V>>() {});
        } catch (Exception e) {
            throw new RuntimeException("Map深拷贝失败", e);
        }
    }
    public static <K, V> TreeMap<K, V> deepCopyTreeMap(TreeMap<K, V> source, Class<K> keyType, Class<V> valueType) {
        if (source == null) {
            return new TreeMap<>();
        }

        try {
            String json = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(json,
                    objectMapper.getTypeFactory().constructMapType(TreeMap.class, keyType, valueType));
        } catch (Exception e) {
            throw new RuntimeException("TreeMap深拷贝失败", e);
        }
    }
}