//
//  RewardPackageViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/5/9.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "RewardPackageViewController.h"
#import "UIView+frameAdjust.h"
#import "RewardPackageCell.h"
#import "LoginVC.h"

#import "RewardTimeAlertView.h"

//穿山甲
#import <BUAdSDK/BUAdSDK.h>
//腾讯广点通
#import <GDTRewardVideoAd.h>
#import <GDTSDKConfig.h>

#import "CTAPIBaseManager.h"
#import "RedPackageView.h"

@interface RewardPackageViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,BUNativeExpressRewardedVideoAdDelegate,GDTRewardedVideoAdDelegate>
{
    DDSubActiveModel*selectActiveModel;
}

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)UICollectionView* collectionView;

@property (nonatomic, strong)NSArray* titleArray;

@property (nonatomic, strong)NSArray* imageArray;

//穿山甲
@property (nonatomic, strong)BUNativeExpressRewardedVideoAd* rewardedAd;
//腾讯
@property (nonatomic, strong) GDTRewardVideoAd *rewardVideoAd;
@end

@implementation RewardPackageViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
    
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [GTCountSDK trackCountEvent:@"home_videoForRedPackage" withArgs:@{}];//个推统计
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    
    UIImage*image = [UIImage imageNamed:@"ad_bottomView"];
    //bottomImage
    UIImageView* ad_bottomView = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 345 * WIDTHRADIU)/2, ScreenHeight - 79 * WIDTHRADIU, 345 * WIDTHRADIU, 64 * WIDTHRADIU)];
    ad_bottomView.image = image;
    ad_bottomView.userInteractionEnabled = YES;
    [self.view addSubview:ad_bottomView];
    
    
    UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
    
    [ad_bottomView addGestureRecognizer:tap];
    
    
    //init
    //[BUAdSDKManager setAppID:@"5109638"];
    [GDTSDKConfig registerAppId:@"1111094678"];
}


#pragma mark - 抽奖
- (void)refreshCoins
{
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
        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"]];
                        
                        if ([self.navigationController.visibleViewController isKindOfClass:[RewardPackageViewController class]]) {
                            
                            WebVC *webVC = [[WebVC alloc]init];
                             webVC.type = @"home";
                             webVC.title = @"金币抽奖";
                             //外网http://nginx.weface.com.cn/lesson/award/src/award.html
                             //内网@"http://172.16.10.121/projects/html-nginx/html-nginx/lesson/award/src/award.html"
                            //webVC.url = @"http://nginx.weface.com.cn/lesson/award/src/award.html";
                              webVC.url = CoinsRewardedUrl;
                             webVC.hidesBottomBarWhenPushed =YES;
                             [weakSelf.navigationController pushViewController:webVC animated:YES];
                            
                        }
                        
                        
                    }
                }
            }];
        }
    }else {
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
    }
    
    
   
}


#pragma mark - 看视频得金币
- (void)getCoinsByWhatVideos:(NSString *)activeId{
    NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":activeId,
                          @"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"];
    
    
    
    
    
    
    
     WeakSelf
       [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
           
           if (responseObject) {
               NSNumber *code = responseObject[@"code"];
               if ([code isKindOfClass:[NSNumber class]]) {
                   if (code.integerValue == 1006) {
                       //@1缩放s动画
                       NSNumber *score = responseObject[@"result"][@"score"];
                       if ([score isKindOfClass:[NSNumber class]]) {
                           
                           if ([responseObject[@"result"] isKindOfClass:[NSDictionary class]]) {
                              NSDictionary* result = responseObject[@"result"];
                              NSString* rewardType = [NSString stringWithFormat:@"%@",result[@"rewardType"]];
                              
                              if ([rewardType isEqualToString:@"3001"]) {
                                  
                                  NSNumber*rewardMoney = result[@"rewardMoney"];
                                  NSString*money = [NSString stringWithFormat:@"%0.2f",rewardMoney.doubleValue];
                                  [RedPackageView showMoneyWithVC:self money:money type:KKRedPackageTypeMoney from:RedPackageFromWatchTV  block:^(BOOL success) {
                                      if (success) {
                                          
                                      }
                                  }];
                              }else if ([rewardType isEqualToString:@"3002"]){
                                   NSString*rewardCoins = [NSString stringWithFormat:@"%@",result[@"score"]];
                                  [RedPackageView showMoneyWithVC:self money:rewardCoins type:KKRedPackageTypeCoins from:RedPackageFromWatchTV  block:^(BOOL success) {
                                      if (success) {
                                         [weakSelf refreshCoins];
                                      }
                                  }];
                              }
                          }
                           
                           [self getRdactiveListRequest];
      
                       }
                       
                       
                       
                   }else if ([code isEqualToNumber:@1035]){
                       [SVProgressHUD showInfoWithStatus:@"当天次数已达上限"];
                   }else if ([code isEqualToNumber:@1036]){
                       [SVProgressHUD showInfoWithStatus:@"系统时间异常"];
                   }
                   
                  
                   
               }
               
              
           }
       }];
    
}

