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

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

@interface TaDriftView ()

@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 TaDriftView

+(instancetype)adViewWithOrigin:(CGPoint)origin
                       adslotId:(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();
        }
    }
    
    TaDriftView *aView = [[TaDriftView alloc] initWithFrame:CGRectMake(origin.x, origin.y, 75, 75) 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(frame.origin.x, frame.origin.y, 75, 75)]) {
        self.success = success;
        self.failed = failed;
        self.closed=closed;
        self.imageView = [[DZYLImageView alloc] initWithFrame:self.bounds];
        [self addSubview:self.imageView];
        self.imageView.backgroundColor = [UIColor clearColor];
        self.alpha = 0;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}


-(void)loadRequest
{
    [super loadRequest];
    
    NSDictionary *parameters = @{@"adslot_id":self.adslotId};
    
    __weak TaDriftView *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 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];
        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.hidesBottomBarWhenPushed = YES;
            [self.parentViewController.navigationController pushViewController:web animated:YES];
            self.parentViewController.hidesBottomBarWhenPushed = NO;
        }else{
            NSLog(@"present");
            UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
            [self.parentViewController presentViewController:navi animated:YES completion:nil];
        }
    }
}

-(void)closePress{
   
    if (self.closed) {
        self.closed();
    }
     [self removeFromSuperview];
}
@end
