#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "DCUniMP.h"
#import "UniappPlugin.h"
#import "WXApi.h"


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  // Override point for customization after application launch.
    
    
    // 配置参数
        NSMutableDictionary *options = [NSMutableDictionary dictionaryWithDictionary:launchOptions];
        // 设置 debug YES 会在控制台输出 js log,默认不输出 log,注:需要引入 liblibLog.a 库
        [options setObject:[NSNumber numberWithBool:YES] forKey:@"debug"];
        [DCUniMPSDKEngine initSDKEnvironmentWithLaunchOptions:options ];
        
        FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
        FlutterMethodChannel* uniAppChannel = [FlutterMethodChannel methodChannelWithName:@"min" binaryMessenger:(NSObject<FlutterBinaryMessenger> *)controller];
        UniappPlugin * plugin = [[UniappPlugin alloc] init];
        [DCUniMPSDKEngine setDelegate:plugin];
        [uniAppChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
            NSString * method = call.method;
            if ([method isEqual:@"initialize"] || [method isEqual:@"isInitialize"]) {
                result([NSNumber numberWithBool:YES]);
            }
            //是否已经解压过了
            if ([method isEqual:@"isExistsApp"]) {
                NSString * appid = [call.arguments valueForKey:@"appid"];
                [DCUniMPSDKEngine isExistsApp:appid] ? result([NSNumber numberWithBool:YES]): result([NSNumber numberWithBool:NO]);
            }
            if ([method isEqual:@"closeCurrentApp"]) {
                [DCUniMPSDKEngine closeUniMP];
            }
            if ([method isEqual:@"getAppBasePath"]) {
                NSString * appid = [call.arguments valueForKey:@"appid"];
                result([DCUniMPSDKEngine getAppRunPathWithAppid:appid]);
            }
            if ([method isEqual:@"runingAppid"]) {
                result([DCUniMPSDKEngine getActiveUniMPAppid]);
            }
            if ([method isEqual:@"currentPageUrl"]) {
                result([DCUniMPSDKEngine getCurrentPageUrl]);
            }
            if ([method isEqual:@"startMin"]) {
                NSLog(@"call.arguments:%@",call.arguments);
                NSString * appid = [call.arguments valueForKey:@"appid"];
                NSDictionary* dict = [call.arguments objectForKey:@"json"];
                [plugin openUniApp:appid dict:dict];
                result(@"");
            }
            if ([method isEqual:@"getAppVersionInfo"]) {
                NSString * appid = [call.arguments valueForKey:@"appid"];
                result([[DCUniMPSDKEngine getUniMPVersionInfoWithAppid:appid] valueForKey:@"name"]);
            }
            if ([method isEqual:@"reloadWgt"]) {
                NSString * appid = [call.arguments valueForKey:@"appid"];
                NSString * wgtPath = [call.arguments valueForKey:@"wgtPath"];
                BOOL r = [DCUniMPSDKEngine releaseAppResourceToRunPathWithAppid:appid resourceFilePath:wgtPath];
                r ? result([NSNumber numberWithBool:YES]) : result([NSNumber numberWithBool:NO]);
            }
            //这是原来的下载
            if ([call.method isEqual:@"openUniApp"]) {
                result(@"这是原来的下载。");
            }
            //result(FlutterMethodNotImplemented);
        }];
    
    // 消息内容获取
    __block NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"notification dic: %@", remoteNotification);
    
    FlutterMethodChannel* bridgeAppChannel = [FlutterMethodChannel methodChannelWithName:@"bridge" binaryMessenger:(NSObject<FlutterBinaryMessenger> *)controller];
    [bridgeAppChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        NSString * method = call.method;
        if ([method isEqual:@"action"]) {
            if (remoteNotification != NULL) {
                result(remoteNotification[@"custom"]);
                remoteNotification = nil;
            }
            result(@"");
        }
        if ([method isEqual:@"toAppStore"]) {
            NSString *appURL = @"https://itunes.apple.com/cn/app/1575124838?action=write-review";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]];
            result(@"");
        }
        //result(FlutterMethodNotImplemented);
    }];
    
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    NSLog(@"userActivity%@", userActivity.webpageURL);
    
    NSArray *params = [userActivity.webpageURL.query componentsSeparatedByString:@"&"];
    
    __block NSString *customParam = @"";
    
    for (NSString *string in params) {
        NSLog(@"userActivity%@", string);
        NSArray *array =[string componentsSeparatedByString:@"="];
        if ([array[0] isEqual:@"id"]) {
            customParam = [NSString stringWithFormat:@"{\"typed\":1,\"info\":\"%@\"}", array[1]];
        }
    }
    
    NSLog(@"userActivity%@", customParam);
    FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
    FlutterMethodChannel* bridgeAppChannel = [FlutterMethodChannel methodChannelWithName:@"bridge" binaryMessenger:(NSObject<FlutterBinaryMessenger> *)controller];
    [bridgeAppChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        NSString * method = call.method;
        if ([method isEqual:@"action"]) {
            if (customParam != NULL) {
                result(customParam);
                customParam = @"";
            }
            result(@"");
        }
        if ([method isEqual:@"toAppStore"]) {
            NSString *appURL = @"https://itunes.apple.com/cn/app/1575124838?action=write-review";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]];
            result(@"");
        }
        //result(FlutterMethodNotImplemented);
    }];
    // 通过通用链接唤起 App
    [DCUniMPSDKEngine application:application continueUserActivity:userActivity];
    return YES;
}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//    return [WXApi handleOpenURL:url delegate:[FluwxResponseHandler responseHandler]];
//}
//
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
//  return [WXApi handleOpenURL:url delegate:[FluwxResponseHandler responseHandler]];
//}

@end