//
//  tabViewController.m
//  socialSecurity
//
//  Created by 看看智能 on 2017/4/1.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "tabViewController.h"
#import "WKWebViewController.h"
#import "TRNavigationController.h"

#import "NSString+Timestamp.h"



#import "CTAPIBaseManager.h"

#import "AdBottomView.h"

//缓存
#import "CTDiskCacheCenter.h"
#import<AdSupport/AdSupport.h>

#import "GTCountSDK.h"
@interface tabViewController ()
@property(nonatomic,strong)UIViewController *vc;
@property(nonatomic,strong)NSString *UrlStr;
@property(nonatomic,strong)NSString *ur;

@property (nonatomic, strong)NSMutableArray *dataArray;

@property (nonatomic, strong)NSArray *click_tracking_urls;

@property (nonatomic, strong)NSTimer* timer;

@end

@implementation tabViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
      


//    self.vc  = [[UIStoryboard storyboardWithName:@"KKLaunchScreen" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"sbID"];
//    [self.view addSubview: self.vc.view];
    
    
    
   // [self loadAdData];

    self.tabBar.hidden = YES;
    
   
}

- (void)dealloc
{
    if (self.timer) {
        [self.timer invalidate];
    }
    
}










#pragma mark - 加载广告
- (void)loadAdData
{
    //NSString *url = @"http://sandbox.mmp.marketin.cn/mmps/v1/req_ad";
    NSString *url = @"http://mobquery.marketin.cn/mmps/v1/c_10028/req_ad";
    
    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    NSDictionary *params = @{
                             @"id":[NSString getNowTimeTimestamp],
                             @"app":@{
                                     @"id":@"10096",
                                     @"publisher":@{
                                             @"id":@"10028"
                                             }
                                     },
                             @"device":@{
                                     @"devicetype":[NSNumber numberWithInt:1],
                                     @"model":@"iphone",
                                     @"os":@"1",
                                     @"osv":[[UIDevice currentDevice] systemVersion],
                                     @"screen_orientation":[NSNumber numberWithInt:1],
                                     @"make":@"apple",
                                     @"size":[NSString stringWithFormat:@"%dx%d",(int)[UIScreen mainScreen].bounds.size.width,(int)[UIScreen mainScreen].bounds.size.height],
                                     @"ifa":idfa,
                                     @"ifa_md5":[idfa CT_MD5]
                                     },
                             @"network":@{
                                     @"type":@0,
                                     @"operator":@0,
                                     @"cellular_id":@"1111"
                                     },
                             @"adpos":@[@{
                                            @"capacity":@1,
                                            @"pos_id":@"10155"
                                            }]
                             };
    
    //AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    NSString *appId = @"f250daff6a09865ff432821b2adac54f";
    NSString *user_id = @"10040";
    NSString *app_key = @"CE91C478-34A5-4276-8E32-0CDB6E1FF8F4";
    NSString *timeStamp = [NSString getNowTimeTimestamp];
    //       NSString *appId = @"4ccea3161064506dda8e0c9fd416d1ae";
    //    NSString *user_id = @"10037";
    //    NSString *app_key = @"56669853-8430-4534-BCE8-01FADE1010B5";
    //    NSString *timeStamp = @"1513937374";
    
    NSString *signature = [[NSString stringWithFormat:@"%@%@%@",appId,app_key,timeStamp] CT_SHA1];
    NSString *token =  [[NSString stringWithFormat:@"%@,%@,%@,%@",appId,user_id,timeStamp,signature] CT_Base64Encode];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:params error:nil];
    request.timeoutInterval = 10.f;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    WeakSelf
   NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
         NSLog(@"-----responseObject===%@+++++",responseObject);
                NSLog(@"-----error%@+++",error);
                
                if(error){
                    [weakSelf loadMyData];
                    //    [SVProgressHUD showErrorWithStatus:@"当前网络状态差"];
        //            [self.vc.view removeFromSuperview];
        //            [self.vc.view setUserInteractionEnabled:NO];
                    return;
                }
                
                NSNumber *success = responseObject[@"success"];
                NSNumber *nbr = responseObject[@"nbr"];
                if (success.boolValue && nbr.integerValue == 0) {
                    
                    
                    NSArray *array = responseObject[@"ads"];
                    NSMutableArray *array1 =[NSMutableArray new];
                    for (NSDictionary *dic in array) {
                        
                        [array1 addObject:dic[@"creative_elements"][@"image"]];
                        self.UrlStr =dic[@"click_through_url"];
                        self.ur = dic[@"creative_elements"][@"image"];
                        self.click_tracking_urls = dic[@"click_tracking_urls"];
                        
                        
                        [self loadOtherData:dic[@"imp_tracking_urls"]];
                        NSTimeInterval cacheTime = 24 * 60 * 60;
                        
                        [CTDiskCacheCenter saveCacheWithResponse:dic key:@"marketinAd" cacheTime:cacheTime];
                        
                        [[NSUserDefaults standardUserDefaults]setObject:self.UrlStr forKey:@"urlPath"];
                        [[NSUserDefaults standardUserDefaults]setObject:self.ur forKey:@"imageu"];
                    }
                    
                    
                    self.vc.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height);
                    UIImageView *imageV = [[UIImageView  alloc]initWithFrame:[UIScreen mainScreen].bounds];
                     imageV.contentMode = UIViewContentModeScaleAspectFill;
                    if (array1.count <=0) {
                        [self.vc.view removeFromSuperview];
                        return;
                    }
                    
                    
                
                    
                    
                    NSData * ss = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.ur]];
                    imageV.image = [UIImage imageWithData:ss];
                    
                    
                    
                    [self.vc.view addSubview:imageV];
                    
                    
                    //        添加按钮
                    UIButton *showDetailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    [showDetailBtn setTitle:@"跳过>>" forState:UIControlStateNormal];
                    [showDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [showDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
                    showDetailBtn.titleLabel.font = [UIFont systemFontOfSize:13];
                    CGRect f = [UIScreen mainScreen].bounds;
                    showDetailBtn.frame = CGRectMake(f.size.width - 70, 30, 60, 30);
                    showDetailBtn.layer.borderColor = [UIColor whiteColor].CGColor;
                    showDetailBtn.layer.borderWidth = 1.0f;
                    showDetailBtn.layer.cornerRadius = 3.0f;
                    showDetailBtn.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.3];
                    imageV.userInteractionEnabled =YES;
                    //        [showDetailBtn addTarget:self action:@selector(showAdDetail:) forControlEvents:UIControlEventTouchUpInside];
                    [imageV addSubview:showDetailBtn];
                    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
                    UITapGestureRecognizer * PrivateLetterTap_2=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeLun)];
                    
                    
                    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
                    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
                    PrivateLetterTap_2.numberOfTouchesRequired = 1; //手指数
                    PrivateLetterTap_2.numberOfTapsRequired = 1; //tap次数
                    //   PrivateLetterTap.delegate= self;
                    imageV.contentMode = UIViewContentModeScaleAspectFill;
                    [imageV addGestureRecognizer:PrivateLetterTap];
                    [showDetailBtn addGestureRecognizer:PrivateLetterTap_2];
                    
                    AdBottomView *bottomView = [[AdBottomView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 130, ScreenWidth, 130)];
                    
                    bottomView.backgroundColor = [UIColor whiteColor];
                    
                    [imageV addSubview:bottomView];
                    
                   
                    
                }else {
                    
                    [weakSelf loadMyData];
        //            [self.vc.view removeFromSuperview];
        //            [self.vc.view setUserInteractionEnabled:NO];
                    return;
                }
    }];
    
    [task resume];
}

