// Alipay.mm

#import "Alipay.h"
#import <AlipaySDK/AlipaySDK.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
#import <React/RCTLog.h>

@implementation Alipay

// Define error messages
#define NOT_REGISTERED (@"registerApp required.")
#define INVOKE_FAILED (@"Alipay API invoke returns false.")

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE()

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:@"RCTOpenURLNotification" object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)handleOpenURL:(NSNotification *)aNotification
{
    NSString * aURLString =  [aNotification userInfo][@"url"];
    NSURL * aURL = [NSURL URLWithString:aURLString];
    
    if ([aURL.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:aURL standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [self sendPayResult:resultDic];
        }];
        return YES;
    }
    return NO;
}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup {
    return YES;
}

RCT_EXPORT_METHOD(registerApp:(NSString *)appId
                  :(NSString *)universalLink
                  :(RCTResponseSenderBlock)callback)
{
    if (appId && appId.length > 0) {
        if (universalLink && universalLink.length > 0) {
            [[AlipaySDK defaultService] registerApp:appId universalLink:universalLink];
        } else {
            [[AlipaySDK defaultService] registerApp:appId universalLink:nil];
        }
        callback(@[[NSNull null], @(YES)]);
    } else {
        callback(@[INVOKE_FAILED, @(NO)]);
    }
}

RCT_EXPORT_METHOD(pay:(NSString *)orderInfo
                  :(RCTResponseSenderBlock)callback)
{
    if (!orderInfo || orderInfo.length == 0) {
        callback(@[@"orderInfo cannot be empty"]);
        return;
    }
    
    // 获取应用配置的 scheme
    NSString *appScheme = [self getAppScheme];
    if (!appScheme || appScheme.length == 0) {
        callback(@[@"App scheme not configured. Please configure URL scheme in Info.plist"]);
        return;
    }
    
    [[AlipaySDK defaultService] payOrder:orderInfo fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        [self sendPayResult:resultDic];
        NSString *resultStatus = resultDic[@"resultStatus"];
        if ([resultStatus isEqualToString:@"9000"]) {
            callback(@[[NSNull null], resultDic]);
        } else {
            NSString *memo = resultDic[@"memo"] ?: @"支付失败";
            callback(@[memo, resultDic]);
        }
    }];
}

RCT_EXPORT_METHOD(getVersion:(RCTResponseSenderBlock)callback)
{
    NSString *version = [[AlipaySDK defaultService] currentVersion];
    callback(@[[NSNull null], version ?: @""]);
}

RCT_EXPORT_METHOD(isAlipayInstalled:(RCTResponseSenderBlock)callback)
{
    // 支付宝 SDK 没有直接提供判断是否安装的方法
    // 可以通过尝试打开支付宝 URL Scheme 来判断
    NSURL *alipayURL = [NSURL URLWithString:@"alipay://"];
    BOOL isInstalled = [[UIApplication sharedApplication] canOpenURL:alipayURL];
    callback(@[[NSNull null], @(isInstalled)]);
}

- (NSString *)getAppScheme
{
    NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"];
    for (NSDictionary *urlType in urlTypes) {
        NSArray *urlSchemes = urlType[@"CFBundleURLSchemes"];
        for (NSString *scheme in urlSchemes) {
            if (![scheme isEqualToString:@"alipay"] && ![scheme isEqualToString:@"alipays"]) {
                return scheme;
            }
        }
    }
    return nil;
}

- (void)sendPayResult:(NSDictionary *)resultDic
{
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    body[@"resultStatus"] = resultDic[@"resultStatus"] ?: @"";
    body[@"result"] = resultDic[@"result"] ?: @"";
    body[@"memo"] = resultDic[@"memo"] ?: @"";
    body[@"type"] = @"PayResult.Resp";
    
    [self.bridge.eventDispatcher sendDeviceEventWithName:@"Alipay_Resp" body:body];
}

@end

