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

#import "FindViewController.h"
#import "FindTableTopCell.h"
#import "FindRecommendBookCell.h"
#import "FindEntertainmentCell.h"
#import "FindBottomCell.h"
#import "HomeVideoContentCell.h"

#import "GuessLikeController.h"
#import "XMLYSleepViewController.h"
#import "KKLisenViewController.h"
#import "QFMultiResponseScrollView.h"

#import "CoinsCenterViewController.h"
#import "LoginVC.h"

#import "MyPrizeListVC.h"
#import "ShareViewController.h"

#import "AiDaAlertView.h"

#import <CoreMotion/CoreMotion.h>

#import "XBYStatusLabel.h"
#import "KKListenSubCell.h"
#import "KKListenDetailController.h"
#import "XMSDK.h"
#import "ProgressView.h"
#import "ICMusicPlayManager.h"
#import "KKPlayerViewController.h"

#import "WETianqiController.h"
#import "FindPackageAlertView.h"
#import "CTAPIBaseManager.h"
#import "OnFootAlertView.h"
#import "KKFindTableView.h"
#import "StatisticsViewController.h"
#import "CoinsCenterViewController.h"
#import "CoinsDetailListVC.h"

#import "YDAuthenticationHelper.h"
#import "PrizeInfoCommitSuccessAlertView.h"

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

#import "UIViewController+KSCUFeedPageExtend.h"


//抢红包点击事件model
#import "KKRedPackageClickEventModel.h"
#import <objc/runtime.h>
#import "WXApi.h"


//存钱罐
#import "StatisticsViewController.h"
#import "SaveTabBarController.h"
#import "SaveProductListController.h"
#import "MyAssetsController.h"
#import "LittleGoldHouseWebVC.h"
#import "ProductDetailController.h"
#import "KKActivityRedPackageBaseView.h"
#import "KKCLFundViewController.h"

//小满
#import <BXMediaSDK/BXMediaMaterialManager.h>
#import "KKActivityViewController.h"
#import "MyFruitViewController.h"

#import "YDTempUrlInstance.h"

#import "HeadLineViewController.h"

//AI照相馆
#import "KKDealIdPhotoVC.h"
#import "CTToast.h"

#import "testVC.h"
#import "CommunityVC.h"
@interface FindViewController ()<FindRecommendBookCellDelegate,FindTableTopCellDelegate,DHCWNativeRenderAdDelegate,DHCWNativeLocaVideoAdDelegate,DHCWNativeAdViewDelegate,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,KSCUFeedPageScrollViewDelegate>
{
    BOOL superCanScroll;
    BOOL childCanScroll;
    NSInteger currentPage;
    XMSDKPlayer *_sdkPlayer;
    NSInteger _stepCount;
    
    BOOL goToNextVC;
}

@property (nonatomic, strong)QFMultiResponseScrollView* scrollView;

@property (nonatomic, strong)AiDaAlertView* aiDaView;

@property(nonatomic,strong)CMPedometer *pedometer;

@property (nonatomic, strong)FindTableTopCell* topCell;

@property (nonatomic, strong)FindRecommendBookCell *bookCell;

@property (nonatomic, strong)UIScrollView* smallScrollView;

@property (nonatomic, strong)UIView *topWhiteView;

/**
 当前滑块的index
 */
@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, strong)UIView* blueLineView;

@property (nonatomic, strong)NSMutableArray* labelArray;

//每一个label宽度
@property (nonatomic, strong)NSMutableArray* labelWidthArray;

//每个label的起始位置
@property (nonatomic, strong)NSMutableArray* labelMinXArray;

@property (nonatomic, strong)KKFindTableView*tableView;

@property (nonatomic, strong)NSMutableArray*titleArray;

@property (nonatomic, strong)NSMutableArray* dataArray;


@property (nonatomic, strong)UIImageView* iconImg;

@property (nonatomic, strong)ProgressView* progressView;

@property (nonatomic, strong)UIView* shadowView;


@property (nonatomic, strong)UIButton* TopBtn;


@property (nonatomic, assign)BOOL hiddenBtn;


//变现猫
@property (nonatomic, strong) DHCWNativeRenderAd *nativeAd;
@property (nonatomic, strong) NSMutableArray *adDataArray;


@property (nonatomic, strong)HomeVideoContentCell *videoCell;

@property (nonatomic, strong)UIView *videoHeaderView;

//抢红包点击事件数组
@property (nonatomic, strong)NSMutableArray *redPackageClickEventsArray;
@property (nonatomic, strong)NSMutableArray *topDataArr1;
@property (nonatomic, strong)NSMutableArray *topDataArr2;
@property (nonatomic, strong) UIView *middleBanner;
@end

@implementation FindViewController

- (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:YES animated:animated];
    goToNextVC = NO;
    [self getStepCount];
    UIWindow *curWindow = [[UIApplication sharedApplication].delegate window];
    
    
    if (self.aiDaView) {
            [curWindow  bringSubviewToFront:self.aiDaView.maskView];
             [curWindow bringSubviewToFront:self.aiDaView];
        }
    
    XMTrack*track = [_sdkPlayer currentTrack];

     if (track && self.iconImg == nil) {
         UIView*shadowView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 70, ScreenHeight - 150, 50, 50)];
         self.shadowView = shadowView;
         _iconImg = [[UIImageView alloc]init];
         _iconImg.frame = CGRectMake(2, 2, 46, 46);
         _iconImg.layer.cornerRadius = 23;
         _iconImg.layer.masksToBounds = YES;
         _iconImg.userInteractionEnabled = YES;
         _iconImg.layer.borderWidth = 2;
         _iconImg.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.5].CGColor;
         ProgressView*progressView = [[ProgressView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
         self.progressView = progressView;
         progressView.width = 5;
         
         [self.view addSubview:shadowView];
         [shadowView addSubview:progressView];
         [shadowView addSubview:_iconImg];
         shadowView.layer.shadowColor = [UIColor blackColor].CGColor;

         shadowView.layer.shadowOffset = CGSizeMake(0, 0);

         shadowView.layer.shadowOpacity = 1;

         shadowView.layer.shadowRadius = 5.0;

         shadowView.layer.cornerRadius = 25.0;

         shadowView.clipsToBounds = NO;
         
         UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
         [_iconImg addGestureRecognizer:tap];
         
     }
     
     if (self.iconImg && track) {
         [_iconImg sd_setImageWithURL:[NSURL URLWithString:track.coverUrlLarge] placeholderImage:[UIImage imageNamed:@"trackPlaceImg"]];
     }
     
     if (_sdkPlayer.isPlaying && self.iconImg) {
         [self startRotatingWithView:self.iconImg];
     }
     
     ICMusicPlayManager*manager = [ICMusicPlayManager sharedManager];
     manager.KKPlayerPlayTimeChanged = ^(CGFloat percent, NSUInteger currentSecond) {
         NSLog(@"kk:percent:%.2lf,current:%ld",percent,currentSecond);
         self.progressView.percent = percent;
     };
     
     if (_sdkPlayer.playerState == XMSDKPlayerStateStop) {
            self.shadowView.hidden = YES;
        }else{
            if (self.shadowView) {
                self.shadowView.hidden = NO;
            }
              self.progressView.percent = track.listenedTime/(CGFloat)track.duration;
        }
    
    [self showGuideView];
    
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"showSuspension"]) {
//       //悬浮按钮
//       [[clickEvent instance] SuspensionBtnRooterVC:self];
//    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//      if (!(self.presentedViewController || self.presentingViewController )) {
//              [self.navigationController setNavigationBarHidden:NO animated:animated];
//          }
    UIWindow *curWindow = [[UIApplication sharedApplication].delegate window];
    if (self.aiDaView) {
         [curWindow  sendSubviewToBack:self.aiDaView];
        [curWindow  sendSubviewToBack:self.aiDaView.maskView];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //[self navConfig];
    superCanScroll = YES;
    childCanScroll = NO;
    self.hiddenBtn = YES;
    self.currentIndex = 0;
    currentPage = 1;
    self.titleArray = [NSMutableArray array];
    self.labelArray = [NSMutableArray array];
    self.labelWidthArray = [NSMutableArray array];
    self.labelMinXArray = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
    [self.view addSubview:self.scrollView];
    
    [self.view addSubview:self.topWhiteView];
    
    [self getStepCount];
    
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_CategoriesList params:nil withCompletionHander:^(id result, XMErrorModel *error) {
       NSLog(@"result:%@  error:%@",result,error);
      NSArray*array = [self showReceivedData:result className:@"XMCategory" valuePath:nil titleNeedShow:nil];
       if ([result isKindOfClass:[NSArray class]]) {
          for (XMCategory *model in array) {
              if ([model.categoryName isEqualToString:@"有声书"]) {
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"音乐"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"相声评书"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"儿童"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"国学书院"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"戏曲"]){
                  [self.titleArray addObject:model];
              }
              if (self.titleArray.count >= 6) {
                  break;
              }
          }
           
           [self setupSmallScrollView];
       }
       
    }];
    
    _sdkPlayer = [XMSDKPlayer sharedPlayer];
   [_sdkPlayer setPlayMode:XMSDKPlayModeTrack];
   [_sdkPlayer setTrackPlayMode:XMTrackPlayerModeList];
   [_sdkPlayer setAutoNexTrack:YES];
   [[XMSDKPlayer sharedPlayer] setVolume:0.5];
    
    
    [self.view addSubview:self.TopBtn];
    
    [self.TopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.offset(- cl_kTabBarHeight - 40);
        make.width.offset(100);
        make.height.offset(40);
    }];
    
    [self hiddenrequest];
    
    
    [self requestRedPackageIconsAndTargetEvent];
    
}
- (void)updata{
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_CategoriesList params:nil withCompletionHander:^(id result, XMErrorModel *error) {
       NSLog(@"result:%@  error:%@",result,error);
      NSArray*array = [self showReceivedData:result className:@"XMCategory" valuePath:nil titleNeedShow:nil];
       if ([result isKindOfClass:[NSArray class]]) {
          for (XMCategory *model in array) {
              if ([model.categoryName isEqualToString:@"有声书"]) {
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"音乐"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"相声评书"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"儿童"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"国学书院"]){
                  [self.titleArray addObject:model];
              }else if ([model.categoryName isEqualToString:@"戏曲"]){
                  [self.titleArray addObject:model];
              }
              if (self.titleArray.count >= 6) {
                  break;
              }
          }
           
           [self setupSmallScrollView];
       }
       
    }];
}
#pragma mark -Private Method
- (void)setupSmallScrollView
{
   // CGFloat labelW = [ScreenWidth/(self.titleArray.count>4?4:self.titleArray.count)];
    
    self.smallScrollView.contentSize = CGSizeMake([self getAllLabelWidth], 44);
    
    CGFloat labelX,labelY,labelW = 0, labelH = 44;
    for (int i = 0; i < self.titleArray.count; i++) {
        XMCategory*model = self.titleArray[i];
        labelX = [self getLabelMinXWithIndex:i];
        NSNumber* width = self.labelWidthArray[i];
        labelW = width.floatValue;
        [self.labelMinXArray addObject:@(labelX)];
        XBYStatusLabel *label = [[XBYStatusLabel alloc]initWithFrame:CGRectMake(labelX, labelY, labelW, labelH)];
        label.textAlignment = NSTextAlignmentCenter;
        label.showColor = [UIColor colorWithHex:0x333333];
        label.text = model.categoryName;
        label.tag = i;
        label.userInteractionEnabled = YES;
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapAction:)]];
        [self.smallScrollView addSubview:label];
        [self.labelArray addObject:label];
        if (i == 0) {
            UIView*blueLine = [[UIView alloc]init];
            blueLine.backgroundColor = K_MainColor;
            blueLine.tag = 200;
            [self.smallScrollView addSubview:blueLine];
            blueLine.frame = CGRectMake(labelX + (labelW - 30)/2 , labelY + labelH - 4, 30 , 2);
            self.blueLineView = blueLine;
        }
    }
    
    XBYStatusLabel *lable = [self.labelArray firstObject];
    lable.scale = 1.0;
    
    [self loadData];
}

