//
//  AppDelegate.m
//  <%= appName %>
//
//  Created by EMAS on 2017/12/7.
//  Copyright © 2017年 EMAS. All rights reserved.
//

#import "AppDelegate.h"

// --自初始化头文件
#import <AliEMASConfigure/AliEMASConfigure.h>

// --基础库头文件
#import <UT/UTAnalytics.h>
#import <UT/AppMonitor.h>
#import <NetworkSDK/NetworkCore/NWNetworkConfiguration.h>
#import <NetworkSDK/NetworkCore/NetworkDemote.h>
#import <NetworkSDK/NetworkCore/NWuserLoger.h>
#import <NetworkSDK/AliReachability/NWLog.h>

// --ACCS头文件
#import <TBAccsSDK/TBAccsManager.h>

// --PUSH头文件
#if __has_include(<PushCenterSDK/TBSDKPushAPNSReceiver.h>)

#import <PushCenterSDK/TBSDKPushCenterConfiguration.h>
#import <PushCenterSDK/TBSDKPushCenterEngine.h>
#else
#endif

// --高可用头文件
#import <AliHAAdapter4poc/AliHAAdapter.h>
#import <AliHASecurity/AliHASecurity.h>
#import <TRemoteDebugger/TRDManagerService.h>
#import <TBRest/TBRestSendService.h>

// --网关头文件
#import <MtopSDK/MtopSDK.h>
#import <MtopCore/MtopService.h>
#import <MtopCore/TBSDKConfiguration.h>

#import "EMASWXSubSDKEngine.h"

#if __has_include(<WeexSDK/WeexSDK.h>)

#if __has_include(<DynamicConfigurationAdaptor/DynamicConfigurationAdaptorManager.h>)
// --weex灰度头文件
#import <DynamicConfigurationAdaptor/DynamicConfigurationAdaptorManager.h>
#else
#endif

// --ZCache
#if __has_include(<ZCache/ZCache.h>)
#import <ZCache/ZCache.h>
#else
#endif

#else
#endif

#if __has_include(<orange/Orange.h>)

// --远程配置
#import <orange/Orange.h>
#import <orange/OrangeLog.h>
#else
#endif

// --读取配置
#import "EMASService.h"



// --ViewController
#import "EMASHostViewController.h"
#import "EMASTabBarController.h"
#import "EMASNativeViewController.h"
#import "EMASBaseNavigationController.h"
#import "EMASWeexContainerService.h"
#import "EMASPortalViewController.h"

// --WindVane

#if __has_include(<WindVane/WindVane.h>)
#import "EMASWindVaneConfig.h"
#else
#endif

// Push
#import <UserNotifications/UserNotifications.h>
#import "PushReporter.h"


#if __has_include(<EmasSocial/XCOSocial.h>)
#import <EmasSocial/XCOSocial.h>
#else
#endif

#if __has_include(<EmasWeexComponents/EmasWeexComponents.h>)
#import <EmasWeexComponents/XSocialProtocol.h>
#else
#endif

#if __has_include(<AlicloudHotFixEmas/AlicloudHotFixEmas.h>)
#import <AlicloudHotFixEmas/AlicloudHotFixServiceEmas.h>

#if __has_include("HFXTestClass.h")
#import "HFXTestClass.h"
#else
#endif

#else
#endif

@interface MyPolicyCenter : NSObject <NWPolicyDelegate, CYLTabBarControllerDelegate>
@end

@implementation MyPolicyCenter

- (nullable NWPolicy *)queryPolicy:(nonnull NSString *)host
                        withScheme:(nonnull NSString *)scheme
                  withAcceleration:(BOOL)acceleration
                  withSuccessAisle:(BOOL)success {
    if ([host isEqualToString:[[EMASService shareInstance] ACCSDomain]] && acceleration==YES) {
        
        NSString *strategy = [[[EMASService shareInstance] IPStrategy] objectForKey:host];
        NSArray *ipPort = [strategy componentsSeparatedByString:@":"];
        if ([ipPort count] != 2)
        {
            return nil;
        }
        NSString *ip = [ipPort objectAtIndex:0];
        NSString *port = [ipPort objectAtIndex:1];
        NWAisle *aisle = [NWAisle new];
        aisle.protocol = @"http2";
        aisle.ip = ip;
        aisle.port = [port intValue];
        aisle.encrypt = YES;
        aisle.auth = YES;
        aisle.publickey = @"emas";
        
        NWPolicy *policy = [NWPolicy new];
        policy.type = kNWAislePolicy;
        policy.host = host;
        policy.aisles = @[ aisle ];
        
        return policy;
    }
    
    return nil;
}