#pragma mark - 激励视频活动
- (NSDictionary *)getRdactiveListRequestParams
{
    NSDictionary *params = @{
        @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]]
    };
    return params;
}

- (void)getRdactiveListRequest
{
    NSString*urlString = [NSString stringWithFormat:@"%@score/getrdactivelist",CoinsBaseUrl];
    NSLog(@"激励视频url:%@",urlString);
    NSLog(@"params:%@",[self getRdactiveListRequestParams]);
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post2:urlString Params:[self getRdactiveListRequestParams] Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString*code = [NSString stringWithFormat:@"%@",objc[@"code"]];
            if ([code isEqualToString:@"0"]) {
                NSDictionary*dic = objc[@"result"];
                DDActiveModel*model = [DDActiveModel mj_objectWithKeyValues:dic];
                self.model = model;
                
                [self.collectionView reloadData];
                
            }else{
                [self refreshCoins];
            }
        }else{
//            [SVProgressHUD showErrorWithStatus:@"系统异常"];
        }
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}



#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 - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.model.activelist.count;
    
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
   
    
    @try {
           
       
    
    RewardPackageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.lb_title.text = self.titleArray[indexPath.item];
    cell.image.image = [UIImage imageNamed:self.imageArray[indexPath.item]];
    DDSubActiveModel*model = self.model.activelist[indexPath.item];
    NSDictionary *attributedDict = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:16.0 * WIDTHRADIU],
                                     NSForegroundColorAttributeName:[UIColor colorWithHex:0x4d4d4d],
                                     };
        
        
    NSString *titleStr = [NSString stringWithFormat:@"%@(%@/%@)",model.activeName,model.currentcount,model.totalcount];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleStr attributes:attributedDict];
    
        if (model.currentcount.integerValue > 0) {
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(model.activeName.length + 1, model.currentcount.length)];
    }
    
    
    cell.lb_title.attributedText = attributedString;
        
     return cell;
        
    } @catch (NSException *exception) {
        //捕获到异常要执行的代码
        NSLog(@"exc == %@, 最后我弹了一个弹框说这样不合适",exception);
    } @finally {
        //不管能不能捕获到异常都会执行的方法
        NSLog(@"最后");
    }
   
   
        
    
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    CGFloat width = CGRectGetWidth(collectionView.bounds) / 2;
    
    return CGSizeMake(width, 151 * WIDTHRADIU);
}
/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10.0 * WIDTHRADIU ;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
        return CGSizeZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",indexPath);
    
    selectActiveModel = self.model.activelist[indexPath.item];
    
    if (! selectActiveModel.isclick) {
        NSString *imageName = nil;
        if (indexPath.item == 0) {
            imageName = @"shishouqi";
        }else if (indexPath.item == 1){
            imageName = @"zoudayun";
        }else if (indexPath.item == 2){
            imageName = @"buxinxie";
        }else if (indexPath.item == 3){
            imageName = @"wolihai";
        }
         [RewardTimeAlertView showMoney2WithVC:self imageName:imageName];
        return;
    }
    
    if ([self.model.status isEqualToString:@"1"]) {
        
        if (indexPath.item == 0 || indexPath.item == 2) {
            BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
            model.userId = @"tag123";
            self.rewardedAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:@"945539143" rewardedVideoModel:model];
      
            self.rewardedAd.delegate = self;
           [self.rewardedAd loadAdData];
        }else if (indexPath.item == 1 || indexPath.item == 3){
            self.rewardVideoAd = [[GDTRewardVideoAd alloc] initWithPlacementId:@"5081234635108553"];
            self.rewardVideoAd.delegate = self;
            //self.rewardVideoAd.videoMuted = NO; // 设置激励视频是否静音
            [self.rewardVideoAd loadAd];
        }
        
    }else if ([self.model.status isEqualToString:@"2"]){
        NSString *imageName = nil;
        if (indexPath.item == 0) {
            imageName = @"shishouqi";
        }else if (indexPath.item == 1){
            imageName = @"zoudayun";
        }else if (indexPath.item == 2){
            imageName = @"buxinxie";
        }else if (indexPath.item == 3){
            imageName = @"wolihai";
        }
        
        [self judgeTimeStampisValid:self.model.nextPlayTime imageName:imageName index:indexPath.item];
        
    }
    
   
}

