#import "NSObject+XXGModel.h"
#import <objc/runtime.h>

@implementation NSObject (XXGModel)

+ (instancetype)xxpk_modelWithDict:(NSDictionary *)dict {
    if (![dict isKindOfClass:[NSDictionary class]]) return nil;
    
    id model = [[self alloc] init];
    
    // 获取所有属性列表
    NSArray *propertyNames = [self xxpk_propertyNames];
    NSDictionary *keyMapping = [self xxpk_replacedKeyFromPropertyName];
    NSDictionary *arrayMapping = [self xxpk_objectClassInArray];
    
    for (NSString *propertyName in propertyNames) {
        // 1. 获取对应的键路径（支持多级映射）
        NSString *keyPath = keyMapping[propertyName] ?: propertyName;
        
        // 2. 通过键路径获取值（支持多级访问）
        id value = [dict valueForKeyPath:keyPath];
//        NSLog(@"🔑 KeyPath: %@ => Value: %@", keyPath, value); // 添加日志
        if (!value || [value isKindOfClass:[NSNull class]]) continue;
        
        // 3. 获取属性类型
        NSString *propertyType = [self xxpk_propertyTypeForPropertyName:propertyName];
        
        // 4. 处理特殊类型转换
        value = [self xxpk_convertValue:value
                       forPropertyName:propertyName
                              keyPath:keyPath
                        propertyType:propertyType
                       arrayMapping:arrayMapping
                              parentDict:dict];
        
        // 5. 安全赋值
        if (value) {
            @try {
                [model setValue:value forKey:propertyName];
            } @catch (NSException *exception) {
//                NSLog(@"⚠️ Property set error: [%@] => %@", propertyName, exception);
            }
        }
    }
    return model;
}

+ (NSArray *)xxpk_modelArrayWithDictArray:(NSArray *)dictArray {
    // 1. 安全类型检查
    if (![dictArray isKindOfClass:[NSArray class]]) return @[];
    
    // 2. 创建可变数组存放转换结果
    NSMutableArray *modelArray = [NSMutableArray arrayWithCapacity:dictArray.count];
    
    // 3. 遍历字典数组
    for (id element in dictArray) {
        // 4. 跳过非字典元素
        if (![element isKindOfClass:[NSDictionary class]]) {
//            NSLog(@"⚠️ 数组元素类型错误，期望 NSDictionary，实际类型：%@", [element class]);
            continue;
        }
        
        // 5. 转换单个模型
        id model = [self xxpk_modelWithDict:element];
        
        // 6. 有效模型才加入数组
        if (model) {
            [modelArray addObject:model];
        }
    }
    
    return [modelArray copy];
}