- (nullable NSString *)queryScheme:(nonnull NSString *)host {
    // 如果需要对该域名的所有请求的url的scheme进行修改，可以在这里进行
    
    // 所有 www.abc.com 的域名使用 https
    if ([host isEqualToString:[[EMASService shareInstance] ACCSDomain]]) {
        return @"https";
    }
    // 所有 www.xyz.com 的域名使用 http
    if ([host isEqualToString:[[EMASService shareInstance] MTOPDomain]]) {
        return @"http";
    }
    // 没有需求的直接返回nil
    return nil;
}

- (nonnull NSString *)queryCname:(nonnull NSString *)host {
    return host;
}

- (void)updateAisleStatus:(nonnull NWAisle *)aisle
                 withHost:(NSString*)host
               withStatus:(NWAisleStatus)status {
    // do something
}

- (nullable NWPolicy *)queryPolicy:(nonnull NSString *)host {
    return nil;
}

@end

@interface AppDelegate () <UNUserNotificationCenterDelegate>
@property(nonatomic,strong) MyPolicyCenter *policyCenter;
#if __has_include(<AlicloudHotFixEmas/AlicloudHotFixEmas.h>)

@property (nonatomic, strong) AlicloudHotFixServiceEmas *hotfixService;
#else
#endif
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [AliEMASConfigure configure];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    // 0. 打开网络库日志
    [NWLog setLogLevel:NW_LOG_DEBUG];
    
    // 1. 先初始化基础库
    [self initCommonConfig];
    
    // 2. 初始化高可用，高可用依赖基础库和ACCS，因此高可用的初始化顺序为，基础库->ACCS->高可用
    [self initAccsConfig];
    [self initHAConfig];
    
    // 3. 初始化Weex，Weex依赖基础库、网关和高可用，因此Weex的初始化顺序为，基础库->高可用->网关->远程配置->ZCache->Weex
    //[self initRemoteConfig];
    [self initMtopConfig];
    [self initZCacheConfig];

    
    // 4. 初始化PUSH
    [self initPushConfig];
    
    [self initDyConfig];
    
    [self initShareModule];

#if __has_include(<WeexSDK/WeexSDK.h>)
    [EMASWXSubSDKEngine setup];
#else
#endif
    
#if __has_include(<WindVane/WindVane.h>)
    [EMASWindVaneConfig setUpWindVanePlugin];
#else
#endif
    
    [self showMainViewController];
#if __has_include(<AlicloudHotFixEmas/AlicloudHotFixEmas.h>)

    [self hotfixSdkInit];
#else
#endif
    return YES;
}


#if __has_include(<AlicloudHotFixEmas/AlicloudHotFixEmas.h>)
// 初始化热修复
- (void)hotfixSdkInit {
    self.hotfixService = [AlicloudHotFixServiceEmas sharedInstance];
    [self.hotfixService setLogEnabled:YES];
    [self.hotfixService setServerURL:[[EMASService shareInstance] HotfixServerURL]];
    [self.hotfixService initWithAppId:[[EMASService shareInstance] appkey] appSecret:[[EMASService shareInstance] appSecret] callback:^(BOOL res, id data, NSError *error) {
        if (res) {
            NSLog(@"HotFix SDK init success.");
        } else {
            NSLog(@"HotFix SDK init failed, error: %@", error);
        }
    }];
    
#if __has_include(<AlicloudHotFixEmas/AlicloudHotFixEmas.h>)
#if __has_include("HFXTestClass.h")
    [self.hotfixService loadPatch:^(BOOL res, id data, NSError *error) {
        NSString *msg;
        if (res) {
            msg = @"Load patch success.";
            HFXTestClass *testClass = [[HFXTestClass alloc] init];
            
            NSLog(@"🔴类名与方法名：%@（在第%@行），描述：%@", @(__PRETTY_FUNCTION__), @(__LINE__), [testClass output]);
            if ([[testClass output] isEqualToString:@"1"]) {
                dispatch_async(dispatch_get_main_queue(),^{
                    [[self cyl_tabBarController].tabBar.items enumerateObjectsUsingBlock:^(UITabBarItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (idx == 0) {
                            obj.title = @"热更新1";
                        } else if (idx==1) {
                            obj.title = @"热更新2";
                        }
                        [obj setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateNormal];
                        [obj setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]} forState:UIControlStateSelected];
                    }];
                });
            }
        } else {
            msg = [NSString stringWithFormat:@"Load patch failed, data: %@ , error: %@" , data ,error];
        }
        NSLog(@"🔴类名与方法名：%@（在第%@行），描述：%@ data:%@", @(__PRETTY_FUNCTION__), @(__LINE__), msg, data);
    }];