//返回曝光检测地址请求
- (void)loadOtherData:(NSArray *)array
{
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_queue_t searialQueue = dispatch_queue_create("com.hmc3.www", DISPATCH_QUEUE_SERIAL);
    
    
    
    for (NSString *urlStr in array) {
        dispatch_group_enter(group);
        dispatch_group_async(group, searialQueue, ^{
            //网络请求1
            [CTAPIBaseManager GET:urlStr params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                dispatch_group_leave(group);
            }];
        });
    }
    
    //多个网络请求结束后,刷新UI
    dispatch_group_notify(group, searialQueue, ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"返回曝光地址请求");
            });
        });
    });
}

- (void)loadMyData
{
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:8  target:self selector:@selector(costumRemoveRun) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
    [NewsNetModel acquirePicture:nil andlocationCoordinate:nil andint:2 complete:^(homePageNewsModel* model, NSError *error) {
        //2017年7月11日修改
        /*
         修改内容:添加无网络的时候手机app的提醒
         
         **/
        if(error){
            //    [SVProgressHUD showErrorWithStatus:@"当前网络状态差"];
            [self.vc.view removeFromSuperview];
            [self.vc.view setUserInteractionEnabled:NO];
            return;
        }
        NSLog(@"%@",error);
        
        
        NSMutableArray *array1 =[NSMutableArray new];
        for (homePageNewsResultModel *str1 in model.Result) {
            [array1 addObject:str1.KKImage];
            self.UrlStr =str1.targetUrl;
            self.ur = str1.KKImage;
            [[NSUserDefaults standardUserDefaults]setObject:self.UrlStr forKey:@"urlPath"];
            [[NSUserDefaults standardUserDefaults]setObject:str1.KKImage forKey:@"imageu"];
        }
        //        CATransition *applicationLoadViewIn =[CATransition animation];
        //        [applicationLoadViewIn setDuration:0.2];
        //        [applicationLoadViewIn setType:kCATransitionReveal];
        //        [applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
        //        [[self.vc.view layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
        self.vc.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height);
        UIImageView *imageV = [[UIImageView  alloc]initWithFrame:[UIScreen mainScreen].bounds];
        imageV.contentMode = UIViewContentModeScaleAspectFit;
        if (array1.count <=0) {
            [self.vc.view removeFromSuperview];
            return;
        }
        //
        //        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        //        NSURL *URL = [NSURL URLWithString:array1[0]];
        //        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        //        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        //
        //            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        //            return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        //        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        //            NSLog(@"File downloaded to: %@", filePath);
        //
        //            NSData * image = [NSData dataWithContentsOfURL:filePath];
        ////            [[NSUserDefaults standardUserDefaults]setObject:image forKey:@"imageu"];
        //        }];
        //        [downloadTask resume];
        
        
        
        
        
        
        //        NSMutableData * data = [[NSUserDefaults standardUserDefaults]objectForKey:@"imageu"];
        //   NSString *strUrl=  [[NSUserDefaults standardUserDefaults]objectForKey:@"imageu"];
        NSData * ss = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.ur]];
        imageV.image = [UIImage imageWithData:ss];
        
        //             [imageV sd_setImageWithURL:[NSURL URLWithString:array1[0]] placeholderImage:[UIImage imageNamed:@"0-启动"]];
        //            NSData * image = [NSData dataWithContentsOfURL:[NSURL URLWithString:array1[0]]];
        //            [[NSUserDefaults standardUserDefaults]setObject:image forKey:@"imageu"];
        
        
        [self.vc.view addSubview:imageV];
        
        
        //        添加按钮
        UIButton *showDetailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [showDetailBtn setTitle:@"跳过>>" forState:UIControlStateNormal];
        [showDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [showDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        showDetailBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        CGRect f = [UIScreen mainScreen].bounds;
        showDetailBtn.frame = CGRectMake(f.size.width - 70, 30, 60, 30);
        showDetailBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        showDetailBtn.layer.borderWidth = 1.0f;
        showDetailBtn.layer.cornerRadius = 3.0f;
        showDetailBtn.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.3];
        imageV.userInteractionEnabled =YES;
        //        [showDetailBtn addTarget:self action:@selector(showAdDetail:) forControlEvents:UIControlEventTouchUpInside];
        [imageV addSubview:showDetailBtn];
        UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
        UITapGestureRecognizer * PrivateLetterTap_2=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(costumRemoveRun)];
        
        
        PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
        PrivateLetterTap_2.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap_2.numberOfTapsRequired = 1; //tap次数
        //   PrivateLetterTap.delegate= self;
        imageV.contentMode = UIViewContentModeScaleAspectFill;
        [imageV addGestureRecognizer:PrivateLetterTap];
        [showDetailBtn addGestureRecognizer:PrivateLetterTap_2];
        
        
      
        
        
        //      [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(removeLun) userInfo:nil repeats:NO];
        
    }];
}


-(void)tapAvatarView:(UITapGestureRecognizer*)gg
{
    
    if (self.UrlStr) {
        NSDictionary *dic = @{
                              @"url":self.UrlStr,
                              @"click_tracking_urls":self.click_tracking_urls ? self.click_tracking_urls : @[]
                              
                              };
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLPushToAdvert" object:nil userInfo:dic];
    }
    
    [self removeLun];
   
    
    
}

- (void)costumRemoveRun
{
    [self removeLun];
}

-(void)removeLun
{
    [self.vc.view removeFromSuperview];
    [self.vc.view setUserInteractionEnabled:NO];
    

    
}




- (void)showAdDetail:(UITapGestureRecognizer*)gg
{
    [self.vc.view removeFromSuperview];
    [self.vc.view setUserInteractionEnabled:NO];
    
    
    // AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    /// delegate.onstr = YES;
    
    
}

#pragma mark - getters and setters
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
@end