- (NSMutableDictionary *)xxpk_modelToDict {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    // 获取所有属性
    NSArray *propertyNames = [[self class] xxpk_propertyNames];
    NSDictionary *keyMapping = [[self class] xxpk_replacedKeyFromPropertyName];
    NSDictionary *arrayMapping = [[self class] xxpk_objectClassInArray];
    
    for (NSString *propertyName in propertyNames) {
        NSString *keyPath = keyMapping[propertyName] ?: propertyName;
        id value = [self valueForKey:propertyName];
        
        if (!value || [value isKindOfClass:[NSNull class]]) continue;
        
        // 处理模型对象（包含嵌套模型）
        if ([value isKindOfClass:[NSObject class]] &&
            ![value isKindOfClass:[NSString class]] &&
            ![value isKindOfClass:[NSNumber class]] &&
            ![value isKindOfClass:[NSArray class]] &&
            ![value isKindOfClass:[NSDictionary class]]) {
            // 递归转换自定义对象
            value = [value xxpk_modelToDict];
        }
        
        // 处理模型数组（核心改进点）
        if ([value isKindOfClass:[NSArray class]]) {
            NSMutableArray *convertedArray = [NSMutableArray array];
            
            // 获取数组中元素的类型
            Class elementClass = arrayMapping[propertyName];
            if (!elementClass) {
                // 尝试从类方法获取类型（兼容旧版）
                NSString *className = [[self class] xxpk_objectClassInArray][propertyName];
                elementClass = NSClassFromString(className);
            }
            
            for (id item in value) {
                if (elementClass && [item isKindOfClass:elementClass]) {
                    // 递归转换数组中的模型元素
                    [convertedArray addObject:[item xxpk_modelToDict]];
                } else if ([item isKindOfClass:[NSObject class]] &&
                          ![item isKindOfClass:[NSString class]] &&
                          ![item isKindOfClass:[NSNumber class]]) {
                    // 处理未声明类型的模型元素
                    [convertedArray addObject:[item xxpk_modelToDict]];
                } else {
                    [convertedArray addObject:item];
                }
            }
            value = [convertedArray copy];
        }
        
        // 处理多级键路径（如把 subName 映射到 super.sub.name）
        if ([keyPath containsString:@"."]) {
            NSArray *keys = [keyPath componentsSeparatedByString:@"."];
            __block NSMutableDictionary *currentDict = dict;
            
            [keys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
                if (idx == keys.count - 1) {
                    currentDict[key] = value;
                } else {
                    if (!currentDict[key] || ![currentDict[key] isKindOfClass:[NSMutableDictionary class]]) {
                        currentDict[key] = [NSMutableDictionary dictionary];
                    }
                    currentDict = currentDict[key];
                }
            }];
        } else {
            dict[keyPath] = value;
        }
    }
    
    return [dict mutableCopy];
}

#pragma mark - 新增多级键路径支持的核心方法
// 修改后的属性列表获取方法（包含父类属性）
+ (NSArray<NSString *> *)xxpk_propertyNames {
    NSMutableArray *names = [NSMutableArray array];
    Class cls = self;
    
    // 递归遍历父类直到NSObject
    while (cls != [NSObject class]) {
        unsigned int count;
        objc_property_t *properties = class_copyPropertyList(cls, &count);
        
        for (unsigned int i = 0; i < count; i++) {
            objc_property_t property = properties[i];
            const char *name = property_getName(property);
            NSString *propertyName = [NSString stringWithUTF8String:name];
            
            // 防止重复添加（优先保留子类属性）
            if (![names containsObject:propertyName]) {
                [names addObject:propertyName];
            }
        }
        free(properties);
        
        // 继续获取父类属性
        cls = [cls superclass];
    }
    return [names copy];
}

// 增强版类型转换处理
+ (id)xxpk_convertValue:(id)value
       forPropertyName:(NSString *)propertyName
              keyPath:(NSString *)keyPath
        propertyType:(NSString *)propertyType
       arrayMapping:(NSDictionary *)arrayMapping
        parentDict:(NSDictionary *)parentDict {
    
    // 处理字典转模型（支持嵌套键路径）
    if ([value isKindOfClass:[NSDictionary class]]) {
        // 1. 获取目标模型类
        Class modelClass = NSClassFromString(propertyType);
//        NSLog(@"🔄 [Model转换] 属性名:%@ 类型:%@ 键路径:%@", propertyName, modelClass, keyPath);
        
        // 2. 安全检查模型类有效性
        BOOL isValidClass = modelClass &&
                           ![modelClass isSubclassOfClass:[NSDictionary class]] &&
                           ![modelClass isSubclassOfClass:[NSArray class]] &&
                           [modelClass respondsToSelector:@selector(xxpk_modelWithDict:)];
        
        if (!isValidClass) {
//            NSLog(@"❌ [Model转换] 失败: 无效的模型类 %@", modelClass);
            return value; // 返回原始字典避免崩溃
        }
        
        // 3. 统一使用当前层级的value进行转换（关键修复）
//        NSLog(@"✅ [Model转换] 使用子字典转换: %@", [value description]);
        id convertedModel = [modelClass xxpk_modelWithDict:value];
        
        // 4. 二次校验转换结果
        if (!convertedModel) {
//            NSLog(@"⚠️ [Model转换] 警告: %@ 转换失败，检查数据格式", modelClass);
        }
        return convertedModel;
    }
    
    // 处理数组转模型数组
    if ([value isKindOfClass:[NSArray class]]) {
        Class itemClass = NSClassFromString(arrayMapping[propertyName]);
        if (itemClass) {
            NSMutableArray *models = [NSMutableArray array];
            for (id subValue in value) {
                if ([subValue isKindOfClass:[NSDictionary class]]) {
                    [models addObject:[itemClass xxpk_modelWithDict:subValue]];
                } else {
                    [models addObject:subValue];
                }
            }
            return models;
        }
    }
    
    // 处理键路径嵌套值（如 super.sub.name）
    if ([keyPath containsString:@"."] && [value isKindOfClass:[NSString class]]) {
        return [self xxpk_convertBasicTypeValue:value propertyType:propertyType];
    }
    
    return [self xxpk_convertBasicTypeValue:value propertyType:propertyType];
}