#else
#endif
#else
#endif
}
#else
#endif

- (void)initShareModule {
#if __has_include(<EmasSocial/XCOSocial.h>)
    // 分享初始化
    [[XCOSocial sharedInstance] initUMWithUMAppKey:@"5aa61b67a40fa34fa5000055" appSecrete:nil];
    [[XCOSocial sharedInstance] setPlaform:UMSocialPlatformType_QQ appKey:@"1106736506" appSecret:@"ywLBbVIlh1q2yG5G" redirectURL:@"http://mobile.umeng.com/social"];
    [[XCOSocial sharedInstance] setPlaform:UMSocialPlatformType_Sina appKey:@"367450010" appSecret:@"98f348c6d83e709217353f43a2db43f0" redirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    [[XCOSocial sharedInstance] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx2966bd6a5d307e57" appSecret:@"89f3b7871e90417100f9f4d2aad7e402" redirectURL:@"http://mobile.umeng.com/social"];
#else
#endif
}

#pragma mark -
#pragma mark 显示视图

- (void)showMainViewController {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    NSNumber *tabSizeNumber = [[EMASWeexContainerService shareInstance] tabSize];
    NSInteger integerValue = tabSizeNumber.integerValue;
    
    if (integerValue >= 2) {
        //weex脚手架
        NSNumber *tabSize = [[EMASWeexContainerService shareInstance] tabSize];
        NSInteger tabSizeInt = tabSize.integerValue;
        [self showTabBarViewController];
    } else {
        //Native脚手架
        [self showNativeViewController];
    }
}

- (void)showNativeViewController {
   //storyboard已初始化

}

- (void)showTabBarViewController {
    EMASTabBarController *tabBarViewController = [[EMASTabBarController alloc] init];
    tabBarViewController.delegate = self;
    [self.window setRootViewController:tabBarViewController];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
}

- (void)showBlankViewController {
    EMASNativeViewController *viewController = [[EMASNativeViewController alloc] initWithNavigatorURL:[NSURL URLWithString:@"http://cdn.emas-poc.com/material/yanpeicpf/index.html?_wx_tpl=http://cdn.emas-poc.com/app/yanpeicpf-bbb/pages/index/entry.js"]];
    self.window.rootViewController = [[EMASBaseNavigationController alloc] initWithRootViewController:viewController];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
}

#pragma mark -
#pragma mark SDK初始化

// 基础库
- (void)initCommonConfig {
    NSString *scheme = @"https";
    if ([[EMASService shareInstance] useHTTP]) {
        scheme = @"http";
    }
    
    // UT初始化部分
    [[UTAnalytics getInstance] turnOffCrashHandler];
    [[UTAnalytics getInstance] turnOnDebug]; // 打开调试日志
    [[UTAnalytics getInstance] setTimestampHost:[[EMASService shareInstance] HATimestampHost] scheme:scheme];
    [[UTAnalytics getInstance] setAppKey:[[EMASService shareInstance] appkey] secret:[[EMASService shareInstance] appSecret]];
    [[UTAnalytics getInstance] setChannel:[[EMASService shareInstance] ChannelID]];
    [[UTAnalytics getInstance] setAppVersion:[[EMASService shareInstance] getAppVersion]];
    [AppMonitor disableSample]; // 调试使用，上报不采样，建议正式发布版本不要这么做
}

// ACCS
- (void)initAccsConfig {
    // ACCS初始化部分
    void tbAccsSDKSwitchLog(BOOL logCtr);
    tbAccsSDKSwitchLog(YES); // 打开调试日志
    
    // ACCS 通过配置文件自初始化
    TBAccsManager *accsManager = [TBAccsManager accsManagerByConfigureName:nil];
    [accsManager startAccs];
    
    [accsManager bindAppWithAppleToken: nil
                              callBack:^(NSError *error, NSDictionary *resultsDict) {
                                  if (error) {
                                      NSLog(@"\n\n绑定App出错了 %@\n\n", error);
                                  }
                                  else {
                                      NSLog(@"\n\n绑定App成功了\n\n");
                                  }
                              }];
}

// PUSH
- (void)initPushConfig {
#if __has_include(<PushCenterSDK/TBSDKPushAPNSReceiver.h>)
    // PUSH 通过配置文件自初始化
    TBSDKPushCenterEngine *pce = [TBSDKPushCenterEngine sharedInstanceWithDefaultConfigure];
    [TBSDKPushCenterConfiguration shareInstance].scheduleLocalNotificationWhenAppBackground = NO;
    [pce start];
#else
#endif
    // register notification setting
    [self registerNotificationSetting];
}

- (void)registerNotificationSetting {
    dispatch_async(dispatch_get_main_queue(),^{
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if(error) {
                    NSLog( @"Push registration FAILED" );
                    NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
                    NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
                    return;
                }
                
                [[UIApplication sharedApplication] registerForRemoteNotifications];
                NSLog( @"Push registration success." );
            }];
        } else {
            [[UIApplication sharedApplication] registerUserNotificationSettings:
             [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                               categories:nil]];
            
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            
            NSLog(@"[APNS] registerNotificationSetting");
        }
    });
}

