
//  AppDelegate.m
//  Open
//
//  Created by 黄江涛 on 16/9/6.
//  Copyright © 2016年 黄江涛. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <Bugly/Bugly.h>
#import "PhotoViewController.h"
#import "XLJNewFetureController.h"
#import "TRNavigationController.h"
//#import "DemoPreDefine.h"
#import "uitableViewController.h"
#import <UMShare/UMShare.h>

#import "smallTableVController.h"
#import "AppDelegate.h"
#import "tabViewController.h"
#import "NewsNetModel.h"
#define USHARE_DEMO_APPKEY @"5861e5daf5ade41326001eab"
#import "UIImageView+WebCache.h"
//test
#import "kankanshebaoxieyi.h"


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

#import <DFTTFramework_Base/DFTTFramework_Base.h>
#import <GTSDK/GeTuiSdk.h>
#import <DFTTPushSDK/TTPushManager.h>



#import <CL_ShanYanSDK/CL_ShanYanSDK.h>
#import "GTCountSDK.h"
#import "WXApi.h"


#import <GInsightSDK.h>
#import <AdSupport/AdSupport.h>

//极光统计
#import <JANALYTICSService.h>




//东方头条
#import "SpecialDetailVC.h"
#import "NewsDetailVC.h"
#import "VideoDetailVC.h"
#import "AtlasDetailVC.h"
#import "KKNewsVC.h"

#define kGcAppId @"CYol79N33N71BV6dcjrqj3"
#define WXAppId @"wx205c6619f1eab2e8"

#endif
@interface AppDelegate ()<DFTTPushDelegate,GeTuiSdkDelegate,WXApiDelegate,UNUserNotificationCenterDelegate>
@property(nonatomic,strong)     NSMutableArray *mArray;
@property(nonatomic,strong)UIViewController *splashView;

@property(nonatomic,strong)     NSString *webTitle;
@property(nonatomic,strong)     NSString *webUrl;


@property (strong, nonatomic) ViewController *viewController;
@property (assign, nonatomic) int lastPayloadIndex;
@end
@implementation AppDelegate

@synthesize window =_window;
@synthesize isLogin;
@synthesize isHuoti;
@synthesize isTel;
@synthesize telStr;
@synthesize telephoneLoginStr;
@synthesize telephoneLoginPassport;
@synthesize jin;
@synthesize wei;
@synthesize changeProgress;
@synthesize mySelfSignation;

-(NSMutableArray *)mArray
{
    if (!_mArray) {
        _mArray =@[@"socialSecurity1.jpg",@"socialSecurity2.jpg",@"socialSecurity3.jpg"].mutableCopy;
    }
    return _mArray;
}
-(NSMutableArray *)numberXMLArray
{
    if (!_numberXMLArray) {
        _numberXMLArray =[NSMutableArray array];
    }
    return _numberXMLArray;
}


#pragma mark - life cycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    
    //东方头条初始化
     [[DFTT getInitializeInstance] configueBaseArgument];
    [[DFTT getInitializeInstance] appRegisterWithAppid:@"201904040001" withAppkey:@"fdcead8683d853e4" withSofttype:@"kankanshebaosdk" withSoftname:@"kkshebaoios" withApptypeid:@"sdk_kkshebao" withQid:@"qid10902"];
    [DFTTSDK shareManager].pushDelegate = self;
   
    
    [[TTPushManager shared] registerPushSDKAppid:@"CYol79N33N71BV6dcjrqj3"appKey:@"rdLx5zumRK7oEme8MheAh8" appSecret:@"XMJ1jSsu3S89471rlEta52"callBack:^(BOOL success) {
        [[DFTTSDK shareManager] installLog];
        
    }];
    
    [GeTuiSdk setPushModeForOff:NO];
    
    
    //个数
    [GTCountSDK startSDKWithAppId:kGcAppId withChannelId:@"appstore"];
    
   // [GeTuiSdk startSdkWithAppId:@"CYol79N33N71BV6dcjrqj3" appKey:@"rdLx5zumRK7oEme8MheAh8" appSecret:@"XMJ1jSsu3S89471rlEta52"
    //                   delegate:self];
   
    [GeTuiSdk runBackgroundEnable:true];
    
    [GeTuiSdk setChannelId:@"GT-Channel"];
   
    
    //个像
    [GInsightSDK startSDK:kGcAppId channel:@"appstore" onSuccess:^(NSString *giUid) {
        NSLog(@"个像初始化成功");
    } onFail:^(NSString *failInfo) {
        NSLog(@"个像初始化失败");
     
        
    }];

//    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    NSLog(@"hahahahahaha=%d",idfa);
     NSString * IDFV = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
     NSLog(@"hahahahahaha：%@",IDFV);
   
    
    //雷俊博注释
