//
//  AppDelegate.m
//  jiaPei
//
//  Created by apple on 15/11/2.
//  Copyright (c) 2015年 JCZ. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiManager.h"
#import <ZFPlayer/ZFLandscapeRotationManager.h>

@interface AppDelegate () <WXApiDelegate>
/// APP管理的导航栏的堆栈
@property (nonatomic, readwrite, strong) RQNavigationControllerStack *navigationControllerStack;
/// APP的服务层
@property (nonatomic, readwrite, strong) RQViewModelServicesImpl *services;
@end

@implementation AppDelegate

@synthesize window;

#pragma mark- 获取appDelegate
+ (AppDelegate *)sharedDelegate {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

//程序开始
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	[super application:application didFinishLaunchingWithOptions:launchOptions];
    
    /// 初始化UI之前配置
    [self rq_configureApplication:application initialParamsBeforeInitUI:launchOptions];
    
    // Config Service
    self.services = [[RQViewModelServicesImpl alloc] init];
    // Config Nav Stack
    self.navigationControllerStack = [[RQNavigationControllerStack alloc] initWithServices:self.services];
    
    // Configure Window
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    // 重置rootViewController
    [self.services resetRootViewModel:[self rq_createInitialViewModelWithFromType:RQSwitchRootViewControllerFromTypeLogin]];
    // 让窗口可见
    [self.window makeKeyAndVisible];
    
    // 初始化UI后配置
    [self rq_configureApplication:application initialParamsAfterInitUI:launchOptions];
    
#if defined(DEBUG)||defined(_DEBUG)
    /// 调试模式
    [self rq_configDebugModelTools];
#endif
    
    // Save the application version info. must write last
    [[NSUserDefaults standardUserDefaults] setValue:RQ_APP_VERSION forKey:RQApplicationVersionKey];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [RQ_AD_MANAGER loadMineSplashAd];
    
    
    
    

    return YES;
}





/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    ZFInterfaceOrientationMask orientationMask = [ZFLandscapeRotationManager supportedInterfaceOrientationsForWindow:window];
    if (orientationMask != ZFInterfaceOrientationMaskUnknow) {
        return (UIInterfaceOrientationMask)orientationMask;
    }
    /// 这里是非播放器VC支持的方向
    return UIInterfaceOrientationMaskPortrait;
}




- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
	
	// 通用链接

	if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {

		NSURL *url = userActivity.webpageURL;
		
		NSLog(@"通用链接 ：%@", url);
		
		if ([[url absoluteString] containsString:RQ_WECHAT_MANAGER.appID]) {
			return [WXApi handleOpenUniversalLink:userActivity
			delegate:RQ_WECHAT_MANAGER];
		} else if ([[url absoluteString] containsString:@"https://app.jppt.com.cn/JSJPStudent/"]) {
			return YES;
		}
		
		return NO;

	}
	
	return NO;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
	if ([url.host isEqualToString:@"safepay"]) {
		// 支付跳转支付宝钱包进行支付，处理支付结果
		[[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
			NSLog(@"result = %@",resultDic);
		}];
		
		// 授权跳转支付宝钱包进行支付，处理支付结果
		[[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
			NSLog(@"result = %@",resultDic);
			// 解析 auth code
			NSString *result = resultDic[@"result"];
			NSString *authCode = nil;
			if (result.length>0) {
				NSArray *resultArr = [result componentsSeparatedByString:@"&"];
				for (NSString *subResult in resultArr) {
					if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
						authCode = [subResult substringFromIndex:10];
						break;
					}
				}
			}
			NSLog(@"授权结果 authCode = %@", authCode?:@"");
		}];
	}
    /// 
	if ([[url absoluteString] containsString:RQ_WECHAT_MANAGER.appID]) {
		return  [WXApi handleOpenURL:url delegate:RQ_WECHAT_MANAGER];
	}
	return YES;
}

#pragma mark - 在初始化UI之前配置
- (void)rq_configureApplication:(UIApplication *)application initialParamsBeforeInitUI:(NSDictionary *)launchOptions {
    // 配置广告
    [RQ_AD_MANAGER rq_configureADSuiSDK];
    // 配置文件夹
    [self rq_configureApplicationDirectory];
    
    // 配置FMDB
    [self rq_configureFMDB];

    //  配置微信
    [self rq_configureWechat];
    
    // 配置键盘
    [self rq_configureKeyboardManager];
    
    
}



// 配置文件夹
- (void)rq_configureApplicationDirectory {
    /// 创建doc
    [RQFileManager createDirectoryAtPath:RQWeChatDocDirPath()];
    /// 创建cache
    [RQFileManager createDirectoryAtPath:RQWeChatCacheDirPath()];
    
    NSLog(@"RQWeChatDocDirPath is [ %@ ] \n RQWeChatCacheDirPath is [ %@ ]" , RQWeChatDocDirPath() , RQWeChatCacheDirPath());
}