- (NSArray *)showReceivedData:(id)result className:(NSString*)className valuePath:(NSString *)path titleNeedShow:(NSString*)title
{
    NSMutableArray *models = [NSMutableArray array];
    Class dataClass = NSClassFromString(className);
    if([result isKindOfClass:[NSArray class]]){
       for (NSDictionary *dic in result) {
            id model = [[dataClass alloc] initWithDictionary:dic];
            [models addObject:model];
        }
    }
    else if([result isKindOfClass:[NSDictionary class]]){
        if(path.length == 0)
        {
            id model = [[dataClass alloc] initWithDictionary:result];
            [models addObject:model];
        }
        else
        {
            NSArray *paths = [path componentsSeparatedByString:@"."];
            
//            NSLog(@"paths have %lu objects inside", (unsigned long)[paths count]);
//            NSLog(@"paths last object is %@", paths.lastObject);
            
            NSDictionary *dic = result;
            for (int i=0;i<paths.count-1;i++)
            {
                NSString *subPath = paths[i];
                dic = dic[subPath];
            }
            for (NSDictionary *dict in dic[paths.lastObject])
            {
                id model = [[dataClass alloc] initWithDictionary:dict];
                [models addObject:model];
                
            }
        }
    }
    return models;
//    GerneralTableViewController *vc = [[GerneralTableViewController alloc] init];
//    vc.array = models;
//    vc.titleWillShow = title;
//
//    [self.navigationController pushViewController:vc animated:YES];
}


- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor colorWithHex:0x1886d3];
    [self.view addSubview:navView];
}


- (void)showGuideView
{
    BOOL alert = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alertLife"] boolValue];
    if (alert) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"alertLife"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        return;
    }else{
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"alertLife"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
//    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideLife"];
//
//    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//        return;
//    }
//    NSDate *oldDate = [NSDate date];
//    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideLife"];
//    [[NSUserDefaults standardUserDefaults]synchronize];

    NSInteger x = (arc4random() % 2) + 1;
    
    switch (x) {
        case 1:
        {
            //[self showGuideDiscountAlertView];
        }
            break;
        case 2:
        {
            //[self showGuideLookingJobAlertView];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - 外卖红包弹框
- (void)showGuideTakeOutAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"Guidetakeout"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"Guidetakeout"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [NetworkRequest statisticsWithEventName:@"show_life_waimai"];
    [GuideAlertView showInWindowWithImageName:@"find_to" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"dialog_life_waimai"];
        [weakSelf jumpToHTML5:@"http://dpurl.cn/jGGTHGXz" andJAnalytics:@"外卖红包"];
    }];
}
#pragma mark - 限时特惠弹框
- (void)showGuideDiscountAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideDiscount"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideDiscount"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [NetworkRequest statisticsWithEventName:@"show_life_zhekou"];
    [GuideAlertView showInWindowWithImageName:@"find_Discount" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"dialog_life_zhekou"];
        [weakSelf goToFanLiVC];
    }];
}
#pragma mark - 找工作弹框
- (void)showGuideLookingJobAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"LookingJob"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"LookingJob"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [NetworkRequest statisticsWithEventName:@"show_life_jobTiger"];
    [GuideAlertView showInWindowWithImageName:@"find_LookingJob" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"dialog_life_jobTiger"];
        [[clickEvent instance] clickEventRooterVC:weakSelf Content:@"jobTiger" menuName:@"找工作"];
    }];
}
#pragma mark - 听听弹框(停用)
- (void)showGuideTingTingAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideTingTing"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideTingTing"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [GuideAlertView showInWindowWithImageName:@"find_ts" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"find_ts"];
        KKLisenViewController*vc = [KKLisenViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        vc.fromHome = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
}

#pragma mark - 广场舞弹框(停用)
- (void)showGuangChangWuAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideGuangChangWu"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideGuangChangWu"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [GuideAlertView showInWindowWithImageName:@"find_gcw" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"find_gcw"];
        [weakSelf jumpToHTML5:@"https://cpu.baidu.com/1088/a571ca45?scid=83317" andJAnalytics:@"广场舞"];
        
    }];
}


#pragma mark - 搞笑视频(停用)
- (void)showHappyTVAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideHappyTV"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideHappyTV"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [GuideAlertView showInWindowWithImageName:@"find_guIdeTV" Block:^(BOOL success) {
    
        [weakSelf goToHappyTVVC];
    
    }];
}
#pragma mark - 返利网
- (void)goToFanLiVC{
     UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
     __block KKNavViewController *nav1 = (KKNavViewController *)keywindow.rootViewController;
     
     if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstlog"]){
         
         NSInteger loginState = [UserDefault integerForKey:@"appleLoginState"];
         
         if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"] && loginState == 1031) {
             NSString* uid = [UserDefault objectForKey:@"appleId"];
             NSString* userId = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
             NSString* cus_name = [getPeopleID Peopletitle];
             NSString* photoUrl = [getPeopleID PeoplePhoto].absoluteString;

             BPViewController *bpVC = [[BPViewController alloc]init];
             bpVC.UID = uid;
             bpVC.Id = userId;
             bpVC.wxName = [NSString blankString:cus_name] ? @"" :cus_name;
             bpVC.wxPhotoUrl = photoUrl;
             bpVC.title = @"绑定手机号";
             bpVC.from = @"other";
             WeakSelf
             bpVC.block = ^(BOOL show) {
                 [weakSelf getToFanLiVCUrl];
             };
             UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:bpVC];
             [nav1 presentViewController:nav animated:YES completion:nil];
             return;
         }
         
         LoginVC *loginVC = [[LoginVC alloc]init];
         WeakSelf
         loginVC.block = ^(BOOL show) {
             [weakSelf getToFanLiVCUrl];
         };
         
         UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
         [nav1 presentViewController:nav animated:YES completion:nil];

         return;
     }else{
         [self getToFanLiVCUrl];
     }
}
#pragma mark - 返利网
- (void)getToFanLiVCUrl
{
    NSString *url = [NSString stringWithFormat:@"https://web.kanface.com:444/get/fanli/url?uid=%@",@([getPeopleID PeopleID])];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    NSDictionary *params = @{
        @"uid":@([getPeopleID PeopleID]),
        @"tel":[getPeopleID PeopleIphoneNmber]
    };
    [KKLoadingAnimationView show];
    [NetworkRequest Get:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            NSString *url = [NSString stringWithFormat:@"%@",objc[@"result"]];
            
            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
           
            [self jumpToHTML5:url andJAnalytics:@"限时特惠"];

        }else{
            [self alertShow:describe];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShow:@"网络异常"];
    }];
}