- (void)judgeTimeStampisValid:(NSString *)timeStamp imageName:(NSString *)imageName index:(NSInteger)index
{
    NSDate *datenow = [NSDate date];
    NSTimeInterval currentInterval = [datenow timeIntervalSince1970] * 1000;
    
    NSTimeInterval nextInterval =[timeStamp doubleValue];
    
    
    
    if (currentInterval >= nextInterval) {
        NSTimeInterval tt =  currentInterval - nextInterval;
        if (tt > 60 * 45 * 1000) {
            [Tools showMessage:@"系统繁忙,请稍后重试!!!"];
            
        }else{
            if (index == 0 || index == 2) {
                  BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
                  model.userId = @"";
                  self.rewardedAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:@"945165627" rewardedVideoModel:model];
            
                  self.rewardedAd.delegate = self;
                 [self.rewardedAd loadAdData];
              }else if (index == 1 || index == 3){
                  //self.rewardVideoAd = [[GDTRewardVideoAd alloc] initWithAppId:@"1110119875" placementId:@"4051816119319036"];
                  self.rewardVideoAd.delegate = self;
                  //self.rewardVideoAd.videoMuted = NO; // 设置激励视频是否静音
                  [self.rewardVideoAd loadAd];
              }
        }
    }else{
        NSTimeInterval tt =  nextInterval - currentInterval;
        
        if (tt > 60 * 30 * 1000) {
            [Tools showMessage:@"手机系统时间异常"];
        }else{
            [RewardTimeAlertView showMoneyWithVC:self imageName:imageName count:(NSInteger)round(tt)/1000];
        }
        
    }
   
}



#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    NSLog(@"scrollViewDidScroll");
    CGPoint point=scrollView.contentOffset;
    NSLog(@"%f,%f",point.x,point.y);
    // 从中可以读取contentOffset属性以确定其滚动到的位置。
    // 注意：当ContentSize属性小于Frame时，将不会出发滚动
    if (point.y <= -cl_kNavigationBarHeight) {
        scrollView.contentOffset = CGPointMake(point.x, -cl_kNavigationBarHeight);
    }
}
    
#pragma mark - BUNativeExpressRewardedVideoAdDelegate

- (void)nativeExpressRewardedVideoAdDidLoad:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    [self showRewardVideoAd];
}


- (void)nativeExpressRewardedVideoAd:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error
{
    
}

- (void)nativeExpressRewardedVideoAdDidDownLoadVideo:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}

- (void)nativeExpressRewardedVideoAdViewRenderSuccess:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
   
}


- (void)nativeExpressRewardedVideoAdViewRenderFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd error:(NSError *_Nullable)error
{
    
}

- (void)nativeExpressRewardedVideoAdWillVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}


- (void)nativeExpressRewardedVideoAdDidVisible:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}

/**
 This method is called when video ad is about to close.
 */
- (void)nativeExpressRewardedVideoAdWillClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}

/**
 This method is called when video ad is closed.
 */
- (void)nativeExpressRewardedVideoAdDidClose:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{

    self.rewardedAd = nil;

    self.rewardedAd.delegate = nil;
    
}

/**
 This method is called when video ad is clicked.
 */
- (void)nativeExpressRewardedVideoAdDidClick:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}

/**
 This method is called when the user clicked skip button.
 */
- (void)nativeExpressRewardedVideoAdDidClickSkip:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}