//-- 高可用
- (void)initHAConfig {
    NSString *scheme = @"https";
    if ([[EMASService shareInstance] useHTTP]) {
        scheme = @"http";
    }
    
    // 高可用初始化部分
    // 如果需要重公钥，请一定要放到初始化前！！！
    NSString *rasPublicKey = [[EMASService shareInstance] HARSAPublicKey];
    if (rasPublicKey.length) {
        [[AliHASecurity sharedInstance] initWithRSAPublicKey:rasPublicKey];
    }
    [AliHAAdapter initWithAppKey:[[EMASService shareInstance] appkey]
                      appVersion:[[EMASService shareInstance] getAppVersion]
                         channel:[[EMASService shareInstance] ChannelID]
                         plugins:nil
                            nick:@"emas-ha"]; // nick根据app实际情况填写
    [AliHAAdapter configOSS:[[EMASService shareInstance] HAOSSBucketName]];
    [AliHAAdapter setupAccsChannel:[[EMASService shareInstance] ACCSDomain] serviceId:[[EMASService shareInstance] HAServiceID]];
    [AliHAAdapter setupRemoteDebugRPCChannel:[[EMASService shareInstance] HAUniversalHost] scheme:scheme];
    
    TBRestConfiguration *restConfiguration = [[TBRestConfiguration alloc] init];
    restConfiguration.appkey = [[EMASService shareInstance] appkey];
    restConfiguration.appVersion = [[EMASService shareInstance] getAppVersion];
    restConfiguration.channel = [[EMASService shareInstance] ChannelID];
    restConfiguration.usernick = @"emas-ha"; // nick根据app实际情况填写
    if ([[EMASService shareInstance] useHTTP]) {
        restConfiguration.dataUploadScheme = @"http";
    }
    restConfiguration.dataUploadHost = [[EMASService shareInstance] HAUniversalHost];
    [[TBRestSendService shareInstance] configBasicParamWithTBConfiguration:restConfiguration];
}

// 网关
- (void)initMtopConfig {
    // MTOP初始化部分
    TBSDKConfiguration *config = [TBSDKConfiguration shareInstanceDisableDeviceID:YES andSwitchOffServerTime:YES];
    config.environment = TBSDKEnvironmentRelease;
    if ([[EMASService shareInstance] useHTTP]) {
        config.enableHttps = NO;
    }
    config.safeSecret = NO;
    config.appKey = [[EMASService shareInstance] appkey];
    config.appSecret = [[EMASService shareInstance] appSecret];
    config.wapAPIURL = [[EMASService shareInstance] MTOPDomain];//设置全局自定义域名
    config.wapTTID = [[EMASService shareInstance] ChannelID]; //渠道ID
    openSDKSwitchLog(YES); // 打开调试日志
}