//    self.telephoneLoginStr=DIANHUAHUAOMA;
//    self.telephoneLoginPassport =MIMAPASSPORT;
    [UMConfigure setLogEnabled:YES];
    [UMConfigure initWithAppkey:@"5be94bc9b465f51051000057" channel:nil];
    [MobClick setScenarioType:E_UM_NORMAL];
    [self configUSharePlatforms];
    [self confitUShareSettings];
    if ([@"https://socialsecurity.weface.com.cn:8066" isEqualToString:IPDIZHI]) {
        [Bugly startWithAppId:@"f9ca4b1e62"];
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
    ////雷俊博注释
//    [logNetModel getLogMessage3:nil andTelephone:self.telephoneLoginStr andLoginpassword:self.telephoneLoginPassport  andUid:nil andl:0 andweixinId:nil andPicId:nil completionHandle:^(lodModel *model, NSError *error) {
//        if (error ) {
//
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if(model.userinfo.account_type == 0)  [getPeopleID getLimmitedToBanbana:YES];else
//                [getPeopleID getLimmitedToBanbana:NO];
//        });
//    }];
    [getPeopleID getLimmitedToBanbana:YES];
    [application setApplicationIconBadgeNumber:0];
   
   
    self.isLogin = NO;
    self.isHuoti = NO;
    self.isTel = NO;
    [getPeopleID getSocialSecurityProvinceData:@"上海市" andCountry:@"市辖区" andOther:@"浦东新区"];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        [getPeopleID deletePlist];
        [getPeopleID createPlistByCode];
        [[NSUserDefaults standardUserDefaults] setInteger:80 forKey:@"fucck"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firdfghjefhrju"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"fucck_two"];
        [[NSUserDefaults standardUserDefaults]synchronize];
      [self baiduFaceReCo];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {		
        [getPeopleID createPlistByCode];
        [[NSUserDefaults standardUserDefaults] setInteger:80 forKey:@"fucck"];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstlog"];
        //雷俊博注释:目前没什么用
       // [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"zhifubaAlibaba"];
        [getPeopleID socialSate:0];
        UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        uitableViewController *tc=[sb instantiateViewControllerWithIdentifier:@"uitableViewController"];
        XLJNewFetureController *newVC = [[XLJNewFetureController alloc] initWithNSArray:self.mArray withButtonSize:CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width) withButtonTitle:@" " withButtonImage:nil withButtonTitleColor:[UIColor orangeColor] withButtonHeight:0.73 withViewController:tc];

        self.window.rootViewController = newVC;
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        
    }
    else
    {
        UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        uitableViewController *tc=[sb instantiateViewControllerWithIdentifier:@"uitableViewController"];
        tabViewController *TC =[[tabViewController alloc]init];
        TC.viewControllers =[NSArray arrayWithObjects:tc, nil];
        TC.tabBar.hidden =YES;
        self.window.rootViewController =TC;
        [self.window makeKeyAndVisible];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    }
    [self dianchi];
    
    
    
    //向注册微信
    [WXApi registerApp:WXAppId];
    
   
    
    
    //ShanYanSDK集成（setup1）初始化
   
    [CLShanYanSDKManager initWithAppId:cl_SDK_APPID AppKey:cl_SDK_APPKEY timeOut:3 complete:^(CLCompleteResult * _Nonnull completeResult) {
            NSLog(@" CL_ShanYanSDKVersionNumber:%f",CL_ShanYanSDKVersionNumber);
            if (completeResult.error) {
                NSLog(@"SDK 初始化失败：%@",completeResult.message);
            }else{
                NSLog(@"SDK 初始化成功：%@",completeResult.message);
            }
        }];
    
    
    //极光统计SDK初始化
    JANALYTICSLaunchConfig * config = [[JANALYTICSLaunchConfig alloc] init];
    config.appKey = appKey;
    config.channel = channel;
    [JANALYTICSService setupWithConfig:config];
    [JANALYTICSService setDebug:isProduction];
    
    
    
    
    //日志
    [DDLog addLogger:[DDASLLogger sharedInstance]]; // Uses os_log
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init]; // File Logger
    fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];
    
    
    DDLogVerbose(@"Verbose");
    DDLogDebug(@"Debug");
    DDLogInfo(@"Info");
    DDLogWarn(@"Warn");
    DDLogError(@"Error");
    
  
    return YES;
}




#pragma mark - DFTTPushDelegate
- (void)receivePushNewsModel:(id)model isBackground:(BOOL)isBackground{
    NSLog(@"接收到了---");
    if (isBackground && [model isKindOfClass:[TTNewsListModel class]]) {
         [self ClickWithNewsListModel:model];
    }else if (!isBackground && [model isKindOfClass:[TTNewsListModel class]]) {
        [self addLocalNotice:model];
    }
}

