//
//  AppDelegate.m
//  TianLing_App
//
//  Created by 刘荣毅 on 2017/10/20.
//  Copyright © 2017年 Liu. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabBarViewController.h"
//#import "JX_WriteServerAddressViewController.h"
#import "JX_NewLoginViewController.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

//#import "EMSDK.h"
#import "IQKeyboardManager.h"
#import <WebKit/WebKit.h>


@interface AppDelegate ()<EMChatManagerDelegate,EMClientDelegate,UNUserNotificationCenterDelegate>
/// web
@property (nonatomic, strong) WKWebView *tempWebView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    /**
     *  睡眠1s
     **/
    [NSThread sleepForTimeInterval:1.0];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
//    //设置服务器地址
//  kHostURL = [[NSUserDefaults standardUserDefaults] objectForKey:@"serverAddress"] ;
//    DLog(@"z启动处的主机地址 === %@",kHostURL);
    
    
    
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor = [UIColor whiteColor];
    // 本地没有userId进入登录界面
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] == nil || [[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"] == nil) {
//        JX_LoginViewController *loginVC = [[JX_LoginViewController alloc]init];
        JX_NewLoginViewController *loginVC = [[JX_NewLoginViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        self.window.rootViewController = nav;
    }
    else{
        
        MainTabBarViewController *mainTabBar = [MainTabBarViewController new];
        // 如果是免登录状态，进去要做自动登录
        mainTabBar.isAutoLogin = YES;
        self.window.rootViewController = mainTabBar;
        
    }
    [_window makeKeyAndVisible];
    
    /**
     注册通知
     */
    [self registerNotification:application];
    
        /****************** 环信  ******************/
    
    
    // 注册环信SDK以及推送证书
    [self request_hx_configWithApplication:application Options:launchOptions finishBlock:nil];
    
    /**
     *  替换webview的userAgment
     **/
    self.tempWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
    [self.tempWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable userAgent, NSError * _Nullable error) {
        NSString * oldAgent = userAgent;
        NSString * newAgent = oldAgent;
        
        if (![oldAgent hasSuffix:@"myApps/mobile"])
        {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];//获取app版本信息
            NSLog(@"%@",infoDictionary);  //这里会得到很对关于app的相关信息
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            newAgent = [oldAgent stringByAppendingString:[NSString stringWithFormat:@"/myApps/mobile/iOS/%@", app_Version]];
        }
        //    NSLog(@"new agent :%@", newAgent);
        NSDictionary * dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    
    return YES;
}



- (void)request_hx_configWithApplication:(UIApplication *)application Options:(NSDictionary *)launchOptions finishBlock:(void(^)(void))haveDataBlock {
    __weak typeof(self) weakSelf = self;
    [HttpClient getWithURL:HXCONFIG_URL parameter:[NSMutableDictionary dictionary] success:^(id JSON) {
        __strong typeof(&*self) strongSelf = weakSelf;
        /*
         dict:
             {
             message = "ok",
             data =     {
                 client_secret = "YXA6wvmEKj6c47TMIdEQWrRD5_8ef2E",
                 open = "0",
                 app_key = "1136200508181603#myapps",
                 grant_type = "client_credentials",
                 org_name = "1136200508181603",
                 app_name = "myapps",
                 client_id = "YXA6AEPPWqmhT0qFbqkKfOMn5A",
             },
             status = 0,
         }
         */
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:JSON options:0 error:nil];
        
//        UIAlertController* alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"版本: %@ \n AppKey: %@ \n userId: %@ \n推送证书名称: %@", @"1.1.4",dict[@"data"][@"app_key"], [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"], @"tianling_push_cer"]
//                                                                       message:[NSString stringWithFormat:@"访问地址: \n%@%@ \n\n%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"server"], HXCONFIG_URL, dict]
//                                                                preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel
//                                                             handler:^(UIAlertAction * action) {
//        }];
//
//        [alert addAction:cancelAction];
//        [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        
        NSLog(@"\n-------dict-------\n%@",dict);
        if ([dict[@"status"] integerValue] == 0) {
            [strongSelf registerEaseSDKWithApplication:application Options:launchOptions hxConfig:dict[@"data"]];
        }
        
    } failure:^(NSError *error) {

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
}


- (void)registerEaseSDKWithApplication:(UIApplication *)application Options:(NSDictionary *)launchOptions hxConfig:(NSDictionary *)hxConfig {
    
    if (hxConfig[@"app_key"] == nil || [hxConfig[@"app_key"] isKindOfClass:[NSNull class]]) {
        return;
    }
    /* 更换前的AppKey @"1180171101178675#com-tlin-jarod-tlin" */
    [[EaseSDKHelper shareHelper] hyphenateApplication:application
                        didFinishLaunchingWithOptions:launchOptions
                                               appkey:hxConfig[@"app_key"]/*@"1136200508181603#myapps"*/
                                         apnsCertName:@"tianling_push_cer"// 推送证书名称
                                          otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES],@"easeSandBox":@NO}];
    
    //    EMOptions *options = [EMOptions optionsWithAppkey:@"1136200508181603#myapps"];
    //    options.apnsCertName = @"tianling_push_cer";
    //    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [ChatUIHelper shareHelper];// 初始化环信相关回调
    
    // 初始化web缓存配置, appkey需要自己去LeanCloud官网注册存储服务
    // http://www.imgeek.org/article/825308536
    [UserWebManager config:launchOptions
                     appId:@"utUG5ot9Y64dqJIFG9Ir2rqu-gzGzoHsz"
                    appKey:@"IbHhNkPo4gfrFFc3epCw3eG2"];
    
    
    NSString *userNameIDStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    NSString *userNameStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    NSString *pwd = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
    
    if (userNameIDStr && userNameStr) {
        // 因为设置了自动登录模式：[[EMClient sharedClient].options setIsAutoLogin:YES];
        // 所以，登录之前要先注销之前的用户，否则重复登录会抛异常
        //        EMError *error = [[EMClient sharedClient] logout:YES];
        //        if (!error) {
        //            NSLog(@"退出成功");
        //        }
        
        //    [self showHudInView:self.view hint:@"Loading..."];
        [[EMClient sharedClient] loginWithUsername:userNameIDStr password:pwd completion:^(NSString *aUsername, EMError *aError) {
            
            //        [self hideHud];
            
            if (aError) {
                //            [self showHint:aError.errorDescription];
                if (aError.code == EMErrorUserAlreadyLogin) {
                    //发送自动登陆状态通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
                } else {
                    NSLog(@"登录报错了：%@",aError.errorDescription);
                }
                return ;
            }
            
            
            NSString *userOpenId = userNameIDStr;// 用户环信ID
            NSString *nickName = userNameStr;// 用户昵称
            NSString *avatarUrl = @"http://avatar.csdn.net/E/8/5/2 ... %3B";// 用户头像（绝对路径）
            
            // 登录成功后，如果后端云没有缓存用户信息，则新增一个用户
            [UserWebManager createUser:userOpenId nickName:nickName avatarUrl:avatarUrl];
            
            //设置是否自动登录
            [[EMClient sharedClient].options setIsAutoLogin:YES];
            //            [[ChatUIHelper shareHelper] asyncGroupFromServer];
            [[ChatUIHelper shareHelper] asyncConversationFromDB];
            [[ChatUIHelper shareHelper] asyncPushOptions];
            
            //发送自动登陆状态通知
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
            
        }];
        
    }
}


#pragma mark - 注册通知
- (void)registerNotification:(UIApplication *)application {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //iOS10特有
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        // 必须写代理，不然无法监听通知的接收与点击
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 点击允许
                NSLog(@"注册成功");
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    NSLog(@"%@", settings);
                }];
            } else {
                // 点击不允许
                NSLog(@"注册失败");
            }
        }];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >8.0){
        //iOS8 - iOS10
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];
        
    }else if ([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
        //iOS8系统以下
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
    }
    // 注册获得device Token
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}



