//
//  MyFruitViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/7/23.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "MyFruitViewController.h"

//变现猫广告
#import "DHCWNativeRenderAd.h"
#import "DHCWNativeAdView.h"
#import "LocalPlayerVideoManager.h"
#import "HomeCollectionItem2Cell.h"
#import "DHCWNativeLocalVideoAd.h"

#import "KKActivityViewController.h"

#import <BXMediaSDK/BXMediaMaterialManager.h>
#import <SDWebImage/UIButton+WebCache.h>
@interface MyFruitViewController ()<DHCWNativeRenderAdDelegate,DHCWNativeAdViewDelegate,DHCWNativeLocaVideoAdDelegate>

//变现猫
@property (nonatomic, strong) DHCWNativeRenderAd *nativeAd;
@property (nonatomic, strong) NSMutableArray *adDataArray;
@property (nonatomic, strong) UIButton *firstBtn;
@property (nonatomic,strong) UIView *oldView;
@property (nonatomic, strong)UILabel *countdownLab;
@property (nonatomic) dispatch_source_t timer;
@end

@implementation MyFruitViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
         
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    
    //加载变现猫
    [self loadBXMADViews];
    
//    NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:self.placeId userId:@"" materialModel:nil];
    
    [self lodData];
    
    //悬浮倒计时闹钟
    if (self.TaskModel.clickeventFlag == 601 && self.TaskModel.taskStatus == 305) {
        [self SuspensionCountdown];
    }
}
#pragma mark - 悬浮倒计时闹钟
- (void)SuspensionCountdown{
    UIView *SuspensionView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 80, ScreenHeight -  200, 60, 80)];
    [self.view addSubview:SuspensionView];
    [self.view bringSubviewToFront:SuspensionView];
    UIPanGestureRecognizer   *panTouch    =   [[UIPanGestureRecognizer  alloc]initWithTarget:self action:@selector(handlePan:)];
    [SuspensionView addGestureRecognizer:panTouch];
    
    UIImageView *alarmImgView = [[UIImageView alloc]initWithFrame:CGRectMake(9.5, 0, 41, 46)];
    alarmImgView.image = [UIImage imageNamed:@"alarm"];
    [SuspensionView addSubview:alarmImgView];
    
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 35, 60, 30)];
    baseView.backgroundColor = [UIColor colorWithHex:0xff9126];
    baseView.layer.masksToBounds = YES;
    baseView.layer.cornerRadius = 15;
    [SuspensionView addSubview:baseView];
    
    UILabel *countdownLab = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 50, 30)];
    countdownLab.textAlignment = NSTextAlignmentCenter;
    countdownLab.text = @"浏览10秒领取奖励";
    countdownLab.textColor = [UIColor whiteColor];
    countdownLab.font = [UIFont boldSystemFontOfSize:10];
    countdownLab.numberOfLines = 0;
    [baseView addSubview:countdownLab];
    self.countdownLab = countdownLab;
    
    [self updateCountdownUI];
}
/**
 *  处理拖动手势
 *
 *  @param recognizer 拖动手势识别器对象实例
 */
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    //视图前置操作
    [recognizer.view.superview bringSubviewToFront:recognizer.view];
    
    CGPoint center = recognizer.view.center;
    CGFloat cornerRadius = recognizer.view.frame.size.width / 2;
    CGPoint translation = [recognizer translationInView:self.view];
    //NSLog(@"%@", NSStringFromCGPoint(translation));
    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
    
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        //计算速度向量的长度，当他小于200时，滑行会很短
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult); //e.g. 397.973175, slideMult: 1.989866
        
        //基于速度和速度因素计算一个终点
        float slideFactor = 0.1 * slideMult;
        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),
                                         center.y + (velocity.y * slideFactor));
        //限制最小［cornerRadius］和最大边界值［self.view.bounds.size.width - cornerRadius］，以免拖动出屏幕界限
        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),
                           self.view.bounds.size.width - cornerRadius);
        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),
                           self.view.bounds.size.height - cornerRadius);
        
        //使用 UIView 动画使 view 滑行到终点
        [UIView animateWithDuration:slideFactor*2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             recognizer.view.center = finalPoint;
                         }
                         completion:nil];
    }
}
- (void)updateCountdownUI{
    typeof(self) wSelf = self;
    // 倒计时时间
    __block int timeout         = self.TaskModel.clickTime;
    dispatch_queue_t queue      = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer  = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

    // 每秒执行
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{

        if (timeout <= 0)
        {
            //取消
            dispatch_source_cancel(wSelf.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 设置界面的按钮显示，根据自己需求设置
                wSelf.countdownLab.text = @"奖励已发放";
            });
        }
        else
        {
            
            NSString *strTime = [NSString stringWithFormat:@"浏览%i秒领取奖励", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                wSelf.countdownLab.text = strTime;
            });
            timeout--;
        }
    });
    //恢复
    dispatch_resume(_timer);
}
- (void)dealloc
{
    //移除定时器
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil; // OK
    }
}
- (void)setupUI
{
    
    //bg
    UIImageView *bgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 181, ScreenWidth, 181)];
    
    //bgView.contentMode = UIViewContentModeScaleAspectFill;
    
    bgView.image = [UIImage imageNamed:@"fruit_bg"];
    
    [self.view addSubview:bgView];
    
//    //top
//    UIImageView *topIcon = [[UIImageView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 15 * WIDTHRADIU)];
//
//    topIcon.contentMode = UIViewContentModeScaleAspectFill;
//
//    topIcon.image = [UIImage imageNamed:@"jingtie_topbg"];
//
//    [self.view addSubview:topIcon];
    //newBtn
