#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工具函数：支持 NSDictionary 和 NSArray
    NSString* jsonStringWithObject(id obj) {
        if (!obj) return @"{}";
        if (![NSJSONSerialization isValidJSONObject:obj]) {
            NSLog(@"⚠️ 无法序列化对象：%@", obj);
            return @"{}";
        }
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
        if (jsonData) {
            return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        } else {
            NSLog(@"❌ JSON 转换失败：%@", error.localizedDescription);
            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 = jsonStringWithObject(dict);
    UnitySendMessage("SdkManager", "OnSdkInit", [json UTF8String]);
}

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

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

- (void)payError:(NSError *)error {
    NSLog(@"🍎 支付失败: %@", error.localizedDescription);
    NSString *errorMsg = [NSString stringWithFormat:@"pay_failed:%@", error.localizedDescription];
    UnitySendMessage("SdkManager", "OnSdkPay", [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];
    }
    NSString *json = jsonStringWithObject(array);
    UnitySendMessage("SdkManager", "OnPayGoodsList", [json UTF8String]);
}

- (void)payGpodsListFail {
    NSLog(@"🍎 获取商品列表失败");
    UnitySendMessage("SdkManager", "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 = jsonStringWithObject(dict);
    UnitySendMessage("SdkManager", "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 = jsonStringWithObject(dict);
    UnitySendMessage("SdkManager", "OnUserRefresh", [json UTF8String]);
}

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

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

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

- (void)shareFailed:(BOOL)result {
    NSLog(@"🍎 分享失败: %@", result ? @"YES" : @"NO");
    UnitySendMessage("SdkManager", "OnSdkShare", "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[@"extendAction"]);

        id extraObj = jsonDict[@"extra"];
        if (extraObj == nil || [extraObj isKindOfClass:[NSNull class]]) {
            playerInfo.extra = @"";
        } else if ([extraObj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = (NSDictionary *)extraObj;
            NSMutableArray *keyValuePairs = [NSMutableArray array];
            [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
                [keyValuePairs addObject:[NSString stringWithFormat:@"%@:%@", key, value]];
            }];
            playerInfo.extra = [keyValuePairs componentsJoinedByString:@";"];
        }
        
        [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];
    }
}