- (void)goToHappyTVVC
{
    UITabBarController *vc = self.navigationController.tabBarController;
    
    UINavigationController *nav = vc.viewControllers[1];
    
    HeadLineViewController *headVC = nav.viewControllers[0];
    
    headVC.currentIndex2 = 1;
    
    
    self.tabBarController.selectedIndex = 1;
    
}


#pragma mark - loadData
- (void)loadData
{
    if (self.titleArray.count == 0) {
        [self updata];
        [self loadData];
        return;
    }
    XMCategory*model = self.titleArray[_currentIndex];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@(model.categoryId) forKey:@"category_id"];
    [params setObject:@1 forKey:@"calc_dimension"];
    [params setObject:@20 forKey:@"count"];
    [params setObject:@(currentPage) forKey:@"page"];
    __weak typeof(self) sself = self;
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_AlbumsList params:params withCompletionHander:^(id result, XMErrorModel *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (!error){
            
            NSArray*array  =  [sself showReceivedData:result className:@"XMAlbum" valuePath:@"albums" titleNeedShow:@"albumTitle"];
            if (array.count > 0) {
                for (XMAlbum* album in array) {
                               [self.dataArray addObject:album];
                           }
                           
                           if (array.count %20 != 0) {
                               [self.tableView.mj_footer resetNoMoreData];
                           }
                           
                           
                       
                          
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }
            
            self->currentPage++;
             [self.tableView reloadData];
           
        }else {
           NSLog(@"Error: error_no:%ld, error_code:%@, error_desc:%@",(long)error.error_no, error.error_code, error.error_desc);
        }
    }];
}

- (NSDictionary *)getincreateScoreRequestPara
{
    NSDictionary *dic = @{      @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                                @"scoreType":@"1013",
                                @"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"];
    return params;
}


- (void)getincreateScoreRequest
{
    NSString *url = [NSString stringWithFormat:@"%@/score/increateScore",CoinsBaseUrl];
    NSLog(@"走路赚金币url:%@",url);
    NSLog(@"params:%@",[self getincreateScoreRequestPara]);
       WeakSelf
    [KKLoadingAnimationView show];
       [CTAPIBaseManager POST:url params:[self getincreateScoreRequestPara] completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
           
           [KKLoadingAnimationView dismiss];
           if (error) {
               NSLog(@"error:%@",error);
           }
           
           if (responseObject) {
               NSLog(@"responseObject:%@",responseObject);
           }
           
           if (responseObject) {
               NSNumber *code = responseObject[@"code"];
               NSString *des = responseObject[@"des"];
               if (code.integerValue == 1006) {
                   
                   [getPeopleID setOnFootCoinsDate:[NSDate date]];
                   [weakSelf getStepCount];
                   
                   NSString*score = [NSString stringWithFormat:@"+%@",responseObject[@"result"][@"score"]];
                   WeakSelf
                   [PrizeInfoCommitSuccessAlertView showReceiveViewInWindowWithVC:self Number:score block:^(CTShareType type) {
                       [weakSelf refreshCoins];
                   }];
                   
                   
                  
//                   [OnFootAlertView alertWithButtonClickedBlock:^{
//
//                       [self refreshCoins];
//                      }];
                    
                  
                   
               }else{
                   [self alertShow:des];
               }
           }
           
           
       }];
}

- (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];
        [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
           [KKLoadingAnimationView dismiss];
            
            if (error) {
                [SVProgressHUD showInfoWithStatus:@"无网络"];
                return ;
            }
            if (responseObj) {
                NSString *code = [responseObj[@"code"] stringValue];
                if ([code isEqualToString:@"0"]) {
                    [getPeopleID getTotalCoins:responseObj[@"result"]];
                   
                    WebVC *webVC = [[WebVC alloc]init];
                     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 = CoinsRewardedUrl;
                      //webVC.url = @"http://172.16.10.144/projects/html-nginx/html-nginx/lesson/award/src/award.html";
                    webVC.hidesBottomBarWhenPushed = YES;
                     [self.navigationController pushViewController:webVC animated:YES];
                    
                    return ;
                }
            }
            
        
        }];
    }
}

- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}

//判断当前是否可以领取
- (BOOL)canRequestOnFootApi
{
       NSDate *oldTime = [getPeopleID getOnFootCoinsDate];

       if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
           return NO;
       }
    
    return YES;
    
}

#pragma mark - life cycle
//获取计步数
- (void)getStepCount
{
    
//    WeakSelf
    
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    // 开始日期
    NSDate *startDate = [calendar dateFromComponents:components];
    // 结束日期
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
   
    //判断记步功能
    if ([CMPedometer isStepCountingAvailable]) {
        [self.pedometer queryPedometerDataFromDate:startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error) {
                NSLog(@">>>error====%@",error);
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakSelf.btn_GetCoins setTitle:@"开启权限,领今日金币" forState:UIControlStateNormal];
//                    [weakSelf.btn_GetCoins setBackgroundImage:[self gradientImageWithBounds:CGRectMake(0, 0, ScreenWidth - 50 * WIDTHRADIU, 45 * WIDTHRADIU) andColors:@[(id)[UIColor colorWithHex:0xee551a] ,(id)[UIColor colorWithHex:0xf36d39]] andGradientType:1] forState:UIControlStateNormal];
//                    weakSelf.btn_GetCoins.userInteractionEnabled = YES;
                    [Tools showMessage:@"请开启运动权限"];
                });
                
            }else {
                
                //self->open = YES;
                
                NSLog(@"步数====%@",pedometerData.numberOfSteps);
                NSLog(@"距离====%@",pedometerData.distance);
                NSInteger stepCount = pedometerData.numberOfSteps.integerValue;
                
                


                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    
                    
                    //self.currentStepCount = stepCount;
                    NSString* str = [NSString stringWithFormat:@"%ld步",stepCount];
                    NSMutableAttributedString*attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                    [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:40],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, str.length - 1)];
                    [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(str.length - 1, 1)];
                   
                    self.topCell.lb_count.attributedText = attributedStr;
                    self.topCell.progressView.processValue = stepCount/10000.0 >= 1 ? 1.0 :stepCount/10000.0;
                    self->_stepCount = stepCount;
                    
                    if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
                         [self getstepRequest:self->_stepCount distance:pedometerData.distance];
                    }
                    
                   
                });
            }
        }];
    }else{
        NSLog(@"记步功能不可用");
    }
    
    
    
}


- (NSDictionary *)getstepRequestPara:(NSInteger)step
{
    NSDictionary *dic = @{      @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                                @"stepNum":@(step),
                                @"reqStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                                };
    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"];
    return params;
}


- (void)getstepRequest:(NSInteger)step distance:(NSNumber *)distance
{
    NSString *url = [NSString stringWithFormat:@"%@walkservice/getstep",CoinsBaseUrl];
    NSLog(@"获取指定用户的走路步数url:%@",url);
    NSLog(@"params:%@",[self getstepRequestPara:step]);
//    WeakSelf
    
    [CTAPIBaseManager POST:url params:[self getstepRequestPara:step] completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"error:%@",error);
            [SVProgressHUD showErrorWithStatus:@"无网络"];
        }
        
        if (responseObject) {
            NSLog(@"responseObject:%@",responseObject);
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
                NSString *des = [NSString stringWithFormat:@"%@",responseObject[@"des"]];
                if ([code isEqualToString:@"0"] || [code isEqualToString:@"2006"]) {
                    NSDictionary*result = responseObject[@"result"];
                    NSNumber*num1 = result[@"stepNum"];
                    NSNumber*num2 = result[@"shareNum"];
                    NSInteger stepNum = num1.integerValue + num2.integerValue;
                    
                    if (self->goToNextVC) {
                         StatisticsViewController*vc = [StatisticsViewController new];

                         vc.hidesBottomBarWhenPushed = YES;
                           
                         vc.title = @"健康统计";
                         vc.stepCount = [NSNumber numberWithInteger:step];
                         vc.distance = distance;

                         [self.navigationController pushViewController:vc animated:YES];
                         return;
                           
                        
                        return;
                    }
            
                    self->_stepCount = stepNum;
                    NSString* str = [NSString stringWithFormat:@"%ld步",(long)self->_stepCount];
                    NSMutableAttributedString*attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                    [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:40],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, str.length - 1)];
                    [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(str.length - 1, 1)];
                   self.topCell.lb_count.attributedText = attributedStr;
                    self.topCell.progressView.processValue = self->_stepCount/10000.0 >= 1 ? 1.0 :self->_stepCount/10000.0;
                    
                    
                }else if ([code isEqualToString:@"2002"]){
                    [SVProgressHUD showErrorWithStatus:@"当前时间与网络时间不一致!!!"];
                }else if ([code isEqualToString:@"1001"] || [code isEqualToString:@"9999"]){
                    [SVProgressHUD showErrorWithStatus:@"服务器繁忙,请稍等!!!"];
                }else if ([code isEqualToString:@"1009"]){
                    [SVProgressHUD showErrorWithStatus:@"服务器繁忙,请稍等!!"];
                } else{
                    [SVProgressHUD showErrorWithStatus:des];
                }
            }else{
               [SVProgressHUD showErrorWithStatus:@"服务器异常"];
            }
        }
        
        
    }];
}

