//
//  TaLaunchScreenView.m
//  AdIOSSDK
//
//  Created by lc on 16/11/13.
//  Copyright © 2016年 Ta. All rights reserved.
//

#import "TaLaunchScreenView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"

@interface TaLaunchScreenView ()
{
    NSTimer *timer;
    NSInteger timerCount;
}

@property (nonatomic,assign) BOOL reportedDisplay;

@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UILabel *countLabel;
@property(nonatomic, strong) NSDictionary* param;

@property (nonatomic,copy) void(^finished)(void);
@property (nonatomic,copy) void(^userClose)(void);

@end

@implementation TaLaunchScreenView

+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
                         successBlock:(void(^)(void))success
                          failedBlock:(void(^)(void))failed
                        finishedBlock:(void(^)(void))finished
                       userCloseBlock:(void(^)(void))userClose
{
    return [TaLaunchScreenView adViewWithAdslotId:adslotId successBlock:success failedBlock:failed finishedBlock:finished userCloseBlock:userClose];
}

+(instancetype)adViewWithAdslotId:(NSString*)adslotId
                     successBlock:(void(^)(void))success
                      failedBlock:(void(^)(void))failed
                    finishedBlock:(void(^)(void))finished
                   userCloseBlock:(void(^)(void))userClose
{
    if (!adslotId || adslotId.length == 0) {
        if (failed) {
            failed();
        }
    }
    TaLaunchScreenView *aView = [[TaLaunchScreenView alloc] initWithFrame:CGRectZero  successBlock:success failedBlock:failed finishedBlock:finished userCloseBlock:userClose];
    aView.adslotId = adslotId;
    [aView loadRequest];
    return aView;
}

-(instancetype)initWithFrame:(CGRect)frame
                successBlock:(void(^)(void))success
                 failedBlock:(void(^)(void))failed
               finishedBlock:(void(^)(void))finished
              userCloseBlock:(void(^)(void))userClose
{
    CGRect appFrame = [UIScreen mainScreen].bounds;
    if (self = [super initWithFrame:appFrame]) {
        self.success = success;
        self.failed = failed;
        self.finished = finished;
        self.userClose = userClose;
        self.backgroundColor = [UIColor clearColor];
        self.imageView = [[UIImageView alloc] initWithFrame:appFrame];
        self.imageView.backgroundColor = [UIColor blackColor];
        self.imageView.userInteractionEnabled = YES;
        self.imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:self.imageView];
        
        self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(appFrame.size.width - 140, 30, 70, 20)];
        self.countLabel.backgroundColor = [UIColor clearColor];
        self.countLabel.font = [UIFont systemFontOfSize:12];
        self.countLabel.textColor = [UIColor whiteColor];
        self.countLabel.textAlignment = NSTextAlignmentRight;
        [self addSubview:self.countLabel];
        
    
        self.alpha = 0;
        
        
//        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(self.imageView.frame.size.width-26, 0, 26, 26)];
//        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"TaAd" ofType:@"bundle"]];
//        UIImage *image  = [UIImage imageWithContentsOfFile:[bundle pathForResource:@"TaDelete" ofType:@"png"]];
//        [btn setImage:image forState:UIControlStateNormal];
//        [self.imageView addSubview:btn];
//        
//        [btn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];
        
        [TaTmHelper helper].launchScreenAdView = self;
        
    }
    return self;
}

-(void)loadRequest
{
    [super loadRequest];
    
    NSDictionary *parameters = @{@"adslot_id":self.adslotId};
    
    __weak TaLaunchScreenView *weakSelf = self;
    
    [TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
        self.param = resultObj;
        self.clickUrl = [resultObj objectForKey:@"click_url"];
        NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
        self.ad_title = [resultObj objectForKey:@"ad_title"];
        UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.bounds.size.width - 60, 30, 45, 20)];
        closeBtn.backgroundColor = [UIColor clearColor];
        closeBtn.layer.cornerRadius = 10;
        closeBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        closeBtn.layer.borderWidth = 0.5;
        closeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [closeBtn setTitle:@"跳过" forState:UIControlStateNormal];
        if ([[resultObj objectForKey:@"ad_close_visible"] integerValue]==1)
            [self addSubview:closeBtn];
        [closeBtn addTarget:self action:@selector(userCloseAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        if (imageUrlStr&& ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
            //根据返回的字段确定是否加上关闭和广告字样
            NSNumber *ad_icon_visible = resultObj[@"ad_icon_visible"];
            if (!ad_icon_visible) {
                ad_icon_visible=@0;
            }
            NSDictionary *tmp =@{@"ad_close_visible":@"0",@"ad_icon_visible":ad_icon_visible};
            [TaUtils addIconForView:self paramter:tmp btn:@selector(closePress) caller:self];
            
            if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
                imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
            }
            
            [weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
                NSLog(@"weself.imageview:%@ iamge:%@, image2%@",weakSelf.imageView,weakSelf.imageView.image,[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]]);
                weakSelf.imageView.image = [DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
                if (weakSelf.success) {
                    weakSelf.success();
                }
                [weakSelf displayRequest];
            } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
                if (weakSelf.failed) {
                    weakSelf.failed();
                }
            }];
        }
    } failedBlock:^(id resultObj) {
        if (weakSelf.failed) {
            weakSelf.failed();
        }
    }];
}

-(void)displayRequest
{
    self.canTap = YES;
    if (!self.reportedDisplay) {
      
        [TaTmHelper displayAdWithParam:self.param];
        self.reportedDisplay = YES;
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
        timerCount = 5;
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRepeat:) userInfo:nil repeats:YES];
        [self show];
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1;
    }];
}

-(void)timerRepeat:(NSTimer*)aTimer
{
    if (timerCount < 0) {
        [timer invalidate];
        timer = nil;
        timerCount = 5;
        if (self.finished) {
            self.finished();
        }
        [self closeWithAnimation];
        return;
    }
    self.countLabel.text = [NSString stringWithFormat:@"剩余%ld秒",timerCount];
    timerCount --;
}

-(void)tapped:(UITapGestureRecognizer*)tap
{
    if (self.canTap) {
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
        timerCount = 5;
        if (self.finished) {
            self.finished();
        }
        [TaTmHelper clickAdWithParam:self.param];
        [self closeWithAnimation];
        TaSimpleWebViewController *web = [TaSimpleWebViewController new];
        web.url = self.clickUrl;
        web.ad_title = self.ad_title;
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
//        if ([rootViewController isKindOfClass:[UINavigationController class]]&&(rootViewController.navigationController.navigationBarHidden == NO)) {
//            NSLog(@"push, %d",rootViewController.navigationController.navigationBarHidden);
//            [(UINavigationController *)rootViewController pushViewController:web animated:YES];
//        }else{
            NSLog(@"present");
            UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
            [rootViewController presentViewController:navi animated:YES completion:nil];
            
        //}
    }
}

-(void)userCloseAction:(UIButton*)btn
{
    if (self.userClose) {
        self.userClose();
    }
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
    timerCount = 5;
    [self closeWithAnimation];
}

-(void)close:(id)sender
{
    [self removeFromSuperview];
}

-(void)closeWithAnimation
{
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


-(void)show
{
    [[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:self];
}
-(void)closePress{
    [self removeFromSuperview];
}
@end
