//
//  KKSVideoViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/5/10.
//  Copyright © 2021 黄江涛 . All rights reserved.
//
#import <KSAdSDK/KSCUContentPage.h>
#import "KKSVideoViewController.h"

#import "KKTabBarViewController.h"

#import "CTAPIBaseManager.h"

#import "RedPackageView.h"

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



@interface KKSVideoViewController ()<KSCUVideoStateDelegate,KSCUFeedPageCallBackProtocol,CAAnimationDelegate>
{
    CGFloat statusBarHeight;
    UIEdgeInsets gSafeAreaInsets;
    BOOL firstStart;
    
    BOOL isRequest;
    BOOL show;
    
    int timeLength;
    NSString *startTime;
    NSString *endTime;
}
@property (nonatomic, strong) KSCUContentPage *contentEcology;

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

@property (nonatomic,strong)NSMutableArray *videoIdArray;

@property (nonatomic,strong)NSMutableArray *endvideoIdArray;


@property (nonatomic, strong)UILabel *countdownLab; //领取倒计时

@property (nonatomic) dispatch_source_t Counttimer;
@end

@implementation KKSVideoViewController
- (instancetype)initWithType:(BOOL)fromHome{
    self = [super init];
    if (self) {
        _fromHome = fromHome;
    }
    return self;
}
- (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
    
    //移除定时器
    if (_Counttimer) {
        dispatch_source_cancel(_Counttimer);
        _Counttimer = nil; // OK
    }
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    //self.navigationController.tabBarController.tabBar.hidden = YES;
}


- (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);
    }
    
    if (_fromHome) {
        timeLength = 1200;
    }else{
        timeLength = 3000;
    }
    
    
    NSString* time = nil;
    
    if (_fromHome) {
        time = [UserDefault objectForKey:@"videoTimeCoins"];
    }else{
        time = [UserDefault objectForKey:@"videoTimePackage"];
    }
    
    if (time) {
        timeLength = time.intValue;
    }
    
    
    
    // 配置SDK
    [self configContentPage];
    
    //获取看视频时间
    [self getTimeAboutWatchTVRequest:!_fromHome];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    //悬浮倒计时闹钟
    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);
    _Counttimer  = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

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

        if (timeout <= 0)
        {
            //取消
            dispatch_source_cancel(wSelf.Counttimer);
            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(_Counttimer);
}

- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:navView];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight + 9.5, 50, 25);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    
    
    
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = @"看视频";
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
    
    
}


- (void)configContentPage {
    if (self.contentEcology) {
        [self.contentEcology.viewController removeFromParentViewController];
        self.contentEcology = nil;
    }
    NSString *posId = @"6030000009";
    self.contentEcology = [[KSCUContentPage alloc] initWithPosId:posId];
    self.contentEcology.videoStateDelegate = self;
    self.contentEcology.callBackDelegate = self;
    UIViewController *vc = self.contentEcology.viewController;
    [self addChildViewController:vc];
    vc.view.frame = self.view.bounds;
    [self.view addSubview:vc.view];
    
    [self navConfig];
    
    [self creatAnimaUI];
}



#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 (_fromHome){
        
        coinIcon = [UIImage imageNamed:@"my_Earncoins_icon_normal"];
        
        
    }else{
        
        coinIcon = [UIImage imageNamed:@"package"];
        
    }
    CGSize imageSize = CGSizeZero;
    if (_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)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) {
                    if (self.block) {
                        self.block(YES);
                    }
                    //@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"]) {

                   if (self.block) {
                       self.block(YES);
                   }
                
                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)didEnterBackground
{
    [self pausmeAnimation];
}
///恢复旋转
- (void)didBecomeActive
{
    [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)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 - KSCUVideoStateDelegate
/**
 * 视频开始播放
 * @param videoContent 内容模型
 */
- (void)kscu_videoDidStartPlay:(id<KSCUContentInfo>)videoContent
{
    NSLog(@"视频开始播放");
    
    if (!firstStart) {
        firstStart = YES;
        
        
        //第一次播放
        if (self.isStart) {
            [self resumeAnimation];
        }else{
            [self startAnimation];
        }
        
        
        if (![self.videoIdArray containsObject:videoContent.publicContentId] && (![Tools isBlankString:videoContent.publicContentId])) {
            //[tabVC resumeAnimation];
            
            [self addVideoId:videoContent.publicContentId];
        }
        
        
        
    }else{
        
        if (![self.videoIdArray containsObject:videoContent.publicContentId] && (![Tools isBlankString:videoContent.publicContentId])) {
            [self resumeAnimation];
            
            [self addVideoId:videoContent.publicContentId];
        }
        
    }
}
/**
* 视频暂停播放
* @param videoContent 内容模型
*/
- (void)kscu_videoDidPause:(id<KSCUContentInfo>)videoContent
{
    NSLog(@"视频暂停播放");
    
    
    if ([self.videoIdArray containsObject:videoContent.publicContentId] && ![self.endvideoIdArray containsObject:videoContent.publicContentId] && (![Tools isBlankString:videoContent.publicContentId])) {
        [self pausmeAnimation];
    }
    
}
/**
* 视频恢复播放
* @param videoContent 内容模型
*/
- (void)kscu_videoDidResume:(id<KSCUContentInfo>)videoContent
{
    NSLog(@"视频恢复播放");
    
    
    if ([self.videoIdArray containsObject:videoContent.publicContentId] && ![self.endvideoIdArray containsObject:videoContent.publicContentId] && (![Tools isBlankString:videoContent.publicContentId])) {
        [self resumeAnimation];
    }
    
}
/**
* 视频停止播放
* @param videoContent 内容模型
* @param finished     是否播放完成
*/
- (void)kscu_videoDidEndPlay:(id<KSCUContentInfo>)videoContent isFinished:(BOOL)finished
{
    NSLog(@"视频停止播放");
    
    if (finished) {
        
        
        if (![Tools isBlankString:videoContent.publicContentId]) {
            if (![self.endvideoIdArray containsObject:videoContent.publicContentId]) {
                [self pausmeAnimation];
            }
            
            [self addEndVideoId:videoContent.publicContentId];
        }
        
    }
    
}
/**
* 视频播放失败
* @param videoContent 内容模型
* @param error        失败原因
*/
- (void)kscu_videoDidFailedToPlay:(id<KSCUContentInfo>)videoContent withError:(NSError *)error
{
    NSLog(@"视频播放失败");
    
    [self pausmeAnimation];
}

#pragma mark - KSCUContentPageCallback
- (void)kscuClickContentShareWithItem:(NSString *)shareItem {
   // KSDemoShareMediaViewController *vc = [[KSDemoShareMediaViewController alloc] initWithShareItem:shareItem];
    //[self presentViewController:vc animated:YES completion:nil];
}


#pragma mark - event response
- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (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

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

- (NSMutableArray *)endvideoIdArray {
    if (!_endvideoIdArray) {
        _endvideoIdArray = [NSMutableArray array];
    }
    return _endvideoIdArray;
}


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