#pragma mark - 后台获取抢红包的icon和点击事件关键字
- (void)requestRedPackageIconsAndTargetEvent
{
    
    NSString*version = nil;
    NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray*vArr = [v componentsSeparatedByString:@"."];
    
    for (int i = 0; i < vArr.count; i++) {
        if (version == nil) {
            version = [NSString stringWithFormat:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    NSString *url1 = [NSString stringWithFormat:@"%@dynamic/menu/get",[NetworkConfig ipYinShuConfig]];
    
    NSDictionary *params1 = @{
        @"configName":@"ShengHuoShouYeTop",
        @"appName":@"kksh",
        @"version":version,
        @"systemType":@"iOS"
    };
    typeof(self) wSelf = self;
    [NetworkRequest Post15:url1 Params:params1 Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];

            if ([state isEqualToString:@"200"]) {
                if ([objc[@"result"] isKindOfClass:[NSArray class]]) {
                    wSelf.topDataArr1 = [KKRedPackageClickEventModel mj_objectArrayWithKeyValuesArray:objc[@"result"]];
                    //重新更新布局
                    [wSelf UpdateScrollViewLayout];
                    [wSelf.topCell refreshDataWithArray1:wSelf.topDataArr1 andArray2:wSelf.topDataArr2];
                }
            }


        }

    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);


    }];
    
    
    NSString *url2 = [NSString stringWithFormat:@"%@dynamic/menu/get",[NetworkConfig ipYinShuConfig]];
    NSDictionary *params2 = @{
        @"configName":@"ShengHuoShouYe",
        @"appName":@"kksh",
        @"version":version,
        @"systemType":@"iOS"
    };
    [NetworkRequest Post15:url2 Params:params2 Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            
            if ([state isEqualToString:@"200"]) {
                if ([objc[@"result"] isKindOfClass:[NSArray class]]) {
                    wSelf.topDataArr2 = [KKRedPackageClickEventModel mj_objectArrayWithKeyValuesArray:objc[@"result"]];
                    //重新更新布局
                    [wSelf UpdateScrollViewLayout];
                    [wSelf.topCell refreshDataWithArray1:wSelf.topDataArr1 andArray2:wSelf.topDataArr2];
                }
            }
            
           
        }

    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}
//重新布局
- (void)UpdateScrollViewLayout{
    CGFloat top1Height = 0;
    if (self.topDataArr1.count > 0) {
        int index1 = (self.topDataArr1.count % 4 == 0) ? (int)(self.topDataArr1.count / 4) : (int)(self.topDataArr1.count / 4) + 1;
        top1Height = 75 * index1;
    }else{
        top1Height = 75;
    }
    CGFloat top2Height = 0;
    if (self.topDataArr2.count > 0) {
        int index2 = (self.topDataArr2.count % 5 == 0) ? (int)(self.topDataArr2.count / 5) : (int)(self.topDataArr2.count / 5) + 1;
        top2Height = 70  * index2;
    }else{
        top2Height = 70;
    }
    
    
    self.topCell.frame = CGRectMake(0, 0, ScreenWidth, (180 + top1Height + top2Height) * WIDTHRADIU + cl_kStatusBarHeight );
    self.bookCell.frame = CGRectMake(0, CGRectGetMaxY(self.topCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 202 * WIDTHRADIU);
    self.smallScrollView.frame = CGRectMake(0, CGRectGetMaxY(self.bookCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 44);
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.smallScrollView.frame), ScreenWidth, ScreenHeight- cl_kNavigationBarHeight - 10);
    
    self.videoHeaderView.frame = CGRectMake(0, CGRectGetMaxY(self.bookCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 48 * WIDTHRADIU);
    self.videoCell.frame = CGRectMake(0, CGRectGetMaxY(self.videoHeaderView.frame), ScreenWidth, ScreenHeight);
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.tableView.frame) + 10);
}