- (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.
    
        /****************** 环信  ******************/
     [[EMClient sharedClient] applicationDidEnterBackground: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.
    
      /****************** 环信  ******************/
    [[EMClient sharedClient] applicationWillEnterForeground:application];

      /****************** 环信  ******************/
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 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:.
}

#pragma mark - 获取 ,注册deviceToken
// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    if (deviceToken) {
        [[EMClient sharedClient] bindDeviceToken:deviceToken];
    }
}
// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error for deviceToken --- %@",error);
}

#pragma mark - 通知接收到消息
// ios10
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) {
    
    
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED {
    
}
// ios10以下
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo {
    
    
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    
}

#pragma mark - 环信代理
// 登录状态改变
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState {
    
}
// 账号在其他设备登录
- (void)userAccountDidLoginFromOtherDevice {
    // 清空本地数据
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"username"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"avatar"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"access_token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"account"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"domainName"];
    
    // 因为设置了自动登录模式：[[EMClient sharedClient].options setIsAutoLogin:YES];
    // 所以，登录之前要先注销之前的用户，否则重复登录会抛异常
    EMError *error = [[EMClient sharedClient] logout:YES];
    
    [HUDManager hideHUD];
    
    JX_NewLoginViewController *loginVC = [[JX_NewLoginViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = nav;
}

#pragma mark - 接收环信消息
- (void)messagesDidReceive:(NSArray *)aMessages {
    NSLog(@"- - - - %@", aMessages);
    
}

@end
