//
//  KKTabBarViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/2/20.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "KKTabBarViewController.h"
#import "CTAPIBaseManager.h"

#if TARGET_IPHONE_SIMULATOR

#else

//#import <JUnion/JUnion.h>
    
#endif

#import "RedPackageView.h"

#import "BPViewController.h"
#import "LoginVC.h"
#import "CoinsDetailListVC.h"



@interface KKTabBarViewController ()<CAAnimationDelegate>
{
    CGFloat statusBarHeight;
    UIEdgeInsets gSafeAreaInsets;
    UIButton* lastSelectBtn;
    
    BOOL isRequest;
    BOOL show;
    
    int timeLength;
    NSString *startTime;
    NSString *endTime;
}

@property (nonatomic, strong)UIView* kTabBarView;

@property (nonatomic, strong) CAShapeLayer *progressLayer;

@property (nonatomic, strong) CALayer *gradientLayer;


@property (strong, nonatomic)  dispatch_source_t timer;

@property (nonatomic, strong)  UIView*bg;

@property (nonatomic, strong) UILabel *lb_coins;

@end

@implementation KKTabBarViewController

- (instancetype)initWithType:(BOOL)fromHome{
    self = [super init];
    if (self) {
        self.fromHome = fromHome;
        
        if (self.fromHome) {
            timeLength = 1200;
        }else{
            timeLength = 3000;
        }
        
        
        NSString* time = nil;
        
        if (self.fromHome) {
            time = [UserDefault objectForKey:@"videoTimeCoins"];
        }else{
            time = [UserDefault objectForKey:@"videoTimePackage"];
        }
        
        if (time) {
            timeLength = time.intValue;
        }
        
        [self creatAnimaUI];
        
        //[self.view addSubview:self.kTabBarView];
        
        //获取看视频时间
        [self getTimeAboutWatchTVRequest:!self.fromHome];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    //self.tabBar.hidden = YES;
    //[self.cycleView resumeAnimation];
    //禁止手势返回
//    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
//    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
//    [self.view addGestureRecognizer:pan];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //[self.cycleView pauseAnimation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //init
    if ([UIScreen mainScreen].bounds.size.height > 811) {
        statusBarHeight = 44;
        gSafeAreaInsets = UIEdgeInsetsMake(44, 0, 34, 0);
    }else{
        statusBarHeight = 20;
        gSafeAreaInsets = UIEdgeInsetsMake(20, 0, 0, 0);
    }
    
    self.tabBar.barTintColor = [UIColor blackColor];
    

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //self.tabBar.hidden = YES;
    
   
    
    
    
    
    
    //[self.view addSubview:self.cycleView];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
   
}

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


- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    
    
    NSLog(@"页面已销毁");
    
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
//    dispatch_suspend(_timer);
//
//    dispatch_source_cancel(_timer);
//
    _timer =nil;// OK
}

