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

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



@interface TaScreenView ()

@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) DZYLImageView* imageView;
@property(nonatomic, strong) NSDictionary* param;


@end

@implementation TaScreenView

+(instancetype)adViewWithAdslotId:(NSString*)adslotId
             parentViewController:(UIViewController*)parentViewController
                     successBlock:(void(^)(void))success
                      failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
    if (!adslotId || adslotId.length == 0) {
        if (failed) {
            failed();
        }
    }
    TaScreenView *aView = [[TaScreenView alloc] initWithFrame:CGRectZero  successBlock:success failedBlock:failed closedBlock:closed];
    aView.adslotId = adslotId;
    aView.parentViewController = parentViewController;
    [aView loadRequest];
    return aView;
}

-(instancetype)initWithFrame:(CGRect)frame
                successBlock:(void(^)(void))success
                 failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
    if (self = [super initWithFrame:CGRectMake(0, 0, Ta_SCREEN_WIDTH, Ta_SCREEN_HEIGHT)]) {
        self.success = success;
        self.failed = failed;
        self.closed =closed;
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        self.imageView = [[DZYLImageView alloc] initWithFrame:CGRectMake(100, 100, Ta_SCREEN_WIDTH*0.8, Ta_SCREEN_WIDTH*0.8)];
        self.imageView.center = CGPointMake(Ta_SCREEN_WIDTH/2, Ta_SCREEN_HEIGHT/2);
        self.imageView.backgroundColor = [UIColor clearColor];
        self.imageView.userInteractionEnabled = YES;
        [self addSubview:self.imageView];
        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:@"Ta_close" 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:)]];
        
    }
    return self;
}

-(void)loadRequest
{
    [super loadRequest];

    NSDictionary *parameters = @{@"adslot_id":self.adslotId};
    
    __weak TaScreenView *weakSelf = self;
    
    [TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
        self.param = resultObj;
        self.clickUrl = [resultObj objectForKey:@"click_url"];
        weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];

        NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
        
       
        if (imageUrlStr && ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
            [TaUtils addIconForView:self.imageView paramter:resultObj 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) {
                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;
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1;
    }];
}

-(void)tapped:(UITapGestureRecognizer*)tap
{
    if (self.canTap) {

        [TaTmHelper clickAdWithParam:self.param];
         [self close:nil];
        TaSimpleWebViewController *web = [TaSimpleWebViewController new];
        web.url = self.clickUrl;
        web.ad_title = self.ad_title;
        if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
            NSLog(@"push");
            UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
            self.parentViewController.navigationItem.backBarButtonItem = item;
            [self.parentViewController.navigationController pushViewController:web animated:YES];
        }else{
            NSLog(@"present");
            UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
            [self.parentViewController presentViewController:navi animated:YES completion:nil];
        }
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.clickUrl]];
    }
}

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


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

    if (self.closed) {
        self.closed();
    }
     [self removeFromSuperview];
}

@end