#pragma mark - 获取联合登录链接
- (void)getFederatedLoginRequestWithModel:(KKRedPackageClickEventModel *)model
{
    NSString *url = [NSString stringWithFormat:@"%@",model.content];
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    
    NSDictionary *params = @{
        @"uid":@([getPeopleID PeopleID]),
        @"tel":[getPeopleID PeopleIphoneNmber]
    };
    
    NSLog(@"联合登录url:%@",url);
    NSLog(@"params:%@",params);
    [KKLoadingAnimationView show];
    [NetworkRequest Get:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            NSString *url = [NSString stringWithFormat:@"%@",objc[@"result"]];
            
//            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
            WebVC *webvc = [[WebVC alloc]init];
            webvc.url = url;
            webvc.title = model.menuName;
            webvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webvc animated:YES];
        }else{
            [self alertShow:describe];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShow:@"网络异常"];
    }];
    
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    UIScrollView* feedScrollView = [self.videoCell.feedPage.feedViewController getKSCUFeedPageScrollView];
    
    if (scrollView == self.scrollView) {
        NSLog(@"scrollView:%.2f",scrollView.contentOffset.y);
        CGFloat offsetY = scrollView.contentOffset.y;
        CGFloat offsetX = scrollView.contentOffset.x;
        CGFloat maxY = CGRectGetMinY(self.videoHeaderView.frame) - cl_kStatusBarHeight- 0.1 ;
        if (offsetY >= maxY) {
            self.topWhiteView.alpha = 1.0;
        }else{
           self.topWhiteView.alpha = 0;
        }
        if (!superCanScroll) {
            if (offsetY >= maxY){
               scrollView.contentOffset = CGPointMake(offsetX, maxY);
            }else{
                if (self.hiddenBtn) {
                    if (self.tableView.contentOffset.y !=0) {
                        scrollView.contentOffset = CGPointMake(offsetX, maxY);
                    }
                }else{
                    if (feedScrollView.contentOffset.y !=0) {
                        scrollView.contentOffset = CGPointMake(offsetX, maxY);
                    }
                }
            }
            
            childCanScroll = YES;
        }else{
            if (offsetY >= maxY) {
                scrollView.contentOffset = CGPointMake(offsetX, maxY);
                superCanScroll = NO;
                childCanScroll = YES;
            }
        }
        
    }

    if (scrollView == feedScrollView || scrollView == self.tableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        CGFloat offsetX = scrollView.contentOffset.x;
        NSLog(@"%.2f",scrollView.contentOffset.y);
        
        if (offsetY >= 300) {
            self.TopBtn.hidden = NO;
        }else{
            self.TopBtn.hidden = YES;
        }
        if (!childCanScroll) {
            scrollView.contentOffset = CGPointMake(offsetX, 0);
        }else{
            if (offsetY <= 0) {
                childCanScroll = NO;
                superCanScroll = YES;
            }
        }
    }
 
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KKListenSubCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    XMAlbum*model = self.dataArray[indexPath.section];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.coverUrlLarge
                                  ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.albumTitle;
    
    cell.lb_subTitle.text = model.albumIntro;
    cell.lb_count.text = [self getStrWithCount:model.playCount];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 106;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMAlbum*model = self.dataArray[indexPath.section];
    
    KKListenDetailController*detailVC = [[KKListenDetailController alloc]init];
       
   detailVC.model = model;
   
   detailVC.hidesBottomBarWhenPushed = YES;
   
   [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - private methods
- (NSString *)getStrWithCount:(NSInteger)count
{
    if (count < 10000) {
        return [NSString stringWithFormat:@"%ld",count];
    }else if (count < 100000000&& count>= 10000 ){
        return [NSString stringWithFormat:@"%ld万",count/10000];
    }else{
         return [NSString stringWithFormat:@"%ld亿",count/100000000];
    }
}

#pragma mark - FindRecommendBookCellDelegate
- (void)clickItemWithType:(FindRecommendBookCellType)type
{
    if (type == FindRecommendBookCellTypeAllListen) {
        GuessLikeController*vc = [GuessLikeController new];
        vc.title = @"大家都在听";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (type == FindRecommendBookCellTypeSleep){
        XMLYSleepViewController*vc = [XMLYSleepViewController new];
        vc.title = @"助眠";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        KKLisenViewController*vc = [KKLisenViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        vc.fromHome = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
}

#pragma mark - FindTableTopCellDelegate
- (void)TopCellClickWithModel:(KKRedPackageClickEventModel *)model{
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        [self unLoginTap];
        return;
    }
    [NetworkRequest statisticsWithEventName:[NSString stringWithFormat:@"%@",model.ID]];
    switch (model.type.integerValue) {
        case 1001:
            //原生跳转
        {
            [[clickEvent instance] clickEventRooterVC:self Content:model.content menuName:model.menuName];
        }
            break;
        case 1002:
            //h5跳转
        {
            WebVC *vc = [[WebVC alloc]init];
            vc.title = model.menuName;
            vc.url = model.content;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1003:
            //小程序
        {
            if (![WXApi isWXAppInstalled]){
                [Tools showMessage:@"请安装微信APP后重试"];
                return;
            }
            
            NSDictionary *resourceInfoDic = [self dictionaryWithJsonString:model.content];
            if (resourceInfoDic&& resourceInfoDic.allKeys.count > 1) {
                NSString *userName = resourceInfoDic[@"userId"];
                NSString *path = resourceInfoDic[@"path"];
                WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                launchMiniProgramReq.userName = userName; //拉起的小程序的username
                launchMiniProgramReq.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                    
                }];
            }
           
        }
            break;
        case 1004:
            //其他
        {
            NSDictionary *dic = [self dictionaryWithJsonString:model.content];
            if (dic) {
                [self push:dic model:model];
            }
            
        }
            break;
        case 1005:
        {
            [self getFederatedLoginRequestWithModel:model];
        }
            break;
        default:
            break;
    }
}
- (void)TopCellClickWithType:(FindTableTopCellType)type
{
   if (type == FindTableTopCellTypeCoins) {
       
        [self goToMyCoinsVC];//我的金币
        
    }else if (type == FindTableTopCellTypeHuaFees){
        //优惠充值
        [self goToHuaFeeJuanVC];
        
    }else if (type == FindTableTopCellTypeDraw){
        
        [self goToCoinsRewardVC];//金币抽奖
        
    }else if (type == FindTableTopCellTypePrize){
        [self goToMyPrizeListVC];//我的奖品
    }else if (type == FindTableTopCellTypeCoinCenter){
        
        [self goToCoinCenterVC];//打卡领钱
        
    }else if (type == FindTableTopCellTypeInvite){
        
        [self gotoInviteFriendsVC];//邀请好友
        
    }else if (type == FindTableTopCellTypePackage){

        [self gotoSuspendedPackageVC];//悬浮红包

    }else if (type == FindTableTopCellTypeBall){
        if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
            
            [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
            return;
        }
        goToNextVC = YES;
        [self getStepCount];
    } else if (type == FindTableTopCellTypeExpress){

        [self jumpToHTML5:@"https://m.kuaidi100.com/index_all.html"andJAnalytics:@"快递查询"];
    }else if (type == FindTableTopCellTypeWeather){

        NSDictionary *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"TQData"];
        //天气
        if (![NSString blankString:data[@"cityname"]]) {
            NSString *lat = [NSString stringWithFormat:@"%@",data[@"lat"]];
            NSString *lng = [NSString stringWithFormat:@"%@",data[@"lng"]];
            WETianqiController *controlltr = [[WETianqiController alloc] init];
            [controlltr fetchWeatherDataLocationLat:[lat doubleValue] LocationLng:[lng doubleValue]];
            [self presentViewController:controlltr animated:YES completion:NULL];
        }else{
            WETianqiController *controlltr = [[WETianqiController alloc] init];
            [controlltr fetchWeatherDataLocationLat:31.22 LocationLng:121.48];
            [self presentViewController:controlltr animated:YES completion:NULL];
        }
        
    }else if (type == FindTableTopCellTypePhotostudio){
        //AI照相馆
        KKDealIdPhotoVC *vc = [[KKDealIdPhotoVC alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (type == FindTableTopCellTypeInterrogation){
        
        if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
            
            [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
            return;
        }
        
        [self goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/"];
        
    }else if (type == FindTableTopCellTypeRegister){
        [self jumpToHTML5:@"https://kksb.wy.guahao.com/booking" andJAnalytics:@"医院挂号"];
    }else if (type == FindTableTopCellTypeCalendar){
//        [self jumpToHTML5:@"https://m.wannianli.tianqi.com" andJAnalytics:@"万年历"];
        [self jumpToHTML5:@"http://nginx.weface.com.cn/appH5/calendar/#/"andJAnalytics:@"万年历"];
    }else if (type == FindTableTopCellTypeTrain){
        [self jumpToHTML5:@"https://m.ctrip.com/webapp/train/?allianceid=452800&sid=949980&sourceid=2055&popup=close&autoawaken=close&hiderecommapp=1" andJAnalytics:@"火车票"];
    }else if (type == FindTableTopCellTypeTravel){
        [self jumpToHTML5:@"https://www.ctrip.com/" andJAnalytics:@"周边游"];
    }else if (type == FindTableTopCellTypeMore) {
        SearchCollectionViewController* vc = [Storyboard instantiateViewControllerWithIdentifier:@"SearchCollectionViewController"];
        vc.title = @"更多功能";
        vc.fromHome = YES;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (type == FindTableTopCellTypeFreeMedical){
        
        [self jumpToHTML5:@"https://m.haodf.com/nopen/activity?partnerkey=9b6a9ed2bbf5910c" andJAnalytics:@"极速义诊"];
        
    }else if (type == FindTableTopCellTypeYaoFang){

        [self jumpToHTML5:@"https://cpu.baidu.com/1088/a571ca45?scid=83317" andJAnalytics:@"广场舞"];
    }
}


#pragma mark - BXMNativeAdDelegate

/// 广告加载成功
-(void)nativeRendAdsSuccessToLoad:(NSArray<DHCWNativeAdDataObject *> *)nativeAdDataArray nativeAd:(DHCWNativeRenderAd *)nativeAd
{
    NSLog(@"______自渲染加载成功");
    self.adDataArray = [NSMutableArray arrayWithArray:nativeAdDataArray];
    
    if (self.adDataArray.count > 0) {
        //DHCWNativeAdDataObject *model = self.adDataArray[0];
//        NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:0];
        //HomeCollectionCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        //[cell setupCellWithModel:model delegate:self loca:self rootViewController:self];
        //[self.tableView reloadRowsAtIndexPaths:@[indexPath1] withRowAnimation:UITableViewRowAnimationNone];
        DHCWNativeAdDataObject *model = self.adDataArray[0];
        [self.topCell setupCellWithModel:model delegate:self loca:self rootViewController:self];
    }
}

/// 广告加载失败
-(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)mineHealth{
    [[clickEvent instance] clickEventRooterVC:self Content:@"mineHealth" menuName:@"健康统计"];
}
#pragma mark - 加载变现猫广告
- (void)loadBXMADViews
{
    self.nativeAd = [[DHCWNativeRenderAd alloc] initWithAdId:@"807696003001" imageSize:DWAdImageSize_Feed690_388];
    self.nativeAd.delegate = self;
    [self.nativeAd loadRendAdWithCount:1];
}   
#pragma mark - 跳转到药房
- (void)goToYaoFangVC
{
    
    NSDictionary * params = @{@"appId":@"201912161758",
                                 @"phone":[getPeopleID PeopleIphoneNmber]};
       __weak typeof(self) weakSelf = self;
       [KKLoadingAnimationView show];
       [YDAuthenticationHelper authentication:@"https://kankan.yaodouwang.com/user/login/open" body:params success:^(id  _Nonnull response) {
           [KKLoadingAnimationView dismiss];
           if ([response isKindOfClass:[NSDictionary class]]) {
               NSDictionary * data = response[@"data"];
               NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:data andUrl:@"https://k.yaodouwang.com/"];
               Web2ViewController * vc = [Web2ViewController new];
               vc.title= @"平价药房";
               vc.skipUrl = skipUrl;
               vc.hidesBottomBarWhenPushed = YES;
               [weakSelf.navigationController pushViewController:vc animated:YES];
               [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
               
           }else{
               NSLog(@"数据格式不正确 ===> %@",response);
           }
       } fail:^(id  _Nonnull error) {
           [KKLoadingAnimationView dismiss];
           NSLog(@"请求失败，请登录 ===> %@",error);
           [weakSelf alertShow:@"网络异常,请稍后重试"];
       }];
    
}

#pragma mark - 药兜网
- (void)goToYaoDouVCWithLoginUrl:(NSString *)url
{
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
       
        [self unLoginTap];
        return;
    }
    if ([YDTempUrlInstance shareInstance].data && ![self compareWithLastDate:[YDTempUrlInstance shareInstance].lastDate]) {
        NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:[YDTempUrlInstance shareInstance].data andUrl:url];
        
        Web2ViewController * vc = [Web2ViewController new];
        vc.title= @"平价药房";
        vc.skipUrl = skipUrl;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
        return;
    }
    
    
    NSDictionary * params = @{@"appId":@"201912161758",
                                 @"phone":[getPeopleID PeopleIphoneNmber]};
       __weak typeof(self) weakSelf = self;
    __block NSString* tempUrl = url;
       [YDAuthenticationHelper authentication:@"https://kankan.yaodouwang.com/user/login/open" body:params success:^(id  _Nonnull response) {
           
           if ([response isKindOfClass:[NSDictionary class]]) {
               NSDictionary * data = response[@"data"];
               NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:data andUrl:tempUrl];
               [YDTempUrlInstance shareInstance].data = data;
               [YDTempUrlInstance shareInstance].lastDate = [NSDate date];
               
               Web2ViewController * vc = [Web2ViewController new];
               vc.title= @"平价药房";
               vc.skipUrl = skipUrl;
               vc.hidesBottomBarWhenPushed = YES;
               [weakSelf.navigationController pushViewController:vc animated:YES];
               [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
               
           }else{
               NSLog(@"数据格式不正确 ===> %@",response);
           }
          
       } fail:^(id  _Nonnull error) {
           
           NSLog(@"请求失败，请登录 ===> %@",error);
           [weakSelf alertShow:@"网络异常,请稍后重试"];
       }];
}


#pragma mark - 跳转到我的金币
- (void)goToMyCoinsVC {
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
        return;
    }
    
    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];
        [SVProgressHUD show];
        [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
            [SVProgressHUD dismiss];
            if (error) {
                [SVProgressHUD showInfoWithStatus:@"无网络"];
                return ;
            }
            if (responseObj) {
                NSString *code = [responseObj[@"code"] stringValue];
                if ([code isEqualToString:@"0"]) {
                    [getPeopleID getTotalCoins:responseObj[@"result"]];
                    CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
                    vc.title = @"金币明细";
                    vc.type = ListVCTypeCoinsDetail;
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                    
                    return ;
                }
            }
            
        
        }];
    }
}