#pragma mark - 本地推送
- (void)addLocalNotice:(TTNewsListModel *)model {
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        // 标题
        content.title = model.pushTitle;
        // 内容
        content.body = model.pushContent;
        NSString *json = [NSString stringWithFormat:@"{\"url\":\"%@\",\"title\":\"%@\",\"content\":\"%@\",\"ispush\":\"1\",\"pushts\":\"%@\",\"pushlabel\":\"%@\",\"push_type\":\"%@\",\"preload\":\"%@\"}",model.url,model.pushTitle,model.pushContent,model.pushts,model.pushlabel,model.push_type,model.preload];
        content.userInfo = @{@"payload":json};


        // 声音
        // 默认声音
        //    content.sound = [UNNotificationSound defaultSound];
        // 添加自定义声音
        content.sound = [UNNotificationSound soundNamed:@"Alert_ActivityGoalAttained_Salient_Haptic.caf"];
        // 角标 （我这里测试的角标无效，暂时没找到原因）
        content.badge = @1;
        // 多少秒后发送,可以将固定的日期转化为时间
        NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:1] timeIntervalSinceNow];
        //        NSTimeInterval time = 10;
        // repeats，是否重复，如果重复的话时间必须大于60s，要不会报错
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time repeats:NO];
        
        /*
         //如果想重复可以使用这个,按日期
         // 周一早上 8：00 上班
         NSDateComponents *components = [[NSDateComponents alloc] init];
         // 注意，weekday默认是从周日开始
         components.weekday = 2;
         components.hour = 8;
         UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
         */
        // 添加通知的标识符，可以用于移除，更新等操作
        NSString *identifier = @"noticeId";
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
        
        [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
            NSLog(@"成功添加推送");
        }];
    }else {
        UILocalNotification *notif = [[UILocalNotification alloc] init];
        // 发出推送的日期
        notif.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
        // 推送的内容
        notif.alertTitle = model.pushTitle;
        notif.alertBody = model.pushContent;
        NSString *json = [NSString stringWithFormat:@"{\"url\":%@,\"title\":%@,\"content\":%@,\"ispush\":\"1\",\"pushts\":%@,\"pushlabel\":%@,\"push_type\":%@,\"preload\":%@}",model.url,model.pushTitle,model.pushContent,model.pushts,model.pushlabel,model.push_type,model.preload];

        notif.userInfo = @{@"payload":json};
        // 角标
        notif.applicationIconBadgeNumber = 1;
        // 提示音
        notif.soundName = UILocalNotificationDefaultSoundName;
      
        notif.repeatInterval = 0;
        
        [[UIApplication sharedApplication] scheduleLocalNotification:notif];
    }
}


//点击新闻
- (void)ClickWithNewsListModel:(id)newsListModel {
    NSLog(@"代理方法开始");
    //新闻的URL
    // NSString * url = [newsListModel valueForKey:@"url"];
   
        TTNewsDetailController * detailVc = [[TTNewsDetailController alloc] initWithNewsWebDetailcfg:nil withNewsListModel:newsListModel withSuccess:^(NSString *success) {
            
        } withFail:^(NSString *fail) {
            
        }];
    //detailVc.delegate = self;
    
    UIViewController *vc = self.window.rootViewController;
    if ([vc isKindOfClass:[XLJNewFetureController class]]) {
        
    }else if ([vc isKindOfClass:[uitableViewController class]]){
        uitableViewController *tabvc = (uitableViewController *)vc;
        
        tabvc.selectedIndex = 1;
        
        TRNavigationController *nav = tabvc.selectedViewController;
        if ([nav.topViewController isKindOfClass:KKNewsVC.class]) {
            detailVc.hidesBottomBarWhenPushed= YES;
        }
        [nav pushViewController:detailVc animated:YES];
    }else if ([vc isKindOfClass:[tabViewController class]]){
        tabViewController *tabVC = (tabViewController*)vc;
        
        if ([tabVC.selectedViewController isKindOfClass:[uitableViewController class]]) {
             uitableViewController *myTabVC = (uitableViewController *)tabVC.selectedViewController;
            myTabVC.selectedIndex = 1;
            
            TRNavigationController *nav = myTabVC.selectedViewController;
            if ([nav.topViewController isKindOfClass:KKNewsVC.class]) {
                detailVc.hidesBottomBarWhenPushed= YES;
            }
            [nav pushViewController:detailVc animated:YES];
        }
    }
    
}

