//
//  AppDelegate.m
//  total
//  中化道达尔
//  Created by freecui on 15/9/9.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "AppDelegate.h"
//#import "BMKMapManager.h"
#import "IQKeyboardManager.h"
 #import "APService.h"
#import "UploadManager.h"

@interface AppDelegate ()
{
    BMKMapManager* _mapManager;
}
@property (strong, nonatomic) NSString *version;//本地版本号
@property (strong, nonatomic) NSString *severVersion;//服务器版本号
@property (strong, nonatomic) NSString *intVersion;//本地版本号
@property (strong, nonatomic) NSString *intSeverVersion;//服务器版本号

@property (strong, nonatomic) NSString *severUrl;//Ipa下载地址
@property (assign, nonatomic) BOOL severForceUpdate;//强制更新
@property (nonatomic,strong) UIAlertView *alertV;//更新提示框
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [UploadManager getAppOption];
    //版本更新
    [self enterpriseUpdate];
    [self SetIQKeyboardManager];
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"wOOQUMG2dZtV14t9NwKfkBw2"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    [self.window makeKeyWindow];
    
        _m_appViewControllerMgr = [ICRAppViewControllerManager getAppViewControllerManager];
    
    // JPush
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //categories
        [APService
         registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                             UIUserNotificationTypeSound |
                                             UIUserNotificationTypeAlert)
         categories:nil];
    }
    [APService setupWithOption:launchOptions];
    //清除角标
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [self SetupJPushTag];
    return YES;
}

#pragma mark - 键盘
- (void)SetIQKeyboardManager
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    [[IQKeyboardManager sharedManager]setKeyboardDistanceFromTextField:0];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.enableAutoToolbar = YES;
}

#pragma mark - 注册推送别名
/**
 *  极光推送 设置别名
 *
 *  @param application
 *  @param deviceToken
 */
- (void)SetupJPushTag
{
    [APService setAlias:[ICRUserUtil sharedInstance].f_user_uuid callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
}
/**
 *  打印JPush别名/Tag值
 */
- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias
{
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}

#pragma mark enterprise alertView 企业版提示
- (void)enterpriseUpdate{
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"Info" ofType:@"plist"];
    NSDictionary* content =[NSDictionary dictionaryWithContentsOfFile:path];
    NSString *version = [content valueForKey:@"CFBundleShortVersionString"] ;
    self.version=version;
    // 获取服务器更新信息
    [self  getDataFromServer];
}

//请求服务器更新信息
- (void)getDataFromServer{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message  = data[@"message"] ;
            if (success == 1) {
                NSDictionary *dictData = data[@"data"];
                NSString*serverVeision=[dictData objectForKey:@"version"];
                NSString*serverUrl=[dictData objectForKey:@"url"];
                BOOL forceUpdate= [dictData objectForKey:@"forceUpdate"];
                self.severVersion=serverVeision;
                self.severUrl=serverUrl;
                self.severForceUpdate=forceUpdate;
                [strongSelf  comperVersion];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"     无记录     "];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getVeisionIdWithType:@"ipa" success:succ failure:fail];
}

//比较版本号及是否下载
-(void)comperVersion
{
    if (self.version && self.severVersion) {
        self.intVersion=@"";
        self.intSeverVersion=@"";
        NSArray *array1 = [self.version componentsSeparatedByString:@"."];
        NSArray *array2 = [self.severVersion componentsSeparatedByString:@"."];
        for (int i = 0; i < [array1 count]; i++) {
            self.intVersion=[self.intVersion stringByAppendingFormat:@"%@",[array1 objectAtIndex:i]];
            NSLog(@"string:%@", [array1 objectAtIndex:i]);
        }
        for (int i = 0; i < [array2 count]; i++) {
            self.intSeverVersion=[self.intSeverVersion stringByAppendingFormat:@"%@",[array2 objectAtIndex:i]];
            NSLog(@"string:%@", [array2 objectAtIndex:i]);
        }
        BOOL isNeedUpdate=[self compareVersion];
        if (isNeedUpdate) {
            if (self.severForceUpdate) {
                //强制更新
                self.alertV = [[UIAlertView alloc]initWithTitle:@"新版本告知" message:@"有新版本发布请您下载最新版本" delegate:self cancelButtonTitle:nil otherButtonTitles: @"去下载", nil];
                self.alertV.tag = 1001;
                [self.alertV show];
            }else {
                self.alertV = [[UIAlertView alloc]initWithTitle:@"新版本告知" message:@"有新版本发布请您下载最新版本" delegate:self cancelButtonTitle:@"下次再说"otherButtonTitles: @"去下载", nil];//
                self.alertV.tag = 1002;
                [self.alertV show];
            }
        }
    }
}

-(BOOL)compareVersion
{
    float  version=[self.intVersion floatValue];
    float severVersion=[self.intSeverVersion floatValue];
    if (severVersion >version) {
        return YES;
    }else{
        return NO;
    }
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==1001) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.severUrl]];
    }else if (alertView.tag==1002)
    {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.severUrl]];
        }
    }
}

//比较版本号
- (NSComparisonResult)p_compareVersions: (NSString *)version1 betweenVersion2: (NSString *)version2{
    NSComparisonResult result = NSOrderedSame;
    if ([version2 isEqualToString:@""]) {
        result = NSOrderedDescending;
        return result ;
    }
    NSMutableArray *a = (NSMutableArray *)[version1 componentsSeparatedByString:@"."];
    NSMutableArray *b = (NSMutableArray *)[version2 componentsSeparatedByString:@"."];
    
    while (a.count < b.count) {[ a addObject:@"0"];}
    while (b.count < a.count) {[ b addObject:@"0"];}
    
    for(int i = 0; i < a.count; ++i){
        if ([[a objectAtIndex:i] integerValue] < [[b objectAtIndex:i] integerValue]) {
            result = NSOrderedAscending;
            break;
        }else if ([[b objectAtIndex:i] integerValue] < [[a objectAtIndex:i] integerValue]){
            result = NSOrderedDescending;
            break;
        }
    }
    return  result;
    
}

- (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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
//    [self.alertV dismissWithClickedButtonIndex:0 animated:YES];
}

- (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 inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [self enterpriseUpdate];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
//    CLog (@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [APService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required
    [APService handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (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:.
}

@end
