//
//  AppDelegate.m
//  OffcnIMSDKiOS
//
//  Created by vockey on 2018/7/25.
//  Copyright © 2018年 中公教育. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "OffcnIMSDKiOS.h"
#import "OffcnIMSocketManager.h"
#import "OffcnIMZYJFMDBHandler.h"
#import "AppDelegate+OffcnIMPush.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    UINavigationController *mainVC = [[UINavigationController alloc] initWithRootViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController]];
    
    mainVC.navigationBar.translucent = NO;
    self.window.rootViewController = mainVC;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    //中公直播使用测试环境设置为YES，正式环境设置为NO或者去掉这个配置
    NSNumber *changeEnvironment = [[NSUserDefaults standardUserDefaults] valueForKey:kOffcnIMSDKiOS_changeEnvironment];
    NSLog(@"changeEnvironment---%@",changeEnvironment);
    [OffcnIMSDKiOS defaultService].isTest = [changeEnvironment boolValue];
    
    
    //获取用户相关数据库，该方法在登陆或者第一次启动已登陆下执行
    [[OffcnIMZYJFMDBHandler sharedInstance] getUserDB];
    //推送
    [AppDelegate registerOffcnUserNotificationSettingsWithApplication:application options:launchOptions];
    //获取网络状态和内部初始化处理
    [[OffcnIMSDKiOS defaultService] startNotifierUseRealReachability];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}


- (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 {
    if ([OffcnIMSocketManager defaultService].IMConnectStatus != OffcnIMConnectStatusSuccess) {
        //建立连接
//        [[OffcnIMSocketManager defaultService] connectIMServerWithAccount_id:@"ce0819db8391f1e7258a71cc9e2c3235" token:@"fadbce3f4929b6bdee0617fee34e32ae"];
    }
    
    //进入前台,清除推送角标
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [application cancelAllLocalNotifications];
//    [JPUSHService setBadge:0];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    //断开连接
    [[OffcnIMSocketManager defaultService] disConnectIMServer];
}

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler{

}


/**
 *  远程推送注册成功
 *
 *  @param deviceToken deviceToken
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    // 25bb75ac 3ffcebd7 90d9f517 1ebca904 154a367a 87781e5d b9ea288e 37fdf487
    NSLog(@"-----deviceToken ---- ---- %@ devDesc ---%@", deviceToken,deviceToken.description);
    
    NSString *str = [AppDelegate hexStringForData:deviceToken];
    [OffcnIMSDKiOS defaultService].deviceToken = str;
    NSLog(@"token--- %@",str);
    //注册成功，返回token
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"APNS返回的Token:" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    //    applicationIconBadgeNumber
}

/**
 *  注册失败
 *
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    NSLog(@"注册失败 ---- %@",error);
    NSString *tokenStr = [NSString stringWithFormat:@"%@",error];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注册失败!" message:tokenStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    NSLog(@"注册失败%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"接收到远程推送通知Background ---- %@", userInfo);
    [AppDelegate didReceiveRemoteNotification:userInfo];
    
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
//        [self pushNotificationDefaultController];
    }
    // Required, iOS 7 Support
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    NSLog(@"接收到远程推送通知 ---- %@", userInfo);
    [AppDelegate didReceiveRemoteNotification:userInfo];
    
    /*
     "message" : "您的车辆京KKKKKK于2016-4-22 驶入邯郸",
     "aps" : {
        "alert" : "This is some fancy message.",
        "badge" : 1,
        "sound" :  "您的车辆京KKKKKK于2016-4-22 驶入邯郸"
     };
     
     */
    
    //    application.applicationIconBadgeNumber -=1;
    //将推送消息以alert形式呈现
    NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    
    UILocalNotification *backgroudMsg = [[UILocalNotification alloc] init];
    if (backgroudMsg) {
        backgroudMsg.timeZone = [NSTimeZone defaultTimeZone];
        backgroudMsg.alertBody = @"VoIP来电";
        backgroudMsg.alertAction = @"查看";
        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        backgroudMsg.userInfo = infoDic;
        [[UIApplication sharedApplication] presentLocalNotificationNow:backgroudMsg];
        //[self cerateAVAudioPlayer];
    }
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"接收到本地推送通知 ---- %@", notification.userInfo);
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    
    NSLog(@"ls---- %@",notificationSettings);
    
    // 2.注册远程通知
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)(void))completionHandler{
    
    NSLog(@"ios9新增 --- %@ -- %@ --- %@",identifier,userInfo,responseInfo);
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)(void))completionHandler{
    
    NSLog(@"ios8新增 --- %@ -- %@ --- %@",identifier,userInfo,application);
}

@end