- (void)initZCacheConfig {
#if __has_include(<WeexSDK/WeexSDK.h>)

#if __has_include(<ZCache/ZCache.h>)

#ifdef DEBUG
    [ZCache setDebugMode:YES]; // 打开调试日志
#endif
    [ZCache setupWithMtop];
    [ZCache defaultCommonConfig].packageZipPrefix = [[EMASService shareInstance] ZCacheURL];
#else
#endif
#else
#endif
}

// -- dy 初始化
- (void)initDyConfig {
#if __has_include(<WeexSDK/WeexSDK.h>)
    NSString * logicIdentifier = [NSString stringWithFormat:@"%@@%@",[[EMASService shareInstance] appkey],[self isDeviceIphone]?@"iphoneos":@"iPad"];
    [[DynamicConfigurationAdaptorManager sharedInstance] setUpWithMaxUpateTimesPerDay:10 AndIdentifier:logicIdentifier];
#else
#endif
}

// 初始化Orange

- (void)initRemoteConfig {
#if __has_include(<orange/Orange.h>)
    EMASService *service = [EMASService shareInstance];
    openOrangeLog(OrangeLogLevel_ALL);
    [Orange setOrangeDataCenterOnlineHost:service.RemoteConfigHost debugHost:service.RemoteConfigHost dailyHost:service.RemoteConfigHost];
    [Orange setOrangeBetaModeAccsHost:@[service.ACCSDomain,service.ACCSDomain,service.ACCSDomain]];
    [Orange runMode:OrangeUpateModeEvent];
#else
#endif
}

- (void)initPushParameters {
#if __has_include(<PushCenterSDK/TBSDKPushAPNSReceiver.h>)
    NSString *deviceTokenString = [[TBSDKPushCenterEngine shareInstance] getDeviceID];
    NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.emas.demo.push"];
    [sharedDefaults setObject:[[EMASService shareInstance] appkey] forKey:@"TB_PUSH_EXTENSION_APPKEY"];
    [sharedDefaults setObject:deviceTokenString ?: @"" forKey:@"TB_PUSH_EXTENSION_AGOO_TOKEN"];
    
    AliEMASEnvironment environment = [AliEMASConfigure defaultConfigure].options.environment;
    if (environment == AliEMASEnvironmentDaily) {
        [sharedDefaults setObject:@"http://aserver-pre-k8s.emas-poc.com:30080/agooack/apns" forKey:@"TB_PUSH_EXTENSION_AGOO_REPORT_HOST"];
    } else if (environment == AliEMASEnvironmentReleaseDebug) {
        [sharedDefaults setObject:@"http://aserver-pre-k8s.emas-poc.com:30080/agooack/apns" forKey:@"TB_PUSH_EXTENSION_AGOO_REPORT_HOST"];
    } else {
        [sharedDefaults setObject:@"http://aserver.emas-poc.com/agooack/apns" forKey:@"TB_PUSH_EXTENSION_AGOO_REPORT_HOST"];
    }
    [sharedDefaults synchronize];
#else
#endif
}

#pragma mark -
#pragma mark app生命周期

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 收到APNS token时回调
    NSLog(@"[APNS] device token: %@", deviceToken);
#if __has_include(<PushCenterSDK/TBSDKPushAPNSReceiver.h>)

    TBSDKPushCenterEngine *pce = [TBSDKPushCenterEngine sharedInstanceWithDefaultConfigure];
    [pce upLoaderDeviceToken:deviceToken userInfo:nil callback:^(NSDictionary *result, NSError *error){
        if ( error ) {
            NSLog(@"[APNS] update token error: %@", error);
        } else {
            [self initPushParameters];
            NSLog(@"[APNS] update token successfully!");
        }
    }];