#pragma mark - 金币抽奖
- (void)goToCoinsRewardVC {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
        return;
    }
    
    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];
        [SVProgressHUD show];
      [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
          [SVProgressHUD dismiss];
          if (error) {
              [SVProgressHUD showInfoWithStatus:@"无网络"];
              return ;
          }
          if (responseObj) {
              NSString *code = [responseObj[@"code"] stringValue];
              if ([code isEqualToString:@"0"]) {
                  [getPeopleID getTotalCoins:responseObj[@"result"]];
                     WebVC *webVC = [[WebVC alloc]init];
                       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 = CoinsRewardedUrl;
                       // webVC.url = @"http://172.16.10.136/projects/html-nginx/html-nginx/lesson/award/src/award.html";
                       webVC.hidesBottomBarWhenPushed =YES;
                       [self.navigationController pushViewController:webVC animated:YES];
                  return ;
              }
          }
          
      
      }];
    }
    
}

#pragma mark - 金币中心
- (void)goToCoinCenterVC {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
        return;
    }
    
    CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
    vc.title = @"打卡领钱";
    vc.hidesBottomBarWhenPushed = YES;
    vc.Completeblock = ^(BOOL isSuccess) {
        if (isSuccess) {
            self.tabBarController.selectedIndex = 2;
        }
    };
    [self.navigationController pushViewController:vc animated:YES];
    return;
    
}

#pragma mark - 我的奖品
- (void)goToMyPrizeListVC {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
        return;
    }
    
    MyPrizeListVC *vc = [[MyPrizeListVC alloc]init];
    vc.title = @"我的奖品";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    return;
    
}

#pragma mark - 邀请好友
- (void)gotoInviteFriendsVC {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
        return;
    }
    ShareViewController *shareVC = [[ShareViewController alloc]init];
    shareVC.title = @"邀请好友";
    shareVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:shareVC animated:YES];
    
}

#pragma mark - 悬浮红包
- (void)gotoSuspendedPackageVC {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
        return;
    }
    
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"FindPackageShowLastTime"];
    if (_stepCount >= 5000) {
        
        if ([self canRequestOnFootApi]) {
            [self getincreateScoreRequest];
        }else{
            CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
            vc.title = @"金币中心";
            vc.hidesBottomBarWhenPushed = YES;
            vc.Completeblock = ^(BOOL isSuccess) {
                if (isSuccess) {
                    self.tabBarController.selectedIndex = 2;
                }
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }else{
        
        if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
            
            CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
            vc.title = @"金币中心";
            vc.hidesBottomBarWhenPushed = YES;
            vc.Completeblock = ^(BOOL isSuccess) {
                if (isSuccess) {
                    self.tabBarController.selectedIndex = 2;
                }
            };
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            NSDate *oldDate = [NSDate date];
            [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"FindPackageShowLastTime"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            [FindPackageAlertView showAlertView];
            
        }
        
       
    }
    
}

#pragma mark - 免费果园
- (void)goToFruitVC
{
    MyFruitViewController *fruitVC = [MyFruitViewController new];
    fruitVC.title = @"免费果园";
    fruitVC.placeId = @"6666";
    fruitVC.buId = @"946405751";
    fruitVC.gdtAdId = @"2062615177198724";
    fruitVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:fruitVC animated:YES];
}

- (void)addRedPackage
{
    //素材使用代码
   //素材曝光,一般在素材加载完成的时候调用.如果不知道素材加载好的时机,可以在素材所在页面加载完成的时候调用
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
   
   
   //加载素材
   //__weak typeof(self) weakSelf = self;
   [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"6666" thirdUserId:@"" success:^(BXMMaterialModel *model) {
       //weakSelf.model = model;
       if (model) {
           
           [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"6666" userId:@"" materialModel:model];
           
           [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"6666" userId:@"" materialModel:nil];
           
           
           KKActivityViewController *vc = [KKActivityViewController new];
           vc.title = @"免费果园";
           vc.placeId = @"6666";
           vc.buId = @"946405751";
           vc.gdtAdId = @"2062615177198724";
       //    vc.placeId = @"6666";
       //    vc.buId = @"946405751";
       //    vc.gdtAdId = @"2062615177198724";
           vc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:vc animated:YES];
           
           
       }
   } fail:^(NSString *error) {
       
   }];
}

#pragma mark - 话费劵
- (void)goToHuaFeeJuanVC
{
    [[clickEvent instance] clickEventRooterVC:self getFederatedLoginRequestWithUrl:@"https://web.kanface.com:444/common/forward/FamilyChargeForwardUrl" menuName:@"话费充值"];
    
//    WebVC *webvc = [[WebVC alloc]init];
//    NSString  *phone = [getPeopleID PeopleIphoneNmber];
//    if (phone.length > 0) {
//        webvc.url = [NSString stringWithFormat:@"http://www.qld02.com/t/blackcard/callFee/callFeeForH5.html?channel=shebao&mobile=%@",[getPeopleID PeopleIphoneNmber]];
//    }else{
//        webvc.url = @"http://www.qld02.com/t/blackcard/callFee/callFeeForH5.html?channel=shebao";
//    }
////    webvc.url = @"http://priv.icmad.cn/pages/modules/hf/index/hfczsix";
//    webvc.title = @"话费劵";
//    webvc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:webvc animated:YES];
}
#pragma mark - 发射跳转
- (void)push:(NSDictionary *)params model:(KKRedPackageClickEventModel *)model
{
    // 类名
    NSString *class =[NSString stringWithFormat:@"%@", params[@"class"]];
    const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
    
    // 从一个字串返回一个类
    Class newClass = objc_getClass(className);
    if (!newClass)
    {
        // 创建一个类
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        // 注册你创建的这个类
        objc_registerClassPair(newClass);
    }
    // 创建对象
    UIViewController* instance = [[newClass alloc] init];
    
    // 对该对象赋值属性
    NSDictionary * propertys = params[@"property"];
    [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 检测这个对象是否存在该属性
        if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
            // 利用kvc赋值
            [instance setValue:obj forKey:key];
        }
    }];
    
    instance.title = model.menuName;
    
    instance.hidesBottomBarWhenPushed = YES;
    // 跳转到对应的控制器
    [self.navigationController pushViewController:instance animated:YES];
}


- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance
                                                           class], &outCount);
    
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    
    return NO;
}

#pragma mark - json 转字典
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - h5页面跳转
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{

    Web2ViewController*tc = [Web2ViewController new];
    tc.skipUrl =[NSURL URLWithString:url];
    tc.hidesBottomBarWhenPushed =YES;
    tc.title = janalytics;
    [self.navigationController pushViewController:tc animated:YES]; 
    
}
#pragma mark - 爱达api请求
- (NSDictionary *)aiDaTokenRequestPara
{
    NSDictionary* params = @{
        @"loginId":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue,
        @"telephone":[getPeopleID PeopleIphoneNmber]
    };
    return params;
}

