//
//  AppDelegate.m
//  ArcGis
//
//  Created by Mac Book DQ02 on 16/3/16.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "AppDelegate.h"
#import "MyMD5.h" //20160520 xmz modify
#import "CultureGameViewController.h"
#import "CultureOriginVC.h"
#import "UMSocialSinaHandler.h"


#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")

#define NotificationChange CFSTR("com.apple.springboard.lockstate")

#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")


#define UmengAppkey @"5733e612e0f55a55fd000f01"

static int lockState;

@interface AppDelegate () <UITabBarControllerDelegate, UITabBarDelegate> {
    UINavigationController *na2;
}

@end


static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo)

{
    lockState = 2;
    NSLog(@"Darwin notification NAME = %@",name);

    NSString* lockstate = (__bridge NSString*)name;
    
    if ([lockstate isEqualToString:(__bridge  NSString*)NotificationLock]) {
        
        NSLog(@"locked.");
        
    } else {
        
        NSLog(@"lock state changed.");
        
    }
    
}



@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
//    NSString *cachesPath = [FileDownloadTool getTheCachePath];
//    cachesPath = [cachesPath stringByAppendingString:@"/create_scenic_area_info"];
//    [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    
   //程序刚进入，网络请求登录，自动登录
    [Manager loginRequestWithUsernameAndPassword];
    
#pragma mark 友盟社会分享
    //设置友盟社会化组件appkey
   // [UMSocialData setAppKey:UmengAppkey];
    
    //打开调试log的开关
   // [UMSocialData openLog:YES];
    
    // 打开新浪微博的SSO开关
    // 将在新浪微博注册的应用appkey、redirectURL替换下面参数，并在info.plist的URL Scheme中相应添加wb+appkey，如"wb3921700954"，详情请参考官方文档。
   /* [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"1068270375"
                                              secret:@"c104196bdd7cec768a5f6bd0a2426751"
                                         RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    */
    
    [self configUMShare];
    
    
    //注册微信
    [WXApi registerApp:@"wxb8f15f96478031e0" withDescription:@"gaotingshan"];
    
    
    //在appdelegate里面创建单例， 整个程序始终生效,用作文本框的监测键盘弹起事件
    IQKeyboardManager *manger = [IQKeyboardManager sharedManager];
    //控制整个功能是否启用
    manger.enable = YES;
    //控制点击背景是否收起键盘
    manger.shouldResignOnTouchOutside = YES;
    //控制键盘上的工具条颜色是否用户自定义
    manger.shouldToolbarUsesTextFieldTintColor = YES;
    //控制是否显示键盘上的工具条
    manger.enableAutoToolbar = YES;
    
    //开启定位，实时监测位置，上报
    _locationManager = [[CLLocationManager alloc]init];
    [_locationManager setDelegate:self];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
    }
    else
    {
        //要求CLLocationManager对象开始工作，定位设备位置
        [_locationManager startUpdatingLocation];
    }
    
    dispatch_queue_t queque = dispatch_queue_create("my", DISPATCH_QUEUE_CONCURRENT);
    Singleton *single = [Singleton defaultSingleton];
    
   // 程序一进入，开线程，传递数据
    
    dispatch_async(queque, ^{
       
        int i = 19;
        while (1) {
            i++;
            if (i==20) {
                i=0;
                if ([single.userid isEqualToString:@""]) {
                    //没有登录，不上传
                }
                else
                {
                    //用户登录，上传坐标
                    //[Manager uploadLocation:j];
                    [Manager upoadLocationToServer:single.currentLocation];
                    
                }
                continue;
            }
            sleep(1);
        }
    });

    
    
    
    
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"pages"]) {
        //执行tabbar
        [self setMMDrawerController];
        
    } else {
        
        // 执行引导页
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"pages"];
        
        IntroduceViewController *introduceVC = [[IntroduceViewController alloc] init];
        
        self.window.rootViewController = introduceVC;
        
        [self.window makeKeyAndVisible];
        
    }
    


    [Manager startNoticeInternetStatus];
    
     lockState = 0;//锁屏状态
    
    //检测手机锁屏事件2016-05-17
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    
   // CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTabbarSelectedIndex) name:@"AppChangeTabbarSelectIndex" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeToLastIndex) name:@"changeToLastIndex" object:nil];
    
    return YES;
}