#pragma mark - 创建动画
- (void)creatAnimaUI {
    
    CGFloat width = 50.0;
    CGFloat height = 50.0;
    
    //创建动画容器
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 70, cl_kNavigationBarHeight + 15, width, height)];
    bg.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bg];
    
    //金币
    UIImage* coinIcon = nil;
    if (self.fromHome){
        
        coinIcon = [UIImage imageNamed:@"my_Earncoins_icon_normal"];
        
        
    }else{
        
        coinIcon = [UIImage imageNamed:@"package"];
        
    }
    CGSize imageSize = CGSizeZero;
    if (self.fromHome) {
        imageSize = CGSizeMake(width/1.5, height/1.5);
    }else{
        CGFloat width1 = coinIcon.size.width/1.0;
        CGFloat height1 = coinIcon.size.height/1.0;
        
        imageSize = CGSizeMake(width1, height1);
    }
    
     
    
    UIImageView* coinImage = [UIImageView new];
    coinImage.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height);
    coinImage.center = CGPointMake(width/2, height/2);
   
    coinImage.image = coinIcon;
    
    [bg addSubview:coinImage];
    
    
    UIButton *coinsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    coinsBtn.bounds = coinImage.bounds;
    coinsBtn.center = coinImage.center;
    coinsBtn.backgroundColor = [UIColor clearColor];
    [coinsBtn addTarget:self action:@selector(coinsBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [bg addSubview:coinImage];
    [bg addSubview:coinsBtn];
    
    
    //贝塞尔曲线画圆弧
    
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(width/2, width/2) radius:(width-6)/2.0 startAngle:-M_PI/2 endAngle:3*M_PI/2 clockwise:YES];
    //设置颜色
    [[UIColor colorWithHex:0xF6F6F9] set];
    circlePath.lineWidth = 4;
    //开始绘图
    [circlePath stroke];
    
    //创建背景视图
    CAShapeLayer *bgLayer = [CAShapeLayer layer];
    bgLayer.frame = bg.bounds;
    bgLayer.fillColor = [UIColor clearColor].CGColor;//填充色 - 透明
    bgLayer.lineWidth = 4;//线条宽度
    bgLayer.strokeColor = [UIColor colorWithHex:0xe5e5e5].CGColor;//线条颜色
    bgLayer.strokeStart = 0;//起始点
    bgLayer.strokeEnd = 1;//终点
    bgLayer.lineCap = kCALineCapRound;//让线两端是圆滑的状态
    bgLayer.path = circlePath.CGPath;//这里就是把背景的路径设为之前贝塞尔曲线的那个路径
    [bg.layer addSublayer:bgLayer];
    self.bg = bg;
    
    //创建进度条视图
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = bg.bounds;
    _progressLayer.fillColor = [UIColor clearColor].CGColor;
    _progressLayer.lineWidth = 4;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.strokeColor = [UIColor yellowColor].CGColor;
    _progressLayer.strokeStart = 0;
    _progressLayer.strokeEnd = 0;
    _progressLayer.path = circlePath.CGPath;
    [bg.layer addSublayer:_progressLayer];
    
    
    //uilabel
    UILabel *lb_coins = [UILabel new];
    //lb_coins.text = self.number;
    lb_coins.textColor = [UIColor whiteColor];
    lb_coins.font = [UIFont boldSystemFontOfSize:14];
    lb_coins.textAlignment = NSTextAlignmentCenter;
    lb_coins.frame =  CGRectMake(0, width - 20, width, 20);
    lb_coins.layer.opacity = 0.0;
    [bg addSubview:lb_coins];
    self.lb_coins = lb_coins;
    
}

- (void)addMyProgressLayer{
    
    CGFloat width = 50.0;
    
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(width/2, width/2) radius:(width-6)/2.0 startAngle:-M_PI/2 endAngle:3*M_PI/2 clockwise:YES];
    //设置颜色
    [[UIColor colorWithHex:0xF6F6F9] set];
    circlePath.lineWidth = 4;
    //开始绘图
    [circlePath stroke];
    
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = self.bg.bounds;
    _progressLayer.fillColor = [UIColor clearColor].CGColor;
    _progressLayer.lineWidth = 4;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.strokeColor = [UIColor yellowColor].CGColor;
    _progressLayer.strokeStart = 0;
    _progressLayer.strokeEnd = 0;
    _progressLayer.path = circlePath.CGPath;
    [self.bg.layer addSublayer:_progressLayer];
}


#pragma mark - 通知绑定方法

///监听应用退到后台
 - (void)didEnterBackground
{
   
    //[self pausmeAnimation];
    //[self pauseTimer];
    [self pausmeAnimation];
}
///恢复旋转
- (void)didBecomeActive
{
//    self.isPause = NO;
//    [self.cycleView resetAnimation];
    //[self resumeTimer];
    [self resumeAnimation];
}



#pragma mark - 定时器
//开启倒计时效果

- (void)openCountdown {


    if (self.timer == nil) {
        __block NSInteger time = timeLength; //倒计时时间
        __weak __typeof(self) weakSelf = self;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        

        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,0.1*NSEC_PER_SEC, 0); //每秒执行
        

        dispatch_source_set_event_handler(timer, ^{
            __strong typeof(self) strongSelf = weakSelf;

            if(time <= 0){ //倒计时结束，关闭
                time = strongSelf->timeLength;
                strongSelf->isRequest = YES;
//                dispatch_suspend(timer);
//                if(self.timer){
//                    dispatch_suspend(self.timer);
//                }else{
//                    dispatch_suspend(timer);
//                }
               // [self stopTimer];
                
                

                dispatch_source_cancel(timer);

                dispatch_async(dispatch_get_main_queue(), ^{
                    strongSelf->endTime = [NSString stringWithFormat:@"%@",@([strongSelf getNowTimeTimestamp3])];
                    NSString *recordId =  [strongSelf.videoIdArray componentsJoinedByString:@","];
                    if (strongSelf.fromHome) {
                        [strongSelf getCoinsByWhatVideosWithwathchRecordId:recordId];
                    }else{
                        [strongSelf getPackageByWatchVideosAtFirstTime:strongSelf->startTime endTime:strongSelf->endTime wathchRecordId:recordId];
                    }
                    
                    //self.progressLayer.strokeEnd = (1.0 - time/1200.0);
                    //设置按钮的样式
                    //[self startFirstAnimate];
     //                if (self.block) {
     //                    self.block();
     //                }
                });

            }else{
                if (time == 120) {
                    strongSelf->startTime = [NSString stringWithFormat:@"%@",@([strongSelf getNowTimeTimestamp3])];
                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    strongSelf.progressLayer.strokeEnd = (1.0 - time/(float)strongSelf->timeLength);
                    NSLog(@">>>>>>%.2ld",(long)time);

                });

                time--;
                
            }
        });

        dispatch_resume(timer);
         
         self.timer = timer;
    }
   
}

