//
//  MyAdViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/10/17.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "MyAdViewController.h"
#import "UIImageView+WebCache.h"

#import "CTAPIBaseManager.h"


@interface MyAdViewController ()<UIGestureRecognizerDelegate>
{
    //广告曝光图片url
    NSString *img_url;
    //上报曝光url数组
    NSArray *impress_notice_urls;
    //点击链接url
    NSString *click_url;
    //上报点击url数组
    NSArray *click_notice_urls;
    
    int req_width;
    int req_height;
    int width;
    int height;
    int req_x;
    int req_y;
    
    
}

@property (nonatomic, strong)homePageNewsResultModel *model;

@property (nonatomic, strong) UIButton *skipBtn; //跳过button
@property (nonatomic, strong) NSTimer *timer;   //定时器倒计时




@end

//倒计时5s
static NSUInteger AdCount = 5;

@implementation MyAdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self.view addSubview:self.skipBtn];

    
    //[self loadAdAPI];
    
    //[self getAdvertAPI];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.timer = nil;
}

- (void)dealloc
{
    NSLog(@"广告页面被销毁了");
}


#pragma mark - public methds
- (void)loadMyAd
{
    [self loadAdAPI];
}


- (void)loadAdAPI
{
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        // 获得图片URL
       NSString *url = @"http://api.toutiaocri.com/v2/yd3/mApiView";
        CGFloat screenScale = [UIScreen mainScreen].scale;
        NSDictionary *params = @{
            @"version􏰆􏰆􏰆􏰆":@"2.3.2",
            @"c_type":@1,
            @"mid":@"iosgdtgxkp01",
            @"uid":[IPTool getIdentifier],
            @"adCount":@1,
            @"support_macro":@0,
            @"support_https":@0,
            @"support_full_screen_interstitial":@0,
            @"os":@"IOS",
            @"osv":[IPTool getSystemVersion],
            @"networktype":@0,
            @"remoteip":[IPTool getIPAddress:YES],
            @"make":@"apple",
            @"brand":@"iPhone",
            @"model":[IPTool DSMC_getDeviceType],
            @"devicetype":@"1",
            @"idfa":[IPTool getIDFA],
            @"idfv":[IPTool getIDFV],
            @"openudid":[OpenUDID value],
            @"width":[NSNumber numberWithInt:ScreenWidth *screenScale],
            @"height":[NSNumber numberWithInt:ScreenHeight *screenScale],
            @"ad_width":[NSNumber numberWithInt:ScreenWidth *screenScale],
            @"ad_height":[NSNumber numberWithInt:ScreenHeight *screenScale],
            @"density":[NSNumber numberWithFloat:screenScale],
            @"dpi":[NSNumber numberWithFloat:screenScale * 160],
            @"orientation":@1,
            @"appid":[IPTool getBundleId],
            @"appname":[IPTool getAppName],
            @"postion":@4,
            @"operator":[IPTool getOperator]
        };
        
        self->req_width = (int)ScreenWidth;
        self->req_height = (int)ScreenHeight;
        self->width = [NSNumber numberWithInt:ScreenWidth *screenScale].intValue;
        self->height = [NSNumber numberWithInt:ScreenHeight *screenScale].intValue;
        
        NSLog(@"jsonStr:%@",[self toJsonString:params]);

        WeakSelf
           [CTAPIBaseManager POST5:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
               dispatch_async(dispatch_get_main_queue(), ^{
                 
                   
                   if (responseObject) {
                       NSLog(@"%@",[self toJsonString:responseObject]);
                   }
                   
                   
                   if (responseObject) {
                       NSString *ret = responseObject[@"ret"];
                       if ([ret isEqualToString:@"0"]) {
                           self->img_url = responseObject[@"adInfos"][0][@"img_url"];
                           self->impress_notice_urls = responseObject[@"adInfos"][0][@"impress_notice_urls"];
                           self->click_url = responseObject[@"adInfos"][0][@"click_url"];
                           self->click_notice_urls = responseObject[@"adInfos"][0][@"click_notice_urls"];
                           
                           
                           
                           UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
                           
                           PrivateLetterTap.delegate = weakSelf;
                           
                           PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
                           PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
                           [weakSelf.imgView addGestureRecognizer:PrivateLetterTap];
                           
                           [weakSelf.view addSubview:weakSelf.imgView];
                           [weakSelf.view addSubview:weakSelf.skipBtn];
                           [weakSelf.skipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                                make.right.equalTo(@(-30));
                                make.top.equalTo(@(35));
                           }];
                           
                           [weakSelf.imgView sd_setImageWithURL:[NSURL URLWithString:self->img_url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                               
                               if (error) {
                                   if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(MyAd_Fail:)]) {
                                                         [weakSelf.delegate MyAd_Fail:weakSelf];
                                                     }
                                   
                                   return ;
                               }else{
                                   [weakSelf loadOtherData:self->impress_notice_urls];
                                   
                                   if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(MyAd_show:)]) {
                                       [weakSelf.delegate MyAd_show:weakSelf];
                                       
                                       return;
                                   }
                               }
                               
                           }];
                           
                           
                           
                       }
                   }
                   
                   
                   if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(MyAd_Fail:)]) {
                       [weakSelf.delegate MyAd_Fail:weakSelf];
                   }
               });
           }];
        
    });
    
}