/**
 This method is called when video ad play completed or an error occurred.
 @param error : the reason of error
 */
- (void)nativeExpressRewardedVideoAdDidPlayFinish:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error
{
    
}

/**
 Server verification which is requested asynchronously is succeeded.
 @param verify :return YES when return value is 2000.
 */
- (void)nativeExpressRewardedVideoAdServerRewardDidSucceed:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd verify:(BOOL)verify
{
    if (verify) {
         [self getCoinsByWhatVideos:selectActiveModel.activeId];
    }
}

/**
 Server verification which is requested asynchronously is failed.
 Return value is not 2000.
 */
- (void)nativeExpressRewardedVideoAdServerRewardDidFail:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd
{
    
}
-(BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}
    
    
#pragma mark - GDTRewardedVideoAdDelegate
- (void)gdt_rewardVideoAdDidLoad:(GDTRewardVideoAd *)rewardedVideoAd
{
    [self.rewardVideoAd showAdFromRootViewController:self];
}

/**
 视频播放页关闭回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidClose:(GDTRewardVideoAd *)rewardedVideoAd
{
    
//    NSString *inputValue1 = @"late()";
//    [self.webView evaluateJavaScript:inputValue1 completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//           NSLog(@"value图片: %@ error: %@", response, error);
//     }];
//
    
    
   
}

/**
 视频广告信息点击回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidClicked:(GDTRewardVideoAd *)rewardedVideoAd
{
    
}

/**
 视频广告各种错误信息回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 @param error 具体错误信息
 */
- (void)gdt_rewardVideoAd:(GDTRewardVideoAd *)rewardedVideoAd didFailWithError:(NSError *)error
{
    
}

/**
 视频广告播放达到激励条件回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidRewardEffective:(GDTRewardVideoAd *)rewardedVideoAd
{
    [self getCoinsByWhatVideos:selectActiveModel.activeId];
}

/**
 视频广告视频播放完成

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidPlayFinish:(GDTRewardVideoAd *)rewardedVideoAd
{
    
}


#pragma mark - 穿山甲显示广告
// important: show的时候会进行WKWebview的渲染，建议一次最多展示三个广告，如果超过3个会很大概率导致WKWebview渲染失败。当然一般情况下激励视频一次只会show一个
- (void)showRewardVideoAd {
    if (self.rewardedAd) {
        [self.rewardedAd showAdFromRootViewController:self];
    }
}


#pragma mark - event response
- (void)tapClick:(UIGestureRecognizer *)ges
{
    [self refreshCoins];
}

#pragma mark - getters and setters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 79 * WIDTHRADIU)];
        _scrollView.backgroundColor = [UIColor whiteColor];
        //_scrollView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        
        UIImage*image = [UIImage imageNamed:@"rewardbanner"];
        UIImage*image2 = [UIImage imageNamed:@"gonglue"];
        
        //顶部背景图
        UIImageView*topImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, image.size.height * WIDTHRADIU)];
        topImg.image = image;
        [_scrollView addSubview:topImg];
        
        //攻略图
        UIImageView*glImg = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 210 * WIDTHRADIU)/2, topImg.maxY , 210 * WIDTHRADIU, 18 * WIDTHRADIU)];
        glImg.image = image2;
        [_scrollView addSubview:glImg];
        
        //collectionview
        [_scrollView addSubview:self.collectionView];
        
        _scrollView.contentSize = CGSizeMake(ScreenWidth, self.collectionView.maxY);
        
       
    
        
    }
    return _scrollView;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 169 * WIDTHRADIU, ScreenWidth, 312 * WIDTHRADIU) collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        
        // _collectionView.backgroundColor = K_GrayColor;
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        //布局
        fl.minimumLineSpacing = 0;
        fl.minimumInteritemSpacing = 0;
        
        //cell注册
        [_collectionView registerNib:[UINib nibWithNibName:@"RewardPackageCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        
       
        
        
    }
    return _collectionView;
}

- (NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"试手气 (0/3)",@"走大运 (0/3)",@"不信邪 (0/3)",@"我厉害 (0/3)"];
    }
    return _titleArray;
}

- (NSArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = @[@"shishouqi",@"zoudayun",@"buxinxie",@"wolihai"];
    }
    return _imageArray;
}

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