-(void) pauseTimer{
    if(self.timer){
        dispatch_suspend(_timer);
    }
}
-(void) resumeTimer{
    if(self.timer){
        dispatch_resume(_timer);
    }
}
-(void) stopTimer{
    if(self.timer){
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}




#pragma mark - 获取看视频时间
- (void)getTimeAboutWatchTVRequest:(BOOL)isPackage {
    NSString *url = [NSString stringWithFormat:@"%@sysinit/AndroidVideoParam",CoinsBaseUrl];
    NSDictionary *params = nil;
    if (isPackage) {
        params = @{
            @"activeType":@(100121)
                              };
    }
    
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"responseObject:%@,error:%@",responseObject,error);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            if ([code isEqualToString:@"0"]) {
                if (isPackage) {
                    [UserDefault setObject:[NSString stringWithFormat:@"%@",responseObject[@"result"]] forKey:@"videoTimePackage"];
                }else{
                    [UserDefault setObject:[NSString stringWithFormat:@"%@",responseObject[@"result"]] forKey:@"videoTimeCoins"];
                }
            }
        }
        
        
    }];
    
}


#pragma mark - 看视频得金币
- (void)getCoinsByWhatVideosWithwathchRecordId:(NSString *)wathchRecordId{
    NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
    currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":@"1020",
                          @"reqTimesTamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2"
                          };
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    [params setObject:currentVersion forKey:@"versionCode"];
    [params setObject:@"kksh" forKey:@"termalInfo"];
    [params setObject:wathchRecordId forKey:@"wathchRecordId"];
    
    
    
    //[KKLoadingAnimationView show];
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        [self.videoIdArray removeAllObjects];
        [self.endvideoIdArray removeAllObjects];
       
        //[KKLoadingAnimationView dismiss];
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 1006) {
                    //@1缩放s动画
                    [self refreshCoins];
                    NSNumber *score = responseObject[@"result"][@"score"];
                    if ([score isKindOfClass:[NSNumber class]]) {
                        NSString *number = [NSString stringWithFormat:@"+%@",score];
                        self.lb_coins.text = number;
                        [self startThirdAnimate];
                        return;
                    }
                   
                   
                   
                }
               
              
               
            }
           
          
        }
        self->isRequest = NO;
        [self.progressLayer removeFromSuperlayer];
        self.progressLayer = nil;
        [self addMyProgressLayer];
        self.timer = nil;
        [self openCountdown];
     }];
    
}

#pragma mark - 看视频得红包
- (void)getPackageByWatchVideosAtFirstTime:(NSString *)firstTime endTime:(NSString *)endTime wathchRecordId:(NSString *)wathchRecordId  {
    NSString *url = [NSString stringWithFormat:@"%@news/moneybynews",CoinsBaseUrl];
    NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
    currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSDictionary *dic = @{
                          @"uid":@([getPeopleID PeopleID]),
                          @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":@"1020",
                          @"watchstarttime":firstTime,
                          @"watchendtime":endTime,
                          @"fromModel":@"2"
                          };
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    [params setObject:currentVersion forKey:@"versionCode"];
    [params setObject:@"kksh" forKey:@"termalInfo"];
    [params setObject:wathchRecordId forKey:@"wathchRecordId"];
    
    //[KKLoadingAnimationView show];
       [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
           //[KKLoadingAnimationView dismiss];
           [self.videoIdArray removeAllObjects];
           [self.endvideoIdArray removeAllObjects];
           if (responseObject) {
               NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
               NSString *des = [NSString stringWithFormat:@"%@",responseObject[@"des"]];
               if ([code isEqualToString:@"0"]) {

                NSString *packageMoney = responseObject[@"result"];

                NSString*money = [NSString stringWithFormat:@"+%0.2f",packageMoney.doubleValue];
                //self.lb_coins.text = money;
                //[self startThirdAnimate];
                self->isRequest = NO;
                [self.progressLayer removeFromSuperlayer];
                self.progressLayer = nil;
                [self addMyProgressLayer];
                self.timer = nil;
                [self openCountdown];
                [self refreshCoins];
                [RedPackageView showMoneyWithVC:self money:money type:KKRedPackageTypeMoney from:RedPackageFromWatchTV  block:^(BOOL success) {
                    if (success) {
                      
                    }
                }];
                return;

               }else if ([code isEqualToString:@"9992"]){
                   [SVProgressHUD showErrorWithStatus:@"当天红包金额已超限"];
               } else{
                   [SVProgressHUD showErrorWithStatus:des];
               }


           }
           self->isRequest = NO;
           [self.progressLayer removeFromSuperlayer];
           self.progressLayer = nil;
           [self addMyProgressLayer];
           self.timer = nil;
           [self openCountdown];
       }];
}