#else
#endif
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"[APNS] register error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@">>>>>>> [AGOO MESSAGE]: %@", userInfo);
    
    NSString *text = [userInfo description];
    if ( !text ) {
        text = @"消息解析失败!";
    }

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AGOO 消息" message:text delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [alert show];
    
    NSString *messageId = [userInfo objectForKey:@"m"];
    if (messageId.length > 0) {
        [PushReporter reportMessageTaped:messageId];
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    
    NSLog(@">>>>>>> [AGOO MESSAGE]: %@", userInfo);

    NSString *text = [userInfo description];
    if ( !text ) {
        text = @"消息解析失败!";
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AGOO 消息" message:text delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [alert show];
    
    NSString *messageId = [userInfo objectForKey:@"m"];
    if (messageId.length > 0) {
        [PushReporter reportMessageTaped:messageId];
    }
}

#pragma mark - distinguish device
- (BOOL) isDeviceIphone {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return NO;
    }
    return YES;
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result;
#if __has_include(<EmasSocial/XCOSocial.h>)
    result = [[XCOSocial sharedInstance] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
    }
#else
#endif
    return result;

}

- (void)startSplashScreen {
    // Load launch image
    NSString *launchImageName;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        NSLog(@"%f", [UIScreen mainScreen].bounds.size.height);
        if ([UIScreen mainScreen].bounds.size.height >= 480) launchImageName = @"LaunchImage-700@2x.png"; // iPhone 4/4s, 3.5 inch screen
        if ([UIScreen mainScreen].bounds.size.height >= 568) launchImageName = @"LaunchImage-700-568h@2x.png"; // iPhone 5/5s, 4.0 inch screen
        if ([UIScreen mainScreen].bounds.size.height >= 667) launchImageName = @"LaunchImage-800-667h@2x.png"; // iPhone 6, 4.7 inch screen
        if ([UIScreen mainScreen].bounds.size.height >= 736) launchImageName =  @"LaunchImage-800-Portrait-736h@3x.png"; // iPhone 6+, 5.5 inch screen
        if ([UIScreen mainScreen].bounds.size.height >= 812) {
            if ([UIImage imageNamed:@"LaunchImage-1100-Portrait-2436h@3x.png"]) {
                launchImageName = @"LaunchImage-1100-Portrait-2436h@3x.png";
            }
        }
        
    }
    else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        if ([UIScreen mainScreen].scale == 1) launchImageName = @"LaunchImage-700-Portrait~ipad.png"; // iPad 2
        if ([UIScreen mainScreen].scale == 2) launchImageName = @"LaunchImage-700-Portrait@2x~ipad.png"; // Retina iPads
    }
    
    UIImageView* splashView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:launchImageName]];
    
    splashView.contentMode = UIViewContentModeScaleAspectFill;
    splashView.frame = [[UIScreen mainScreen] bounds];
    
    UIImageView *iconImageView = [UIImageView new];
    UIImage *icon = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"xdemo_icon" ofType:@"png"]];
    
    iconImageView.image = icon;
    
    iconImageView.frame = CGRectMake(0, 0, 147, 185);
    iconImageView.contentMode = UIViewContentModeScaleAspectFit;
    iconImageView.center = splashView.center;
    [splashView addSubview:iconImageView];
    
    [self.window addSubview:splashView];
    
    float animationDuration = 1.4;
    CGFloat shrinkDuration = animationDuration * 0.3;
    CGFloat growDuration = animationDuration * 0.7;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        [UIView animateWithDuration:shrinkDuration delay:1.0 usingSpringWithDamping:0.7f initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.75, 0.75);
            iconImageView.transform = scaleTransform;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:growDuration animations:^{
                CGAffineTransform scaleTransform = CGAffineTransformMakeScale(20, 20);
                iconImageView.transform = scaleTransform;
                splashView.alpha = 0;
            } completion:^(BOOL finished) {
                [splashView removeFromSuperview];
            }];
        }];
    } else {
        [UIView animateWithDuration:shrinkDuration delay:1.0 options:0 animations:^{
            CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.75, 0.75);
            iconImageView.transform = scaleTransform;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:growDuration animations:^{
                CGAffineTransform scaleTransform = CGAffineTransformMakeScale(20, 20);
                iconImageView.transform = scaleTransform;
                splashView.alpha = 0;
            } completion:^(BOOL finished) {
                [splashView removeFromSuperview];
            }];
        }];
    }
}

@end