#pragma mark --配置友盟分享key
-(void)configUMShare
{
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:UmengAppkey];
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"1068270375"  appSecret:@"c104196bdd7cec768a5f6bd0a2426751" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}

#pragma mark 改变tabbar的选中项到竞赛页
-(void)changeTabbarSelectedIndex
{
    self.tabbarVC.selectedIndex = 1;
}

#pragma mark 恢复到上一次点击的索引
-(void)changeToLastIndex
{
    self.tabbarVC.selectedIndex = self.lastIndex;
}


#pragma mark - the window rootViewController with MMDrawerController
-(void)setMMDrawerController
{
    
    LeftDrawerViewController *lc = [[LeftDrawerViewController alloc]init];
    _tabbarVC= [[CustomTabBarController alloc]init];
    _tabbarVC.delegate = self;
    //设置TabBar
    _tabbarVC.tabBar.barTintColor = [UIColor blackColor];
    [_tabbarVC.tabBar setTintColor:[UIColor greenColor]];
    
    _drawerController = [[MMDrawerController alloc]initWithCenterViewController:_tabbarVC leftDrawerViewController:lc];
    [self.drawerController setShowsShadow:YES];
    
#pragma mark - set the width of leftView
    [self.drawerController setMaximumLeftDrawerWidth:self.window.frame.size.width*0.75];
#pragma mark - gesture 左右滑动，三个页面间切换
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    self.window.rootViewController = _drawerController;
    
    [self.window makeKeyAndVisible];
}

#pragma mark tabbarVC代理事件
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    Singleton *single = [Singleton defaultSingleton];
    
    if ([viewController isKindOfClass:[CultureOriginVC class]]) {
        if ([single.string isEqualToString:@"9002"]) {
            
            CultureGameViewController *vc = [[CultureGameViewController alloc]init];
            UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:vc];
            [self.tabbarVC presentViewController:na animated:NO completion:nil];
        }
        else
        {
            
            [FileDownloadTool alert:@"您还未登录！" view:self.window];
            return NO;
        }
        
    }
    
    return YES;
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    NSLog(@"tabbar.selectIndex=%ld",(unsigned long)_tabbarVC.selectedIndex);
    if (_tabbarVC.selectedIndex != 2) {
        _lastIndex = _tabbarVC.selectedIndex;
    }

}

#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    Singleton *singleton = [Singleton defaultSingleton];
    
    CLLocation *newLocation = [locations objectAtIndex:0];
    _currentLocation = newLocation;
    singleton.currentLocation = newLocation;
    
}

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

- (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.
    NSNumber *number = [NSNumber numberWithInt:lockState];
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"downloadPause" object:number]];
    
}

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

/**
 这里处理新浪微博SSO授权进入新浪微博客户端后进入后台，再返回原来应用
 处理地图下载任务的重新开始
 */
- (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.
 //   [UMSocialSnsService  applicationDidBecomeActive];
    
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"downloadResume" object:[NSNumber numberWithInt:lockState]]];
    lockState = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSString *tempPath = NSTemporaryDirectory();
    [[NSFileManager defaultManager]removeItemAtPath:tempPath error:nil];
    [_locationManager stopUpdatingLocation];//程序退出的时候，释放定位
}


-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}




/**
 这里处理新浪微博SSO授权之后跳转回来，和微信分享完成之后跳转回来
 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"sourceApplication = %@",sourceApplication);
    NSLog(@"url.host = %@",url.host);
    if ([sourceApplication isEqualToString:@"com.tecent.weixin"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result1 = %@",resultDic);
            
        }];

    }else{
        
        BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
        if (!result) {
            // 其他如支付等SDK的回调
        }
        return result;
    }
   
    return YES;
}



// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    NSLog(@"options = %@",options);

    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result2 = %@",resultDic);
            
        }];
        return YES ;
    }
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
         return [WXApi handleOpenURL:url delegate:self];
    }
    return result;
   
}




@end