#pragma mark - 刷新金币
//获取金币数
- (void)refreshCoins
{
    if ([getPeopleID PeopleID] && [getPeopleID PeopleIphoneNmber])
    {
        NSDictionary *params = @{
                                 @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                 @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                                 };
        NSString *url =[NSString stringWithFormat:@"%@score/getpersonintegrals",CoinsBaseUrl];
//        WeakSelf
        [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
           
            if (responseObj) {
                NSString *code = [responseObj[@"code"] stringValue];
                if ([code isEqualToString:@"0"]) {
                    [getPeopleID getTotalCoins:responseObj[@"result"]];
//                    NSDictionary *dic = [getPeopleID totalCoins];
//                    NSNumber *num = dic[@"totalScore"];
                }
            }
            
        }];
    }
}


#pragma mark - 动画创建
- (void)startThirdAnimate{
    
    CGFloat width = 50.0;
    CGFloat height = 50.0;
    
    CABasicAnimation *an1= [CABasicAnimation animation];
    an1.keyPath = @"position";
    an1.fromValue=[NSValue valueWithCGPoint:CGPointMake(width/2, height - 10)];
    an1.toValue=[NSValue valueWithCGPoint:CGPointMake(width/2, 10)];
    
    
    CABasicAnimation *an2= [CABasicAnimation animation];
    an2.keyPath = @"opacity";
    an2.toValue = @(0.0);
    
    
    CAAnimationGroup *groupAnima = [CAAnimationGroup animation];
    //groupAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    groupAnima.animations = @[an1, an2];
    groupAnima.duration = 1.0;
    groupAnima.fillMode = kCAFillModeForwards;
    groupAnima.removedOnCompletion = NO;
    groupAnima.delegate = self;
    [groupAnima setValue:@"animation3" forKey:@"AnimationKey"];
    [self.lb_coins.layer addAnimation:groupAnima forKey:nil];
    
    self.lb_coins.layer.opacity = 1.0;
    
}

- (void)startFourAnimate {
    
    CABasicAnimation *pathAnima = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];

    pathAnima.duration = 10;
    //pathAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnima.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnima.toValue = [NSNumber numberWithFloat:1.0f];
    pathAnima.fillMode = kCAFillModeForwards;
    pathAnima.removedOnCompletion = NO;
    pathAnima.delegate = self;
    [pathAnima setValue:@"animation4" forKey:@"AnimationKey"];
    [_progressLayer addAnimation:pathAnima forKey:nil];
}
#pragma mark - 动画重置

- (void)resetAnimation {
    //1
    [self.progressLayer removeAllAnimations];
    [self startFourAnimate];
    //[self openCountdown];
}

//暂停layer上面的动画
- (void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

//继续layer上面的动画
- (void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}


#pragma mark - CAAnimationDelegate
- (void)animationDidStart:(CAAnimation *)anim {
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    if ([[anim valueForKey:@"AnimationKey"] isEqualToString:@"animation2"]) {
        
        
    }else if ([[anim valueForKey:@"AnimationKey"] isEqualToString:@"animation3"]) {
        isRequest = NO;
        //self.progressLayer.strokeEnd = 0;
        [self.progressLayer removeFromSuperlayer];
        self.progressLayer = nil;
        [self addMyProgressLayer];
        self.lb_coins.layer.opacity = 0.0;
        [self.lb_coins.layer removeAllAnimations];
        self.timer = nil;
        [self openCountdown];
        
    }else if([[anim valueForKey:@"AnimationKey"] isEqualToString:@"animation1"]) {
        
    }else if ([[anim valueForKey:@"AnimationKey"] isEqualToString:@"animation4"]) {
       
        //[self startFourAnimate];
    }
    
}


#pragma mark - 添加视频id
- (void)addVideoId:(NSString *)videoId {
    __block BOOL isExist = NO;
     [self.videoIdArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:videoId]) {//数组中已经存在该对象
                    *stop = YES;
                    isExist = YES;
              }
    }];
    if (!isExist) {//如果不存在就添加进去
    [self.videoIdArray addObject:videoId];
    }
}