/// 配置FMDB
- (void)rq_configureFMDB {
    
}

/// 检查题库版本
- (void)rq_configureQuestionUpdate {
    NSString *version = [[NSUserDefaults standardUserDefaults] valueForKey:RQApplicationVersionKey];
    if ([version isEqualToString:RQ_APP_VERSION]) {
        [RQ_YDTQuestion_Module rq_updateQuestion];
    }
}

- (void)rq_configureWechat {
    /// 向微信注册
    [RQ_WECHAT_MANAGER initWechatManager];
}

// 配置键盘管理器
- (void)rq_configureKeyboardManager {
    IQKeyboardManager.sharedManager.enable = YES;
    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
    IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = YES;
}


#pragma mark - 在初始化UI之后配置
- (void)rq_configureApplication:(UIApplication *)application initialParamsAfterInitUI:(NSDictionary *)launchOptions {
    /// 配置ActionSheet
    [LCActionSheet rq_configureActionSheet];
    
    /// 预先配置平台信息
//    [SBUMengService configureUMengPreDefinePlatforms];
    
    @weakify(self);
    /// 监听切换根控制器的通知
    [[RQNotificationCenter rac_addObserverForName:RQSwitchRootViewControllerNotification object:nil] subscribeNext:^(NSNotification * note) {
        /// 这里切换根控制器
        @strongify(self);
        // 重置rootViewController
        RQSwitchRootViewControllerFromType fromType = [note.userInfo[RQSwitchRootViewControllerUserInfoKey] integerValue];
        NSLog(@"fromType is  %zd" , fromType);
        /// 切换根控制器
        [self.services resetRootViewModel:[self rq_createInitialViewModelWithFromType:fromType]];
        
        

        /// 切换了根控制器，切记需要将指示器 移到window的最前面
#if defined(DEBUG)||defined(_DEBUG)
        [self.window bringSubviewToFront:[RQDebugTouchView sharedInstance]];
#endif
    }];
    
    /// 配置H5
//        [SBConfigureManager configure];
    
    /// 检查题库版本
    [self rq_configureQuestionUpdate];
    
    [RQ_AD_MANAGER loadAdWithAdType:RQADType_Splash customView:nil];
}

#pragma mark - 调试(DEBUG)模式下的工具条
- (void)rq_configDebugModelTools {    
    /// 打开调试按钮
    [RQDebugTouchView sharedInstance];
    /// RQ Fixed: 切换了根控制器，切记需要将指示器 移到window的最前面
    [self.window bringSubviewToFront:[RQDebugTouchView sharedInstance]];
    
}



#pragma mark - 创建根控制器
- (RQBaseViewModel *)rq_createInitialViewModelWithFromType:(RQSwitchRootViewControllerFromType)fromType {
    
    // The user has logged-in.
    NSString *version = [[NSUserDefaults standardUserDefaults] valueForKey:RQApplicationVersionKey];
    /// 版本不一样就先走 新特性界面
    if (![version isEqualToString:RQ_APP_VERSION]) {
        return [[RQNewFeatureViewModel alloc] initWithServices:self.services params:@{RQViewCommonValueKey : @"2022.05.13appƬͷ_x264"}];
    } else {
        switch (fromType) {
            case RQSwitchRootViewControllerFromTypeCancelLogin:
                return [[RQMainTabBarViewModel alloc] initWithServices:self.services params:nil];
                
            default: {
                /// 这里判断一下
//                if (RQStringIsEmpty(RQ_YDTQuestion_Module.car_type)) {
//                    return [[RQChooseExLibViewModel alloc] initWithServices:self.services params:@{RQViewCommonValueKey : @(YES)}];
//                } else {
                    return [[RQMainTabBarViewModel alloc] initWithServices:self.services params:nil];
//                    if ([SAMKeychain rawLogin] && RQ_USER_MANAGER.currentUser) {
//                        /// 有账号+有用户数据
//                        /// 已经登录，跳转到主页
//                        return [[RQMainTabBarViewModel alloc] initWithServices:self.services params:nil];
//                    } else if(RQ_USER_MANAGER.currentUser) {
//                        /// 没账号+有用户数据
//                        /// 跳转到账户登录页面
//                        return [[RQLoginViewModel alloc] initWithServices:self.services params:nil];
//                    } else {
//                        /// 第一次使用
//                        return [[RQLoginViewModel alloc] initWithServices:self.services params:nil];
//                    }
//                }
            }
        }
    }
}

@end