- (NSString *)toJsonString:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    str = [NSString stringWithFormat:@"%@",str];
    return str;
}





//返回曝光检测地址请求
- (void)loadOtherData:(NSArray *)array
{
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_queue_t searialQueue = dispatch_queue_create("com.liuliangyunying.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(@"返回曝光地址请求");
            });
        });
    });
}








#pragma mark - event response
-(void)tapAvatarView:(UITapGestureRecognizer*)gg
{
       
    NSLog(@"%s",__func__);
    
   click_url = [click_url stringByReplacingOccurrencesOfString:@"__REQ_WIDTH__"withString:[NSString stringWithFormat:@"%d",req_width]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__REQ_HEIGHT__" withString:[NSString stringWithFormat:@"%d",req_height]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__WIDTH__" withString:[NSString stringWithFormat:@"%d",width]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__HEIGHT__" withString:[NSString stringWithFormat:@"%d",height]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__DOWN_X__" withString:[NSString stringWithFormat:@"%d",req_x]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__DOWN_Y__" withString:[NSString stringWithFormat:@"%d",req_y]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__UP_X__" withString:[NSString stringWithFormat:@"%d",req_x]];
    click_url = [click_url stringByReplacingOccurrencesOfString:@"__UP_Y__" withString:[NSString stringWithFormat:@"%d",req_y]];
    NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:click_notice_urls copyItems:YES];
    for (int i = 0; i < newArray.count; i++) {
        NSString *str = newArray[i];
        str = [str stringByReplacingOccurrencesOfString:@"__REQ_WIDTH__"withString:[NSString stringWithFormat:@"%d",req_width]];
        str = [str stringByReplacingOccurrencesOfString:@"__REQ_HEIGHT__" withString:[NSString stringWithFormat:@"%d",req_height]];
        str = [str stringByReplacingOccurrencesOfString:@"__WIDTH__" withString:[NSString stringWithFormat:@"%d",width]];
        str = [str stringByReplacingOccurrencesOfString:@"__HEIGHT__" withString:[NSString stringWithFormat:@"%d",height]];
        str = [str stringByReplacingOccurrencesOfString:@"__DOWN_X__" withString:[NSString stringWithFormat:@"%d",req_x]];
        str = [str stringByReplacingOccurrencesOfString:@"__DOWN_Y__" withString:[NSString stringWithFormat:@"%d",req_y]];
        str = [str stringByReplacingOccurrencesOfString:@"__UP_X__" withString:[NSString stringWithFormat:@"%d",req_x]];
        str = [str stringByReplacingOccurrencesOfString:@"__UP_Y__" withString:[NSString stringWithFormat:@"%d",req_y]];
        
        [newArray replaceObjectAtIndex:i withObject:str];
    }
    
    click_notice_urls = newArray;
    
    if (click_notice_urls.count > 0) {
        NSDictionary *dic = @{
               @"url":![NSString blankString:click_url] ? click_url :@"",
               @"click_tracking_urls":click_notice_urls
               };
               if (self.delegate && [self.delegate respondsToSelector:@selector(MyAd_Click:vc:)]) {
                   [self.delegate MyAd_Click:dic vc:self];
               }
        
    }
    
   
}


-(void)removeLun
{
    [self.imgView removeFromSuperview];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(MyAd_DismissWithVC:)]) {
        [self.delegate MyAd_DismissWithVC:self];
    }
    
}


#pragma mark - UIGestureRecognizerDelegate

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"%s",__func__);
    //获取手指对象
    UITouch *touch = [touches anyObject];
    CGPoint curP = [touch locationInView:self.view];
    
    req_x = (int)curP.x;
    req_y = (int)curP.y;
    
    NSLog(@"触摸开始时x:%f,y:%f",curP.x,curP.y);
    
}







#pragma mark - private methods
- (void)startTimer
{
    NSLog(@">>>>%@",self.imgView);
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self ticktock];
    }];
    
    
}

- (void)ticktock
{
    if (!AdCount) {//计时器为0
        
        [self.timer invalidate];
        
        [self removeLun];
       
        
        
        return;
    }
    
    [_skipBtn setTitle:[NSString stringWithFormat:@"跳过 %@s",@(AdCount--)] forState:UIControlStateNormal];
    [_skipBtn sizeToFit];
}


//广告开始

- (void) show
{
    
    
    //启动定时器
    [self startTimer];
}

- (void)dismiss
{
    [self.timer invalidate];
    [self removeLun];
}


#pragma mark - getters and setters

- (UIImageView *)imgView
{
    if (!_imgView) {
        _imgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
        
        _imgView.contentMode = UIViewContentModeScaleAspectFill;
        _imgView.backgroundColor = [UIColor whiteColor];
        _imgView.userInteractionEnabled = YES;
    }
    
    return _imgView;
}

- (UIButton *)skipBtn
{
    if (!_skipBtn) {
        _skipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_skipBtn setTitle:[NSString stringWithFormat:@"跳过 %lus",(unsigned long)AdCount] forState:UIControlStateNormal];
        _skipBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _skipBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [_skipBtn setContentEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 10)];
        _skipBtn.layer.cornerRadius = 4.0;
        [_skipBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _skipBtn;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