- (void)aiDaTokenRequest:(void (^)(bool success, NSString*token))response
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaConfig],AiDaTokenRequest];
    NSLog(@"爱达token的url:%@",url);
    
    NSLog(@"params:%@",[self aiDaTokenRequestPara]);
    
    [NetworkRequest Get3:url Params:[self aiDaTokenRequestPara] Success:^(id _Nonnull responseObject) {
        
        NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*token = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
                response(YES,token);
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}

#pragma mark - 隐藏比财请求
- (void)hiddenrequest
{
     NSString * url =[NSString stringWithFormat:@"%@%@",[NetworkConfig ipSwitchConfig],SwitchRequest];
    
     NSString*version = nil;
           NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
           NSArray*vArr = [v componentsSeparatedByString:@"."];
           
           for (int i = 0; i < vArr.count; i++) {
               if (version == nil) {
                   version = [NSString stringWithFormat:@"kklife%@",vArr[i]];
               }else{
                   version = [version stringByAppendingFormat:@"%@",vArr[i]];
               }
           }
           
           NSDictionary*params = @{
               @"version":version
           };
              
      [NetworkRequest Get:url Params:params Success:^(id _Nonnull responseObject) {
          
          NSString* state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
          if ([state isEqualToString:@"200"]) {
              NSString* result = responseObject[@"result"];
              if ([result isEqualToString:@"0"]) {
                  self.hiddenBtn = NO;
                  self.topCell.btnHidden = self.hiddenBtn;
                  [self.topCell refreshDataWithArray1:self.topDataArr1 andArray2:self.topDataArr2];
                  
                  //[self loadBXMADViews];
                  
                  //[self addKuaiShouView];
              }else if ([result isEqualToString:@"1"]){
                  self.hiddenBtn = YES;
                  
                  //[self addListenView];
              }
              
              [self showKuaiShouViewWithhiddenBtn:self.hiddenBtn];
          }
          
          
      } Failure:^(NSError* error) {
         
    }];
}
#pragma mark - 隐藏或显示快手或听听
- (void)showKuaiShouViewWithhiddenBtn:(BOOL)hiddenBtn
{
//    self.videoHeaderView.hidden = hiddenBtn;
//    self.videoCell.hidden = hiddenBtn;
    
//    self.smallScrollView.hidden = !hiddenBtn;
//    self.tableView.hidden = !hiddenBtn;
   
//    if (!hiddenBtn) {
//        self.bookCell.frame = CGRectMake(0, CGRectGetMaxY(self.topCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 202 * WIDTHRADIU);
//    }
//    if (hiddenBtn) {
//
//        _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.tableView.frame) + 10);
//
//    }else{
//
//        _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.videoCell.frame) + 10);
//
//    }
    self.bookCell.hidden = hiddenBtn;
    self.middleBanner.hidden = !hiddenBtn;
    _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.videoCell.frame) + 10);
}

#pragma mark - 添加听听
- (void)addListenView
{
    self.smallScrollView.frame = CGRectMake(0, CGRectGetMaxY(self.bookCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 44);
    [_scrollView addSubview:self.smallScrollView];

    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.smallScrollView.frame), ScreenWidth, ScreenHeight- cl_kNavigationBarHeight - 10);
    [_scrollView addSubview:self.tableView];
    
    
    _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.tableView.frame) + 10);
    
    _scrollView.contentOffset = CGPointMake(0, 0);
}

#pragma mark - 添加快手
- (void)addKuaiShouView
{
    UIView *videoHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.bookCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 48 * WIDTHRADIU)];
    videoHeaderView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:videoHeaderView];

    UIImageView *fireIcon = [UIImageView new];
    fireIcon.image = [UIImage imageNamed:@"live_newsicon"];
    [videoHeaderView addSubview:fireIcon];
    [fireIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15 * WIDTHRADIU);
        make.centerY.equalTo(videoHeaderView);
        make.width.offset(13 * WIDTHRADIU);
        make.height.offset(16 * WIDTHRADIU);
    }];

    UILabel *lb_fireTitle = [UILabel new];
    [videoHeaderView addSubview:lb_fireTitle];
    lb_fireTitle.attributedText = [[NSMutableAttributedString alloc] initWithString:@"看你想看" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Semibold" size: 16 * WIDTHRADIU],NSForegroundColorAttributeName: [UIColor colorWithHex:0x333333]}];
    [lb_fireTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(fireIcon.mas_right).offset(5 * WIDTHRADIU);
        make.centerY.equalTo(fireIcon);
    }];

    self.videoHeaderView = videoHeaderView;



    HomeVideoContentCell *videoCell = [[HomeVideoContentCell alloc]init];

    videoCell.frame = CGRectMake(0, CGRectGetMaxY(videoHeaderView.frame), ScreenWidth, ScreenHeight);

    [_scrollView addSubview:videoCell];

    [videoCell setupVideoVCWithSelf:self];

    self.videoCell = videoCell;


    _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.videoCell.frame) + 10);
    
}


#pragma mark - 计算功能栏宽度
- (CGFloat)getAllLabelWidth
{
    CGFloat WidthSum =0.0;
    for (int i = 0; i < self.titleArray.count; i++) {
        XMCategory* category = self.titleArray[i];
        CGFloat labelWidth = [self getLabelWidthWithText:category.categoryName height:44 font:20.0];
        [self.labelWidthArray  addObject:@(labelWidth)];
        WidthSum = WidthSum + labelWidth;
    }
    return WidthSum;
}

//计算每个lable的起始位置
- (CGFloat)getLabelMinXWithIndex:(NSInteger)index
{
    if (index == 0) {
        return 0.0;
    }
    CGFloat minX = 0.0;
    for (int i = 0; i < index; i++) {
        NSNumber* labelWidth = (NSNumber *)self.labelWidthArray[i];
        minX = minX + labelWidth.floatValue;
    }
    return minX;
}

//根据文本计算控件宽度
- (CGFloat)getLabelWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font
{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
    rect.size.width = rect.size.width + 8;
    return rect.size.width;
}
#pragma mark - 动画
- (void)startRotatingWithView:(UIView *)view
{
     CABasicAnimation* rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
     rotateAnimation.fromValue = [NSNumber numberWithFloat:0.0];
     rotateAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    rotateAnimation.duration = 20;
    rotateAnimation.repeatCount = MAXFLOAT;
    [view.layer addAnimation:rotateAnimation forKey:nil];
}

