#import <Foundation/Foundation.h>
#import "UnityBridge.h"
#import <platform_core_sdk/platform_core_sdk.h>

@interface SDKDelegate : AccessCoreAppDelegate <HLSystemDelegate, HLPaymentDelegate, HLAccountDelegate, HLShareCallback>

@end

extern "C" {

    // JSON工具函数
    NSString* jsonStringWithDictionary(NSDictionary* dict) {
        if (!dict) return @"{}";
        
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
        if (jsonData) {
            return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        return @"{}";
    }

    void UnitySendMessage(const char*, const char*, const char*);
}

@implementation SDKDelegate

#pragma mark - HLSystemDelegate
- (void)initSuccess:(AccessInitResult *)initResult {
    NSLog(@"🍎 SDK初始化成功");
    NSDictionary *dict = @{
        @"channel": initResult.channel ?: @"",
        @"gameId": @(initResult.gameId),
        @"channelId": @(initResult.channelId)
    };
    NSString *json = jsonStringWithDictionary(dict);
    UnitySendMessage("PlatformCallback", "onInitSuccess", [json UTF8String]);
}

- (void)initFailed {
    NSLog(@"🍎 SDK初始化失败");
    UnitySendMessage("PlatformCallback", "onInitFailed", "failed");
}

#pragma mark - HLPaymentDelegate
- (void)paySuccess {
    NSLog(@"🍎 支付成功");
    UnitySendMessage("PlatformCallback", "onPaySuccess", "pay_success");
}

- (void)payError:(NSError *)error {
    NSLog(@"🍎 支付失败: %@", error.localizedDescription);
    NSString *errorMsg = [NSString stringWithFormat:@"pay_failed:%@", error.localizedDescription];
    UnitySendMessage("PlatformCallback", "onPayFailed", [errorMsg UTF8String]);
}

- (void)payGoodsList:(NSArray<AccessGoodsInfo *>*)info {
    NSLog(@"🍎 获取商品列表成功，数量: %lu", (unsigned long)info.count);

    NSMutableArray *array = [NSMutableArray array];
    for (AccessGoodsInfo *item in info) {
        NSDictionary *dict = @{
            @"region": item.region ?: @"",
            @"currency": item.currency ?: @"",
            @"symbol": item.symbol ?: @"",
            @"itemId": item.itemId ?: @"",
            @"itemName": item.itemName ?: @"",
            @"itemCount": item.itemCount ?: @"",
            @"itemPrice": item.itemPrice ?: @"",
            @"showTag": item.showTag ?: @""
        };
        [array addObject:dict];
    }

    // 包一层，方便 Unity JsonUtility 解析
    //NSDictionary *wrapper = @{@"array": array};
    NSString *json = jsonStringWithDictionary(array);

    UnitySendMessage("PlatformCallback", "onPayGoodsList", [json UTF8String]);
}

- (void)payGpodsListFail {
    NSLog(@"🍎 获取商品列表失败");
    UnitySendMessage("PlatformCallback", "OnGoodsList", "get_goods_failed");
}

#pragma mark - HLAccountDelegate
- (void)loginSuccess:(AccessLoginInfo *)accountInfo {
    NSLog(@"🍎 登录成功: %lld", accountInfo.uid);
    NSDictionary *dict = @{
        @"uid": @(accountInfo.uid),
        @"accessToken": accountInfo.accessToken ?: @"",
        @"channel": accountInfo.channel ?: @"",
//        @"channelUid": accountInfo.channelUid ?: @"",
        @"serverArea": accountInfo.serverArea ?: @"",
        @"extendInfo": accountInfo.extendInfo ?: @{}
    };
    NSString *json = jsonStringWithDictionary(dict);
    UnitySendMessage("PlatformCallback", "onLoginSuccess", [json UTF8String]);
}

- (void)refreshUser:(AccessLoginInfo *)refreshAccountInfo {
    NSLog(@"🍎 用户信息刷新: %lld", refreshAccountInfo.uid);
    NSDictionary *dict = @{
        @"uid": @(refreshAccountInfo.uid),
        @"accessToken": refreshAccountInfo.accessToken ?: @"",
        @"channel": refreshAccountInfo.channel ?: @"",
//        @"channelUid": refreshAccountInfo.channelUid ?: @"",
        @"serverArea": refreshAccountInfo.serverArea ?: @"",
        @"extendInfo": refreshAccountInfo.extendInfo ?: @{}
    };
    NSString *json = jsonStringWithDictionary(dict);
    UnitySendMessage("PlatformCallback", "onRefreshUser", [json UTF8String]);
}

- (void)loginFailure {
    NSLog(@"🍎 登录失败");
    UnitySendMessage("PlatformCallback", "onLoginFailed", "login_failed");
}

- (void)logout {
    NSLog(@"🍎 用户登出");
    UnitySendMessage("PlatformCallback", "onLogout", "logout_success");
}

#pragma mark - HLShareCallback
- (void)shareSucceeded:(BOOL)result {
    NSLog(@"🍎 分享成功: %@", result ? @"YES" : @"NO");
    UnitySendMessage("PlatformCallback", "onShareSuccess", "share_success");
}

- (void)shareFailed:(BOOL)result {
    NSLog(@"🍎 分享失败: %@", result ? @"YES" : @"NO");
    UnitySendMessage("PlatformCallback", "onShareFailed", "share_failed");
}

@end

// 全局委托实例
static SDKDelegate *sdkDelegate = nil;
@implementation UnityBridge

+ (void)initSdk {
    if (!sdkDelegate) {
        sdkDelegate = [[SDKDelegate alloc] init];
    }
    // 获取SDK单例并设置委托
    AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
    sdk.systemDelegate = sdkDelegate;
    sdk.paymentDelegate = sdkDelegate;
    sdk.accountDelegate = sdkDelegate;
    sdk.shareDelegate = sdkDelegate;
}

@end

// C函数实现
extern "C" {

    void _LoginSdk() {
        NSLog(@"🍎 调用SDK登录");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        [sdk login];
    }

    void _LogoutSdk() {
        NSLog(@"🍎 调用SDK登出");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        [sdk logout];
    }

    void _QueryGoodsInfo() {
        NSLog(@"🍎 查询商品信息");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        [sdk queryGoodsInfo];
    }

    //上报用户信息至SDK
    void _ReportUserInfoFull(int eventType, const char* jsonInfo) {
        NSLog(@"🍎 上报完整用户信息(JSON方式)");
        
        if (!jsonInfo) {
            NSLog(@"🍎 JSON数据为空");
            return;
        }
        
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        AccessPlayerInfo *playerInfo = [[AccessPlayerInfo alloc] init];
        
        NSString *jsonStr = [NSString stringWithUTF8String:jsonInfo];
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        
        if (error || ![jsonDict isKindOfClass:[NSDictionary class]]) {
            NSLog(@"🍎 解析JSON失败: %@", error.localizedDescription);
            return;
        }
        
        // 安全获取字符串值的辅助方法
        NSString* (^safeString)(id) = ^(id obj) {
            if (obj == nil || [obj isKindOfClass:[NSNull class]]) {
                return @"";
            }
            if ([obj isKindOfClass:[NSString class]]) {
                return (NSString*)obj;
            }
            if ([obj isKindOfClass:[NSNumber class]]) {
                return [(NSNumber*)obj stringValue];
            }
            return [obj description] ?: @"";
        };
        
        // 映射字段
        playerInfo.role_id = safeString(jsonDict[@"RoleId"]);
        playerInfo.role_name = safeString(jsonDict[@"RoleName"]);
        playerInfo.role_level = safeString(jsonDict[@"RoleLevel"]);
        playerInfo.server_id = safeString(jsonDict[@"ServerId"]);
        playerInfo.server_name = safeString(jsonDict[@"ServerName"]);
        playerInfo.zone_id = safeString(jsonDict[@"ZoneId"]);
        playerInfo.zone_name = safeString(jsonDict[@"ZoneName"]);
        playerInfo.party_name = safeString(jsonDict[@"PartyName"]);
        playerInfo.vip = safeString(jsonDict[@"Vip"]);
        playerInfo.balance = safeString(jsonDict[@"Balance"]);
        playerInfo.phylum = safeString(jsonDict[@"Phylum"]);
        playerInfo.classfield = safeString(jsonDict[@"Classfield"]);
        playerInfo.extene_action = safeString(jsonDict[@"ExteneAction"]);
        
        // 处理extra字段
        NSString *extraJsonStr = safeString(jsonDict[@"ExtraJson"]);
        if (extraJsonStr.length > 0 && ![extraJsonStr isEqualToString:@"{}"]) {
            NSData *extraData = [extraJsonStr dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *extraDict = [NSJSONSerialization JSONObjectWithData:extraData options:0 error:&error];
            
            if (!error && [extraDict isKindOfClass:[NSDictionary class]]) {
                for (NSString *key in extraDict) {
                    id value = extraDict[key];
                    if ([value isKindOfClass:[NSNumber class]]) {
                        const char *type = [value objCType];
                        if (strcmp(type, @encode(int)) == 0 || strcmp(type, @encode(long)) == 0) {
                            [playerInfo addExtra:key intValue:[value intValue]];
                        } else if (strcmp(type, @encode(double)) == 0 || strcmp(type, @encode(float)) == 0) {
                            [playerInfo addExtra:key doubleValue:[value doubleValue]];
                        }
                    } else if ([value isKindOfClass:[NSString class]]) {
                        [playerInfo addExtra:key NSStringValue:value];
                    }
                }
            } else {
                NSLog(@"🍎 解析 extra JSON 失败: %@", error.localizedDescription);
            }
        }
        
        // 调用 SDK 上报
        [sdk report:(EventType)eventType data:playerInfo];
    }

    void _StartPay(const char* jsonInfo) {
        NSLog(@"🍎 开始支付(JSON方式)");
        
        if (!jsonInfo) return;
        
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        AccessBeginPayInfo *payInfo = [[AccessBeginPayInfo alloc] init];
        
        NSString *jsonStr = [NSString stringWithUTF8String:jsonInfo];
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        
        if (error) return;
        
        // 直接映射字段
        payInfo.productIdentifier = jsonDict[@"ProductId"] ? [NSString stringWithFormat:@"%@", jsonDict[@"ProductId"]] : @"";
        payInfo.price = jsonDict[@"Price"] ? [jsonDict[@"Price"] intValue] : 0;
        payInfo.currencyLocale = jsonDict[@"Currency"] ? [NSString stringWithFormat:@"%@", jsonDict[@"Currency"]] : @"";
        payInfo.notifyUrl = jsonDict[@"NotifyUrl"] ? [NSString stringWithFormat:@"%@", jsonDict[@"NotifyUrl"]] : @"";
        payInfo.gameInfo = jsonDict[@"GameInfo"] ? [NSString stringWithFormat:@"%@", jsonDict[@"GameInfo"]] : @"";
        
        NSLog(@"🍎 支付信息: productId=%@, price=%d", payInfo.productIdentifier, payInfo.price);
        [sdk pay:payInfo];
    }

    void _StartShare(int shareType, const char* title, const char* imagePath, const char* url) {
        NSLog(@"🍎 调用SDK分享");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        
        AccessShareInfo *shareInfo = [[AccessShareInfo alloc] init];
        shareInfo.title = [NSString stringWithUTF8String:title];
        shareInfo.imagePath = [NSString stringWithUTF8String:imagePath];
        shareInfo.linkPath = [NSString stringWithUTF8String:url];
        
        [sdk shareType:(THREE_SHARE_TYPE)shareType shareObject:shareInfo];
    }

    void _AccessParticipate(int activityType, const char* activityData) {
        NSLog(@"🍎 参与活动");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        
        AccessActivityDataInfo *activityDataInfo = [[AccessActivityDataInfo alloc] init];
        // 根据实际需求设置activityDataInfo的属性
        
        [sdk accessParticipate:(ACTIVITY_TYPE)activityType ActivityDataType:activityDataInfo];
    }

    void _OpenAccountCenter() {
        NSLog(@"🍎 打开账号中心");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        [sdk openAccountCenter];
    }

    void _OpenService() {
        NSLog(@"🍎 打开客服中心");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        [sdk openService];
    }
}
