#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("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];
    }
    NSString *json = jsonStringWithObject(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 = jsonStringWithObject(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 = jsonStringWithObject(dict);
    UnitySendMessage("PlatformCallback", "OnUserRefresh", [json UTF8String]);
}

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

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

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

- (void)shareFailed:(BOOL)result {
    NSLog(@"🍎 分享失败: %@", result ? @"YES" : @"NO");
    UnitySendMessage("PlatformCallback", "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:@";"];
        }else if ([extraObj isKindOfClass:[NSString class]]) {
            playerInfo.extra = (NSString *)extraObj;
        }
        [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[@"itemId"] ? [NSString stringWithFormat:@"%@", jsonDict[@"itemId"]] : @"";
        payInfo.price = jsonDict[@"amount"] ? [jsonDict[@"amount"] intValue] : 0;
        payInfo.currencyLocale = jsonDict[@"currency"] ? [NSString stringWithFormat:@"%@", jsonDict[@"currency"]] : @"";
        payInfo.notifyUrl = jsonDict[@"notifyUrl"] ? [NSString stringWithFormat:@"%@", jsonDict[@"notifyUrl"]] : @"";
        payInfo.gameInfo = jsonDict[@"callbackInfo"] ? [NSString stringWithFormat:@"%@", jsonDict[@"callbackInfo"]] : @"";

        NSLog(@"🍎 支付信息: productId=%@, price=%d", payInfo.productIdentifier, payInfo.price);
        [sdk pay:payInfo];
    }

    void _StartShare(int platformType, int shareType, const char* jsonInfo) {
        NSLog(@"🍎 调用SDK分享");
        AccessCoreSdk *sdk = [AccessCoreSdk shareAccessCoreSdkManage];
        
        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;
        
        AccessShareInfo *shareInfo = [[AccessShareInfo alloc] init];
        shareInfo.title = [NSString stringWithFormat:@"%@", jsonDict[@"title"]];
        shareInfo.imagePath = [NSString stringWithFormat:@"%@", jsonDict[@"picPath"]];
        shareInfo.linkPath  = [NSString stringWithFormat:@"%@", jsonDict[@"shareUrl"]];
        
        switch (platformType) {
            case 1:
                [sdk shareType:ACCESS_SCENESESSION shareObject:shareInfo];
                break;
            case 2:
                [sdk shareType:ACCESS_SCENETIMELINE shareObject:shareInfo];
                break;
            case 4:
                [sdk shareType:ACCESS_SCENEQQTOSESSION shareObject:shareInfo];
                break;
            case 7:
                [sdk shareType:ACCESS_SCENEQQTOQZONE shareObject:shareInfo];
                break;
        }
    }

    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];
    }
}