// 基础类型转换（支持 BOOL/NSInteger/NSString 等）
+ (id)xxpk_convertBasicTypeValue:(id)value propertyType:(NSString *)type {
    if ([value isKindOfClass:[NSString class]]) {
        NSString *stringValue = (NSString *)value;
        
        if ([type isEqualToString:@"NSString"]) {
            return stringValue;
        }
        if ([type isEqualToString:@"BOOL"]) {
            return @([stringValue boolValue] ||
                    [stringValue.lowercaseString isEqualToString:@"yes"] ||
                    [stringValue.lowercaseString isEqualToString:@"true"]);
        }
        if ([type isEqualToString:@"NSInteger"]) {
            return @([stringValue integerValue]);
        }
        if ([type isEqualToString:@"int"]) {
            return @([stringValue intValue]);
        }
        if ([type isEqualToString:@"double"]) {
            return @([stringValue doubleValue]);
        }
        if ([type isEqualToString:@"float"]) {
            return @([stringValue floatValue]);
        }
        if ([type isEqualToString:@"NSNumber"]) {
            return [[NSNumberFormatter new] numberFromString:stringValue] ?: @0;
        }
    }
    
    // NSNumber 转基础类型
    if ([value isKindOfClass:[NSNumber class]]) {
        if ([type isEqualToString:@"NSString"]) {
            return [value stringValue];
        }
    }
    
    return value;
}

// 增强属性类型判断
+ (NSString *)xxpk_propertyTypeForPropertyName:(NSString *)name {
    objc_property_t property = class_getProperty(self, name.UTF8String);
    if (!property) return nil;
    
    const char *attrs = property_getAttributes(property);
    NSString *attributeStr = [NSString stringWithUTF8String:attrs];
    
    // 处理格式 T@"Address",&,N,V_address
    if ([attributeStr containsString:@"@\""]) {
        NSRange range = [attributeStr rangeOfString:@"@\""];
        NSString *typeStr = [attributeStr substringFromIndex:range.location+2];
        typeStr = [typeStr componentsSeparatedByString:@"\""].firstObject;
        return typeStr;
    }
    
    // 处理基础类型 q=NSInteger, B=BOOL 等
    const char typeCode = attrs[1];
    switch (typeCode) {
        case 'B': return @"BOOL";
        case 'q': return @"NSInteger";
        case 'i': return @"int";
        case 'd': return @"double";
        case 'f': return @"float";
        default: return nil;
    }
}

// 默认字段映射（子类可重写）
+ (NSDictionary *)xxpk_replacedKeyFromPropertyName {
    return @{};
}

// 处理数组模型转换（子类可重写）
+ (NSDictionary *)xxpk_objectClassInArray {
    return @{};
}

// 处理未定义的 Key，防止崩溃
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

@end