#pragma mark - 远程通知回调
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString*deviceTokenString = [[[[deviceToken description]stringByReplacingOccurrencesOfString:@"<"withString:@""]stringByReplacingOccurrencesOfString:@">"withString:@""]stringByReplacingOccurrencesOfString:@" "withString:@""];
    
    NSLog(@"deviceToken:%@",deviceTokenString);
    TTPushManager * mgr = [TTPushManager shared];
    [mgr configToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark - APP运行中接收到通知(推送)处理 - iOS 10以下版本收到推送
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [UIApplication sharedApplication].applicationIconBadgeNumber ++;
    [[TTPushManager shared] handNotiInfo:userInfo];
}




     
- (void)startupAnimationDone:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context

{
    [_splashView.view removeFromSuperview];
}
-(void)baiduFaceReCo{
    NSString* licensePath = [[NSBundle mainBundle] pathForResource:FACE_LICENSE_NAME ofType:FACE_LICENSE_SUFFIX];
    NSAssert([[NSFileManager defaultManager] fileExistsAtPath:licensePath], @"license文件路径不对，请仔细查看文档");
    [[FaceSDKManager sharedInstance] setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath];
    NSLog(@"baiducanwork=%d",[[FaceSDKManager sharedInstance]canWork]);
#if TARGET_IPHONE_SIMULATOR
    
#else
    NSLog(@"baiduversion=%@", [[FaceVerifier sharedInstance]getVersion]);
#endif
    
}

#pragma mark - AFNetworking
-(void)dianchi{
    
    
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
  
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                self.onLine = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
            default:
                self.onLine = NO;
                break;
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
   
}

//当程序进入后台的时候调用
- (void)applicationWillResignActive:(UIApplication *)application {
//程序准备进入后台通知相关VC 记录当前时间
    [[NSNotificationCenter defaultCenter]postNotificationName:@"APPWillResignActive"object:nil];
}
//当程序进入前台的时候调用
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    //程序进入前台时，记录当前时间
    [[NSNotificationCenter defaultCenter]postNotificationName:@"APPDidBecomeActive"object:nil];
}

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

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [MobClick endLogPageView:@"淘宝"];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];}

//- (void)applicationDidBecomeActive:(UIApplication *)application {
//}

- (void)applicationWillTerminate:(UIApplication *)application {
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}
-(void)setAnimation:(UIImageView *)nowView
{
    [UIView animateWithDuration:3.0f delay:0.0f options:UIViewAnimationOptionTransitionFlipFromBottom
                     animations:^
     {
         
         [nowView setFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width , [UIScreen mainScreen].bounds.size.height )];
     }
                     completion:^(BOOL finished)
     {
     }
     ];
}










- (void)confitUShareSettings
{
    
}
- (void)configUSharePlatforms
{
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx205c6619f1eab2e8" appSecret:@"af42ff79ba3affe872e73fcf93be8714" redirectURL:@"http://mobile.umeng.com/social"];
   
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105907017"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
   
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3411147507"  appSecret:@"3a4c244f979496ad034e369653204006" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
   
    [[UMSocialManager defaultManager] setPlaform: UMSocialPlatformType_AlipaySession appKey:@"2018102361771576" appSecret:nil redirectURL:nil];
    

}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    BOOL result2 = [WXApi handleOpenURL:url delegate:self];
    BOOL result3 = [JANALYTICSService handleUrl:url];
    if (result3) {
        return YES;
    }
    if (result2) {
        return result2;
    }
    if (!result) {
        
    }
    return result;
}

//iOS10以下跳转app
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
   
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    BOOL result2 = [WXApi handleOpenURL:url delegate:self];
    BOOL result3 = [JANALYTICSService handleUrl:url];
    if (result3) {
        return YES;
    }
    if (result2) {
        return result2;
    }
    if (!result) {
     
    }
    return result;
}
//iOS10以上跳转app
- (void)openURL:(NSURL*)url options:(NSDictionary *)options
completionHandler:(void (^ __nullable)(BOOL success))completion
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    BOOL result2 = [WXApi handleOpenURL:url delegate:self];
    BOOL result3 = [JANALYTICSService handleUrl:url];
    if (result3) {
        completion(result3);
    }
    if (result) {
        completion(result);
    }
    if (result2) {
        completion(result2);
    }
}


#pragma mark - WXAPIDelegate
/*! @brief 收到一个来自微信的请求，第三方应用程序处理完后调用sendResp向微信发送结果
 *
 * 收到一个来自微信的请求，异步处理完成后必须调用sendResp发送处理结果给微信。
 * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
 * @param req 具体请求内容，是自动释放的
 */
- (void)onReq:(BaseReq*)req {
    
}
/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp具体的回应内容，是自动释放的
 */
- (void)onResp:(BaseResp*)resp {
    
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]])
    {
        NSString *string = resp.errStr;
        // 对应JsApi navigateBackApplication中的extraData字段数据
    }
}




@end