- (void)addEndVideoId:(NSString *)videoId {
    __block BOOL isExist = NO;
     [self.endvideoIdArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:videoId]) {//数组中已经存在该对象
                    *stop = YES;
                    isExist = YES;
              }
    }];
    if (!isExist) {//如果不存在就添加进去
    [self.endvideoIdArray addObject:videoId];
    }
}

#pragma mark - 开始动画
- (void)startAnimation {
    
    if (isRequest) {
        return;
    }
    
    if (self.isStart) {
        return;
    }
    
    
    self.isStart = YES;
    show = YES;
    self.isPause = NO;
    [self openCountdown];
}

- (void)pausmeAnimation {
    
    if (isRequest) {
        return;
    }
    
    if (self.isPause) {
        return;
    }

    self.isPause = YES;
    show = NO;
    
    //[self pauseLayer:self.progressLayer];
    [self pauseTimer];
}

- (void)resumeAnimation {
    
    if (isRequest) {
        return;
    }
    
    if (show) {
        return;
    }
    
    show = YES;
    self.isPause = NO;
//    [self.cycleView resumeAnimation];
    //[self resumeLayer:self.progressLayer];
    [self resumeTimer];
}

#pragma mark - event response
- (void)btnClick:(UIButton *)sender {
    if (sender == lastSelectBtn) {
        return;
    }
    lastSelectBtn.selected = NO;
    sender.selected = YES;
    lastSelectBtn = sender;
    self.selectedIndex = sender.tag - 200;
    
    if (self.selectedIndex == 1) {
        [self pausmeAnimation];
    }
}

- (void)coinsBtnClick:(UIButton *)sender {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
              return;
          }
    
    if (self.fromHome) {
        CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
        vc.title = @"金币明细";
        vc.type = ListVCTypeCoinsDetail;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
        vc.title = @"我的钱包";
        vc.type = ListVCTypeMyWallet;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


#pragma mark - 获取当前时间戳

-(NSInteger )getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSInteger timeSp = [datenow timeIntervalSince1970]*1000;
    
    return timeSp;
}

#pragma mark - getters and setters
- (UIView *)kTabBarView {
    if (!_kTabBarView) {
        _kTabBarView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height - gSafeAreaInsets.bottom - 49, ScreenWidth, gSafeAreaInsets.bottom + 49)];
        _kTabBarView.backgroundColor = [UIColor blackColor];
        UIButton* leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        leftBtn.frame = CGRectMake(0, 0, ScreenWidth/2, 49);
        [leftBtn setTitle:self.fromHome ? @"看视频" :@"红包视频" forState:UIControlStateNormal];
        [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [leftBtn setTitleColor:[UIColor colorWithHex:0x7a7a7a] forState:UIControlStateNormal];
        leftBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        leftBtn.tag = 200;
        [leftBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_kTabBarView addSubview:leftBtn];
        UIButton* rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(ScreenWidth/2, 0, ScreenWidth/2, 49);
        [rightBtn setTitle:@"更多" forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [rightBtn setTitleColor:[UIColor colorWithHex:0x7a7a7a] forState:UIControlStateNormal];
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        rightBtn.tag = 201;
        [rightBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_kTabBarView addSubview:rightBtn];
        leftBtn.selected = YES;
        lastSelectBtn = leftBtn;
    }
    return _kTabBarView;
}

- (NSMutableArray *)videoIdArray {
    if (!_videoIdArray) {
        _videoIdArray = [NSMutableArray array];
    }
    return _videoIdArray;
}

- (NSMutableArray *)endvideoIdArray {
    if (!_endvideoIdArray) {
        _endvideoIdArray = [NSMutableArray array];
    }
    return _endvideoIdArray;
}
//- (TBCycleView *)cycleView {
//    if (!_cycleView) {
//        WeakSelf
//        _cycleView = [[TBCycleView alloc]initWithFrame:CGRectMake(80, 80, 65, 65) count:timeLength number:@"+30" block:^{
//            [weakSelf getCoinsByWhatVideosWithwathchRecordId:nil];
//        }];
//    }
//    return _cycleView;;
//}

/*
#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