//    UIButton *newBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [newBtn setBackgroundImage:[UIImage imageNamed:@"fruit_new"] forState:UIControlStateNormal];
//    [newBtn addTarget:self action:@selector(newBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:newBtn];
//    self.firstBtn = newBtn;
//
//    [newBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).offset(70 * WIDTHRADIU + NAV_BAR_HEIGHT);
//        make.centerX.equalTo(self.view);
//        make.width.offset(300 * WIDTHRADIU);
//        make.height.offset(150 * WIDTHRADIU);
//    }];
    
    //oldBtn
    UIButton *oldBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [oldBtn setBackgroundImage:[UIImage imageNamed:@"fruit_old"] forState:UIControlStateNormal];
    [oldBtn addTarget:self action:@selector(oldBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:oldBtn];
    
    self.oldView = [[UIView alloc]init];
    [self.view addSubview:self.oldView];
    
    [oldBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50 * WIDTHRADIU+NAV_BAR_HEIGHT);
        make.centerX.equalTo(self.view);
        make.width.offset(300 * WIDTHRADIU);
        make.height.offset(150 * WIDTHRADIU);
    }];
    [self.oldView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.width.height.equalTo(oldBtn);
    }];
    
}


- (void)creatAdViewWithModel:(DHCWNativeAdDataObject *)model
{
    NativeAdCustomView *adView = [[NativeAdCustomView alloc] initWithFrame:CGRectMake(0, 0, 300 * WIDTHRADIU, 150 * WIDTHRADIU)];
    [self.oldView addSubview:adView];
    
    [adView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
    } ];
    
    // 以下代码实现 请严谨按该顺序执行
    adView.delegate = self;

    [adView registerDataObject:model container:adView clickableViews:@[adView.clickButton]];
    adView.rootViewController = self;
    [adView setupWithModel:model];
    
    /**
            可选操作
     */
    DHCWNativeLocalVideoAd *localVideoAd = [[DHCWNativeLocalVideoAd alloc]init];
    localVideoAd.delegate = self;
    [adView configNativeLocalVideoAd:localVideoAd];
}

#pragma mark - BXMNativeAdDelegate
/// 广告加载成功
-(void)nativeRendAdsSuccessToLoad:(NSArray<DHCWNativeAdDataObject *> *)nativeAdDataArray nativeAd:(DHCWNativeRenderAd *)nativeAd
{
    //清空新果园的点击事件
    [UserDefault setInteger:0 forKey:@"fruitVC"];
    [UserDefault synchronize];
    
    NSLog(@"______自渲染加载成功");
    self.adDataArray = [NSMutableArray arrayWithArray:nativeAdDataArray];
    
    if (self.adDataArray.count > 0) {
        DHCWNativeAdDataObject *model = self.adDataArray[0];
        
        [self creatAdViewWithModel:model];
    }
}

/// 广告加载失败
-(void)nativeRendAdsLoadFailWithError:(NSError *)error nativeAd:(DHCWNativeRenderAd *)nativeAd
{
    NSString *toast = [NSString stringWithFormat:@"广告加载失败，code：%ld，%@", error.code, error.localizedDescription];
    NSLog(@"变现猫error:%@",toast);
}

#pragma mark - BXMNativeAdViewDelegate

/// 广告被点击
 - (void)nativeAdDidClick
{
    NSLog(@"______自渲染点击");
}

/// 广告详情页关闭
- (void)nativeAdDetailViewDidClosed
{
    NSLog(@"______关闭详情页");
}
#pragma mark ---------BXMNativeLocaVideoAdDelegate
/**
    加载视频
 */
-(void)loadNativeVideoWithAdId:(NSString *)adId loadVideoType:(DWLocalVideoType)videoType localVideoAd:(nonnull DHCWNativeLocalVideoAd *)localVideoAd
{
    [[LocalPlayerVideoManager manager]localVideoAd:localVideoAd];
}

/**
        展示视频
 */
-(void)showNativeVideoFromController:(UIViewController *)controller localVideoAd:(DHCWNativeLocalVideoAd *)localVideoAd
{
    
    [[LocalPlayerVideoManager manager] showVideoFromController:controller];
}



#pragma mark - 加载变现猫广告
- (void)loadBXMADViews
{
    self.nativeAd = [[DHCWNativeRenderAd alloc] initWithAdId:@"807696003001" imageSize:DWAdImageSize_Feed690_388];
    self.nativeAd.delegate = self;
    [self.nativeAd loadRendAdWithCount:1];
}




#pragma mark - event response
- (void)newBtnClick:(UIButton *)sender
{
//    NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:self.placeId userId:@"" materialModel:nil];
    
    NSInteger i = [UserDefault integerForKey:@"fruitVC"];
    
    i++;
    
    [UserDefault setInteger:i forKey:@"fruitVC"];
    [UserDefault synchronize];
    
    KKActivityViewController *vc = [KKActivityViewController new];
    vc.title = @"免费果园";
    vc.placeId = self.placeId;
    vc.buId = self.buId;
    vc.gdtAdId = self.gdtAdId;
//    vc.placeId = @"6666";
//    vc.buId = @"946405751";
//    vc.gdtAdId = @"2062615177198724";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)oldBtnClick:(UIButton *)sender
{
    NSLog(@"%@",@"果园!!!!!!!!1");
}
#pragma mark - 请求小满素材图片
- (void)lodData{
//    NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:self.placeId thirdUserId:@"" success:^(BXMMaterialModel *model) {
        
        NSLog(@"==========%@",model.materialPath);
        [self.firstBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:model.materialPath] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"fruit_new"]];
        
    } fail:^(NSString *error) {
        
    }];
}
/*
#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