//暂停动画
-(void)animationPauseWithView:(UIView *)view{
    //获取当前layer的动画媒体时间
    CFTimeInterval interval = [view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //设置时间偏移量,保证停留在当前位置
    view.layer.timeOffset = interval;
    //暂定动画
    view.layer.speed = 0;
}
//恢复动画
-(void)animationResumeWithView:(UIView *)view{
    //获取暂停的时间
    CFTimeInterval beginTime = CACurrentMediaTime() - view.layer.timeOffset;
    //设置偏移量
    view.layer.timeOffset = 0;
    //设置开始时间
    view.layer.beginTime = beginTime;
    //开始动画
    view.layer.speed = 1;
}

//判断是否同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}

-(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 - 未登录跳转

- (void)unLoginTap {
    [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
}


#pragma mark - 判断时间是否超过1.5分钟
- (BOOL)compareWithLastDate:(NSDate *)lastDate
{
    NSTimeInterval distanceBetweenDates = [[NSDate date] timeIntervalSinceDate:lastDate];
    distanceBetweenDates = fabs(distanceBetweenDates);
    CGFloat hoursBetweenDates = distanceBetweenDates / 60.0;

    if (hoursBetweenDates >= 1.5) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - event response
- (void)labelTapAction:(UITapGestureRecognizer *)gesture {
    XBYStatusLabel *titlelable = (XBYStatusLabel *)gesture.view;
    if (titlelable.tag == _currentIndex) {
        return;
    }
    
    //    label居中的offsetx
   CGFloat offsetx = titlelable.center.x - self.smallScrollView.frame.size.width * 0.5;
   CGFloat offsetMax = self.smallScrollView.contentSize.width - self.smallScrollView.frame.size.width;
   if (offsetx < 0) {
       offsetx = 0;
   }else if (offsetx > offsetMax){
       if (offsetMax > 0) {
           offsetx = offsetMax;
       }else{
           offsetx = 0;
       }
       
   }
   CGPoint offset = CGPointMake(offsetx, self.smallScrollView.contentOffset.y);
   //  要放在gcd里才有动画,??????
   dispatch_async(dispatch_get_main_queue(), ^{
       [self.smallScrollView setContentOffset:offset animated:YES];
   });

    
    titlelable.scale = 1.0;
    
    CGPoint center = titlelable.center;
    
    CGPoint center2 = self.blueLineView.center;
    
    self.blueLineView.center = CGPointMake(center.x, center2.y);
    _currentIndex = titlelable.tag;
    
    [self.labelArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx != _currentIndex) {
            XBYStatusLabel *temlabel = self.labelArray[idx];
            temlabel.scale = 0.0;
        }
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)tapClick:(UITapGestureRecognizer *)tap
{
    KKPlayerViewController* vc = [KKPlayerViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backToTopClick:(UIButton *)sender
{
    UIScrollView* feedScrollView = [self.videoCell.feedPage.feedViewController getKSCUFeedPageScrollView];
    if (self.hiddenBtn) {
        [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    }else{
        [feedScrollView setContentOffset:CGPointMake(0, 0)];
    }
    
   
    [self.scrollView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
}

#pragma mark - getters and setters
- (UIView *)topWhiteView
{
    if (!_topWhiteView) {
        _topWhiteView = [UIView new];
        _topWhiteView.frame = CGRectMake(0, 0, ScreenWidth, cl_kStatusBarHeight);
        _topWhiteView.backgroundColor = [UIColor whiteColor];
        
        _topWhiteView.alpha = 0;
    }
    return _topWhiteView;
}
- (QFMultiResponseScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[QFMultiResponseScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenHeight - TAB_BAR_HEIGHT)];
        //_scrollView.contentSize = CGSizeMake(ScreenWidth, 941 * WIDTHRADIU + cl_kNavigationBarHeight);
        _scrollView.contentSize = CGSizeMake(ScreenWidth, 325 * WIDTHRADIU + cl_kStatusBarHeight + 10 * WIDTHRADIU + 202 * WIDTHRADIU);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.contentInset = UIEdgeInsetsZero;
        _scrollView.contentOffset = CGPointMake(0, 0);
        _scrollView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _scrollView.delegate = self;
        
        
        FindTableTopCell*headerView = [[NSBundle mainBundle]loadNibNamed:@"FindTableTopCell" owner:nil options:nil].firstObject;
        headerView.delegate = self;
        headerView.backgroundColor = [UIColor whiteColor];
        headerView.frame = CGRectMake(0, 0, ScreenWidth, 325 * WIDTHRADIU + cl_kStatusBarHeight );
        [_scrollView addSubview:headerView];
        headerView.btnHidden = YES;
        [headerView refreshDataWithArray1:self.topDataArr1 andArray2:self.topDataArr2];
        self.topCell = headerView;
        
        FindRecommendBookCell* cell = [[NSBundle mainBundle]loadNibNamed:@"FindRecommendBookCell" owner:nil options:nil].firstObject;
        cell.delegate = self;
        cell.backgroundColor = [UIColor whiteColor];
        cell.frame = CGRectMake(0, CGRectGetMaxY(headerView.frame) + 10 * WIDTHRADIU, ScreenWidth, 0); //202 * WIDTHRADIU
        cell.hidden = YES;
        [_scrollView addSubview:cell];
        self.bookCell = cell;
        
        if (_hiddenBtn) {
            UIView *middleBanner = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame) + 10 * WIDTHRADIU, ScreenWidth, 202 * WIDTHRADIU)];
            self.middleBanner = middleBanner;
            [_scrollView addSubview:middleBanner];
            
            UILabel *lb_fireTitle = [UILabel new];
            [middleBanner addSubview:lb_fireTitle];
            lb_fireTitle.backgroundColor = [UIColor whiteColor];
            lb_fireTitle.attributedText = [[NSMutableAttributedString alloc] initWithString:@"  健康生活" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Semibold" size: 16 * WIDTHRADIU],NSForegroundColorAttributeName: [UIColor colorWithHex:0x333333]}];
            [lb_fireTitle mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(0 * WIDTHRADIU);
                make.top.offset(0 * WIDTHRADIU);
                make.width.offset(ScreenWidth);
                make.height.offset(50 * WIDTHRADIU);
            }];
            
            
            UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10,  60 * WIDTHRADIU, ScreenWidth - 20, 140 * WIDTHRADIU)];
            imgView.image = [UIImage imageNamed:@"life_banner"];
           
            imgView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                       action:@selector(mineHealth)];
            
            [imgView addGestureRecognizer:singleTap];
            [middleBanner addSubview:imgView];
        }
        
//        FindEntertainmentCell*cell2 = [[NSBundle mainBundle]loadNibNamed:@"FindEntertainmentCell" owner:nil options:nil].firstObject;
//        cell2.backgroundColor = [UIColor whiteColor];
//        cell2.frame = CGRectMake(0, CGRectGetMaxY(cell.frame) + 10 * WIDTHRADIU, ScreenWidth, 198 * WIDTHRADIU);
//        [_scrollView addSubview:cell2];
//
//        FindBottomCell*cell3 = [[NSBundle mainBundle]loadNibNamed:@"FindBottomCell" owner:nil options:nil].firstObject;
//        cell3.backgroundColor = [UIColor whiteColor];
//        cell3.frame = CGRectMake(0, CGRectGetMaxY(cell2.frame) + 10 * WIDTHRADIU, ScreenWidth, 195 * WIDTHRADIU);
//        [_scrollView addSubview:cell3];
        
        
        self.smallScrollView.frame = CGRectMake(0, CGRectGetMaxY(self.bookCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 44);
        self.smallScrollView.hidden = YES;
        [_scrollView addSubview:self.smallScrollView];

        self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.smallScrollView.frame), ScreenWidth, ScreenHeight- cl_kNavigationBarHeight - 10);
        self.tableView.hidden = YES;
        [_scrollView addSubview:self.tableView];
        
        
        
        UIView *videoHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.bookCell.frame) + 10 * WIDTHRADIU, ScreenWidth, 48 * WIDTHRADIU)];
        videoHeaderView.backgroundColor = [UIColor whiteColor];
        [_scrollView addSubview:videoHeaderView];

        UIImageView *fireIcon = [UIImageView new];
        fireIcon.image = [UIImage imageNamed:@"live_newsicon"];
        [videoHeaderView addSubview:fireIcon];
        [fireIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(15 * WIDTHRADIU);
            make.centerY.equalTo(videoHeaderView);
            make.width.offset(13 * WIDTHRADIU);
            make.height.offset(16 * WIDTHRADIU);
        }];

        UILabel *lb_fireTitle = [UILabel new];
        [videoHeaderView addSubview:lb_fireTitle];
        lb_fireTitle.attributedText = [[NSMutableAttributedString alloc] initWithString:@"看你想看" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Semibold" size: 16 * WIDTHRADIU],NSForegroundColorAttributeName: [UIColor colorWithHex:0x333333]}];
        [lb_fireTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(fireIcon.mas_right).offset(5 * WIDTHRADIU);
            make.centerY.equalTo(fireIcon);
        }];

        self.videoHeaderView = videoHeaderView;

        HomeVideoContentCell *videoCell = [[HomeVideoContentCell alloc]init];

        videoCell.frame = CGRectMake(0, CGRectGetMaxY(videoHeaderView.frame), ScreenWidth, ScreenHeight - TAB_BAR_HEIGHT - 20);

        [_scrollView addSubview:videoCell];

        [videoCell setupVideoVCWithSelf:self];

        self.videoCell = videoCell;
       
//        videoHeaderView.hidden = YES;
//        self.videoCell.hidden = YES;
        
        _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.tableView.frame) + 10);

//        _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.bookCell.frame) + 10);

    }
    return _scrollView;
}

- (UIScrollView *)smallScrollView {
    if (!_smallScrollView) {
        _smallScrollView = [UIScrollView new];
        _smallScrollView.backgroundColor = [UIColor whiteColor];
        _smallScrollView.showsVerticalScrollIndicator = NO;
        _smallScrollView.showsHorizontalScrollIndicator = NO;
        _smallScrollView.scrollsToTop = NO;
        //        _smallScrollView.layer.borderColor = ColorFromRGB(GGSHighlightGray).CGColor;
        //        _smallScrollView.layer.borderWidth = kSeperatorLineHeight;
    }
    return _smallScrollView;
}

- (KKFindTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[KKFindTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerNib:[UINib nibWithNibName:@"KKListenSubCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.estimatedSectionHeaderHeight = 0;
       _tableView.estimatedSectionFooterHeight = 0;
       _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            currentPage = 1;
            [self.dataArray removeAllObjects];
            [self loadData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
               [self loadData];
           }];
    }
    return _tableView;
}

- (CMPedometer *)pedometer
{
    if (!_pedometer) {
        _pedometer = [[CMPedometer alloc]init];
    }
    return _pedometer;
}

- (UIButton *)TopBtn
{
    if (!_TopBtn) {
        _TopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _TopBtn.backgroundColor = [UIColor blackColor];
        _TopBtn.frame = CGRectMake(0, 0, 80, 40);
        [_TopBtn setTitle:@"返回顶部" forState:UIControlStateNormal];
        [_TopBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _TopBtn.titleLabel.font =[UIFont systemFontOfSize:15];
        _TopBtn.layer.cornerRadius = 20;
        _TopBtn.hidden = YES;
        [_TopBtn addTarget:self action:@selector(backToTopClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _TopBtn;
}
@end
