//
//  KKLisenViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/6/3.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "KKLisenViewController.h"
#import "XMSDK.h"
#import "KKXMTitleModel.h"
#import "XBYStatusLabel.h"
#import "KKListenSubController.h"
#import "KKListenSub2Controller.h"
#import "KKListenDetailController.h"
#import "ICMusicPlayManager.h"
#import "ProgressView.h"
#import "UIImageView+WebCache.h"
#import "KKSearchBar.h"

#import "SearchAlbumViewController.h"
#import "LIstenHistoryViewController.h"

#import <MediaPlayer/MediaPlayer.h>

#import "XLChannelControl.h"
#import "KKXMCategoryModel.h"

#import "KKScrollVerticalView.h"


@interface KKLisenViewController ()<UIScrollViewDelegate,KKListenSubControllerDelegate,KKListenSub2ControllerDelegate,KKScrollVerticalViewDelegate>
{
    CGFloat smallScrollViewH;
    XMSDKPlayer *_sdkPlayer;
    
    //记录第一个页面的背景色是否显示
    BOOL _isTop;
    
}

@property (nonatomic, strong)NSMutableArray*titleArray;

/**
 一个滑块对应一个viewController
 */
@property (nonatomic, strong) NSMutableArray *childVcs;


/**
存放顶部控件的view
*/
@property (nonatomic, strong) UIView* topView;

@property (nonatomic, strong)UIColor*topBackColor;

/**
 用于存放滑块的scrollView
 */
@property (nonatomic, strong) UIScrollView *smallScrollView;

@property (nonatomic, strong)NSMutableArray* labelArray;

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

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


//搜索框
@property (nonatomic, strong)KKSearchBar* searchBar;

@property (nonatomic, strong)KKScrollVerticalView* searchView;

@property (nonatomic, strong)UIImageView* historyImg;

/**
 用于存放viewController的scrollView
 */
@property (nonatomic, strong) UIScrollView *bigScrollView;

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


@property (nonatomic, strong)UIImageView* iconImg;

@property (nonatomic, strong)ProgressView* progressView;

@property (nonatomic, strong)UIView* shadowView;

@property (nonatomic, strong)UIView* lineView;


@end

@implementation KKLisenViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
    [self.navigationController setNavigationBarHidden:YES];

    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.KKPlayerDidStart = ^{
        XMTrack*track1 = [self->_sdkPlayer currentTrack];
        [self setupLockScreenMediaInfo:track1];
        [self SaveTrackDataRequest:track1];
    };
    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;
       }
    
    [GTCountSDK trackCountEvent:@"listen_mainpage_show" withArgs:@{}];
}

#pragma mark - 锁频控制
//更新通知中心控制台媒体信息
- (void)setupLockScreenMediaInfo:(XMTrack *)track {
    
    MPNowPlayingInfoCenter *playingCenter = [MPNowPlayingInfoCenter defaultCenter];
    
    NSMutableDictionary *playingInfo = [NSMutableDictionary new];
    //标题
    playingInfo[MPMediaItemPropertyTitle]      = track.trackTitle;
    //封面图片
    UIImage *coverImage = nil;
    if ([NSString blankString:track.coverUrlLarge]) {
        coverImage = [UIImage imageNamed:@"trackPlaceImg"];
    }else {
        UIImageView *coverImageView = [[UIImageView alloc] init];
        [coverImageView sd_setImageWithURL:[NSURL URLWithString:track.coverUrlSmall]];
        coverImage = coverImageView.image;
        if (coverImage == nil) {
            coverImage = [UIImage imageNamed:@"trackPlaceImg"];
        }
    }
    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:coverImage];
    playingInfo[MPMediaItemPropertyArtwork] = artwork;
    
    // 当前播放的时间
    NSLog(@"playingInfo . currentTime = %f",track.duration / 1000.0);
    playingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = [NSNumber numberWithFloat:100 / 1000];
    // 进度的速度
    playingInfo[MPNowPlayingInfoPropertyPlaybackRate] = [NSNumber numberWithFloat:1.0];
    // 总时间
    playingInfo[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithFloat:track.duration / 1000];
//    if (@available(iOS 10.0, *)) {
//        playingInfo[MPNowPlayingInfoPropertyPlaybackProgress] = [NSNumber numberWithFloat:self.audioControlView.progress];
//    } else {
//        // Fallback on earlier versions
//    }
    [playingCenter setNowPlayingInfo:playingInfo];
}

//存储播放记录
- (NSDictionary *)SaveTrackDataRequestPara:(XMTrack *)track
{
    
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString*phone = nil;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
        phone = adId;
    }else{
        phone = [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY];
    }
    NSDictionary*para = @{
        @"albumid":@(track.subordinatedAlbum.albumId),
        @"trackid":@(track.trackId),
        @"albumtitle":[NSString validBlankStr:track.subordinatedAlbum.albumTitle],
        @"pageindex":[NSString stringWithFormat:@"%ld",track.orderNum + 1],
        @"allpageindex":@([ICMusicPlayManager sharedManager].albumModel.includeTrackCount),
        @"imageurl":[NSString validBlankStr:track.subordinatedAlbum.coverUrlLarge],
        @"phone":phone,
        @"listentitle":track.trackTitle,
        @"listenindex":@(track.orderNum)
    };
    return para;
}

- (void)SaveTrackDataRequest:(XMTrack *)track
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipXMLYHistoryConfig],XMLYSaveHistoryRequest];
    
    [NetworkRequest Post10:url Params:[self SaveTrackDataRequestPara:track] Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}

#pragma mark - 获取滚动条目
- (void)getSearchItemListRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipXMLYHistoryConfig],XMLYScrollListRquest];
    
    NSDictionary*params = @{
        @"rankType":@(0)
    };
    
    [NetworkRequest Get:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        NSString*state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSArray*array = objc[@"result"];
            NSMutableArray*newArray = [NSMutableArray array];
            for (NSString*str in array) {
                if (str.length < 10) {
                    [newArray addObject:str];
                }
            }
            [UserDefault setObject:newArray forKey:@"kkXMLYScrollListItems"];
            [UserDefault synchronize];
            self.searchView.infoArray = newArray;
        }
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar navBarAlpha:1.0 isOpaque:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"听听";
    smallScrollViewH = 98;
    _currentIndex = -1;
    self.titleArray = [NSMutableArray array];
    self.childVcs = [NSMutableArray array];
    self.labelArray = [NSMutableArray array];
    self.labelWidthArray = [NSMutableArray array];
    self.labelMinXArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    self.topBackColor = K_MainColor;
    
    
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.smallScrollView];
    [self.topView addSubview:self.searchBar];
    [self.topView addSubview:self.searchView];
    [self.topView addSubview:self.historyImg];
    
    self.lineView = [[UIView alloc]init];
    self.lineView.backgroundColor = [UIColor colorWithHex:0xcccccc];
    self.lineView.hidden = YES;
    [self.topView addSubview:self.lineView];
    
    
    [self.view addSubview:self.bigScrollView];
    [self setLayouts];
    
    //喜马拉雅
    [[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]]) {
            XMCategory*category = [[XMCategory alloc]init];
            category.categoryName = @"推荐";
            [self.titleArray addObject:category];
            NSMutableArray* tempArray = [NSMutableArray array];
           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];
               }else{
                   [tempArray addObject:model];
               }
//               if (self.titleArray.count >= 7) {
//                   break;
//               }
           }
            
            [self buildDataWithSelectCategorys:self.titleArray unSelectCategorys:tempArray];
            
            for (int i = 0; i < self.titleArray.count; i++) {
                if (i == 0) {
                    KKListenSub2Controller*vc = [KKListenSub2Controller new];
                    vc.delegate = self;
                    [self.childVcs addObject:vc];
                }else{
                    KKListenSubController*vc = [KKListenSubController new];
                    vc.delegate = self;
                    vc.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
                    XMCategory*model = self.titleArray[i];
                    vc.model = model;
                    
                    [self.childVcs addObject:vc];
                }
                
            }
            
            [self setupSmallScrollView];
            [self setupBigScrollView];
            [self setDefaultController];
        }
        
     }];
    
    _sdkPlayer = [XMSDKPlayer sharedPlayer];
    [_sdkPlayer setPlayMode:XMSDKPlayModeTrack];
    [_sdkPlayer setTrackPlayMode:XMTrackPlayerModeList];
    [_sdkPlayer setAutoNexTrack:YES];
    [[XMSDKPlayer sharedPlayer] setVolume:0.5];
    
    [self navConfig];
    
    [self getSearchItemListRequest];
    
    //专辑曝光数据回传API
}


- (void)navConfig
{
    [self.navigationController setNavigationBarHidden:YES];
    
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = K_MainColor;
    [self.view addSubview:navView];
    
    if (self.fromHome) {
        UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight + 9.5, 20, 25);
        backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
        //    [button_2 setTitle:@"asdasd按时打发第三方" forState:UIControlStateNormal];
        [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
        //    [button_2 setBackgroundColor:[UIColor redColor]];
        //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
        [navView addSubview:backBtn];
    }
    
    
    
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = self.title;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
    
//    UIButton * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    addBtn.frame = CGRectMake( ScreenWidth - 40, cl_kStatusBarHeight + 9.5, 20, 25);
//    addBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
//    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
//    //[addBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    //    [button_2 setBackgroundColor:[UIColor redColor]];
//    //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
//    [addBtn addTarget:self action:@selector(showChannelControl) forControlEvents:UIControlEventTouchUpInside];
//    [navView addSubview:addBtn];
    
    
}

- (void)setLayouts {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    CGFloat top;
    if ([self.parentViewController isKindOfClass:[UINavigationController class]]) {
        top = cl_kStatusBarHeight;
    } else {
        top = 0;
    }
    self.topView.frame = CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, smallScrollViewH);
    self.smallScrollView.frame = CGRectMake(0, 0, ScreenWidth, 44);
    self.searchBar.frame = CGRectMake((CGRectGetWidth(self.topView.frame) * 0.3 - 25 - 25)/2 , CGRectGetMaxY(self.smallScrollView.frame) + 10, CGRectGetWidth(self.topView.frame) * 0.7, 40);
    self.searchView.frame = CGRectMake((CGRectGetWidth(self.topView.frame) * 0.3 - 25 - 25)/2 , CGRectGetMaxY(self.smallScrollView.frame) + 10, CGRectGetWidth(self.topView.frame) * 0.7, 40);
    [self.historyImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.searchBar);
        make.left.equalTo(self.searchBar.mas_right).offset(25);
        make.width.height.offset(25);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(0.5);
    }];
    
    
    self.bigScrollView.frame = CGRectMake(0, CGRectGetMaxY(self.topView.frame), ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - smallScrollViewH);
}

#pragma mark -添加频道数据
//初始化数据
-(void)buildDataWithSelectCategorys:(NSArray *)selectCategorys unSelectCategorys:(NSArray *)categorys
{
    if ([XLChannelControl shareControl].inUseItems.count) {return;}
    
    NSMutableArray *itemArr1 = [NSMutableArray new];
    for (XMCategory *model in selectCategorys) {
        KKXMCategoryModel *item = [KKXMCategoryModel new];
        item.categoryName = model.categoryName;
        item.categoryId = model.categoryId;
        [itemArr1 addObject:item];
    }
    
    NSMutableArray *itemArr2 = [NSMutableArray new];
    for (XMCategory *model in categorys) {
        KKXMCategoryModel *item = [KKXMCategoryModel new];
        item.categoryName = model.categoryName;
        item.categoryId = model.categoryId;
        [itemArr2 addObject:item];
    }
    [XLChannelControl shareControl].inUseItems = itemArr1;
    [XLChannelControl shareControl].unUseItems = itemArr2;
    
}


#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 = 0.0,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 whiteColor];
        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 = [UIColor whiteColor];
            blueLine.tag = 200;
            [self.smallScrollView addSubview:blueLine];
            blueLine.frame = CGRectMake(labelX + (labelW - 30)/2 , labelY + labelH - 4, 30 , 2);
            self.blueLineView = blueLine;
        }
    }
    
    
}
- (void)setupBigScrollView {
    self.bigScrollView.contentSize = CGSizeMake(self.titleArray.count * self.view.frame.size.width, self.view.frame.size.height - cl_kNavigationBarHeight - 44);
    

    NSLog(@"");
}

- (void)setDefaultController {
    // 添加默认控制器
    if (self.titleArray.count == 0) {
        return;
    }
    
    for (int i = 0; i < self.titleArray.count; i++) {
        UIViewController*vc = self.childVcs[i];
        vc.view.frame = CGRectMake(i *CGRectGetWidth(self.bigScrollView.bounds), 0, CGRectGetWidth(self.bigScrollView.bounds), CGRectGetHeight(self.bigScrollView.bounds));
        [self addChildViewController:vc];
        [self.bigScrollView addSubview:vc.view];
        [vc didMoveToParentViewController:self];
    }
    
   
    
    
    
    
    XBYStatusLabel *lable = [self.labelArray firstObject];
    lable.scale = 1.0;
}

- (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];
}


#pragma mark - KKScrollVerticalViewDelegate
- (void)clickViewWithSearchContent:(NSString *)content
{
    NSLog(@"显示content:%@",content);
    NSArray *hotSeaches = @[@"大力史", @"易中天品三国", @"乱世枭雄杜月笙", @"河南豫剧名家名段", @"余魁智", @"米小圈上学记", @"宝宝巴士", @"白眉大侠", @"岳飞传", @"童林传", @"《夜色钢琴曲》", @"李峙的不老歌", @"话说宋朝", @"话说明朝",@"36计的故事"];
    
    
    if (content == nil) {
        return;
    }
    SearchAlbumViewController*vc = [SearchAlbumViewController new];
    
    vc.hotSearches = hotSeaches;
    
    vc.placeString = content;
    
    vc.hidesBottomBarWhenPushed = YES;
    
    
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - UIScrollViewDelegate
/** 滚动结束后调用（代码导致） */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    // 获得索引
    NSUInteger index = scrollView.contentOffset.x / self.bigScrollView.frame.size.width;
    
    // 滚动标题栏
    XBYStatusLabel *titleLable = (XBYStatusLabel *)self.labelArray[index];
    //    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];
    });
    
    UIViewController *oldVC = nil;
    if (_currentIndex != -1) {
        oldVC = self.childVcs[_currentIndex];
    }
    
    UIViewController *newsVc = self.childVcs[index];
    self.currentIndex = index;
    //其他label设置成初始状态
    [self.labelArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx != index) {
            XBYStatusLabel *temlabel = self.labelArray[idx];
            temlabel.scale = 0.0;
        }
    }];
    
    if (newsVc.view.superview)  {//调用生命周期函数(如viewwillappear等)
        if (oldVC) {
            [newsVc beginAppearanceTransition:NO animated:YES];
            [newsVc endAppearanceTransition];
        }
        
        [newsVc beginAppearanceTransition:YES animated:YES];
        [newsVc endAppearanceTransition];
        return;
    }
    
    [self addChildViewController:newsVc];
    newsVc.view.frame = scrollView.bounds;//bounds的x就是scrollView的offsetx
    [self.bigScrollView addSubview:newsVc.view];
    [newsVc didMoveToParentViewController:self];
    
//    if ([self.delegate respondsToSelector:@selector(topTabBarViewController:didAddChildViewController:)]) {
//        [self.delegate topTabBarViewController:self didAddChildViewController:newsVc];
//    }
    
    
   
}

/** 滚动结束（手势导致） */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewDidEndScrollingAnimation:scrollView];
    // CGFloat labelW = ScreenWidth/(self.titleArray.count>4?4:self.titleArray.count);
    CGFloat value = ABS(scrollView.contentOffset.x / scrollView.frame.size.width);
    
    //CGRect frame = self.blueLineView.frame;
    //frame.origin.x = [self getLabelMinXWithIndex:(NSInteger)value];
    //NSNumber* labelW = self.labelWidthArray[(int)value];
    //frame.size.width = labelW.floatValue;
    
    //self.blueLineView.frame = frame;
    
    
    XBYStatusLabel*titleLabel = self.labelArray[(int)value];
    
    CGPoint center = titleLabel.center;
    
    CGPoint center2 = self.blueLineView.center;
    
    self.blueLineView.center = CGPointMake(center.x, center2.y);
    
}



/** 正在滚动 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 取出绝对值 避免最左边往右拉时形变超过1
    CGFloat value = ABS(scrollView.contentOffset.x / scrollView.frame.size.width);
    NSUInteger leftIndex = (int)value;//取整代表左边那个label 不管是哪个方向都是
    NSUInteger rightIndex = leftIndex + 1;
    CGFloat scaleRight = value - leftIndex;
    CGFloat scaleLeft = 1 - scaleRight;
    XBYStatusLabel *labelLeft = self.labelArray[leftIndex];
    labelLeft.scale = scaleLeft;
    
    
    // 考虑到最后一个板块，如果右边已经没有板块了 就不在下面赋值scale了
    if (rightIndex < self.labelArray.count) {
        XBYStatusLabel *labelRight = self.labelArray[rightIndex];
        labelRight.scale = scaleRight;
    }
}


#pragma mark - KKListenSubControllerDelegate
- (void)didSelectedWithVC:(KKListenSubController *)vc model:(XMAlbum *)model
{
    KKListenDetailController*detailVC = [[KKListenDetailController alloc]init];
    
    detailVC.model = model;
    
    detailVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - KKListenSub2ControllerDelegate
- (void)ClickItemWithModel:(XMAlbum *)model
{
    KKListenDetailController*detailVC = [[KKListenDetailController alloc]init];
    
    detailVC.model = model;
    
    detailVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)scrollToTop:(BOOL)toTop
{
    _isTop = toTop;
    [self changeStyleWithState:toTop];
    
}


- (void)changeStyleWithState:(BOOL)toTop
{
    self.topBackColor = !toTop ?K_MainColor :[UIColor whiteColor];
    
    if (toTop) {
        self.lineView.hidden = NO;
        for (XBYStatusLabel* label in self.labelArray) {
            label.showColor = [UIColor colorWithHex:0x333333];
        }
        
        self.blueLineView.backgroundColor = [UIColor colorWithHex:0x333333];
        self.historyImg.image = [UIImage imageNamed:@"xmlahistory_gray"];
    }else{
        self.lineView.hidden = YES;
        for (XBYStatusLabel* label in self.labelArray) {
            label.showColor = [UIColor whiteColor];
        }
        self.blueLineView.backgroundColor = [UIColor whiteColor];
        self.historyImg.image = [UIImage imageNamed:@"xmlahistory_white"];
    }
}


#pragma mark - gesture selector
- (void)labelTapAction:(UITapGestureRecognizer *)gesture {
    XBYStatusLabel *titlelable = (XBYStatusLabel *)gesture.view;
    if (titlelable.tag == _currentIndex) {
        return;
    }
    
    if (titlelable.tag ==0 ) {
        [self changeStyleWithState:_isTop];
    }else{
        [self changeStyleWithState:YES];
    }
    
    CGFloat offsetX = titlelable.tag * self.bigScrollView.frame.size.width;
    
    CGFloat offsetY = self.bigScrollView.contentOffset.y;
    CGPoint offset = CGPointMake(offsetX, offsetY);
    
    [self.bigScrollView setContentOffset:offset animated:YES];
    
    
    //CGFloat labelW = ScreenWidth/(self.titleArray.count>4?4:self.titleArray.count);
       
//    CGRect frame = self.blueLineView.frame;
//    //frame.origin.x = titlelable.tag ;
//    NSNumber*labelW = self.labelWidthArray[titlelable.tag];
//    frame.size.width = labelW.floatValue;
//    self.blueLineView.frame = frame;
    
    
    
    CGPoint center = titlelable.center;
    
    CGPoint center2 = self.blueLineView.center;
    
    self.blueLineView.center = CGPointMake(center.x, center2.y);
}
- (void)tapClick:(UITapGestureRecognizer *)tap
{
    KKPlayerViewController* vc = [KKPlayerViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)searchClick:(UITapGestureRecognizer *)tap
{
    NSLog(@"进入搜索页面");
    
    NSArray *hotSeaches = @[@"大力史", @"易中天品三国", @"乱世枭雄杜月笙", @"河南豫剧名家名段", @"余魁智", @"米小圈上学记", @"宝宝巴士", @"白眉大侠", @"岳飞传", @"童林传", @"《夜色钢琴曲》", @"李峙的不老歌", @"话说宋朝", @"话说明朝",@"36计的故事"];
    
    SearchAlbumViewController*vc = [SearchAlbumViewController new];
    
    vc.hotSearches = hotSeaches;
    
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)checkHistory
{
    LIstenHistoryViewController*vc = [LIstenHistoryViewController new];
    
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)showChannelControl
{
    [[XLChannelControl shareControl] showInViewController:self completion:^(NSArray *channels) {
        NSLog(@"频道管理结束：%@",channels);
    }];
}

#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;
}


#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 - setters
- (void)setTopBackColor:(UIColor *)topBackColor
{
    _topBackColor = topBackColor;
    self.topView.backgroundColor = topBackColor;
    
    
}

#pragma mark - getter
- (UIView *)topView
{
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, smallScrollViewH)];
        _topView.backgroundColor = self.topBackColor;
    }
    return _topView;
}

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

- (KKSearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[KKSearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth * 0.7, 40)];
        _searchBar.backgroundColor = [UIColor whiteColor];
        _searchBar.layer.cornerRadius = 22;
        _searchBar.layer.borderWidth = 0.5;
        _searchBar.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(searchClick:)];
        [_searchBar addGestureRecognizer:tap];
    }
    return _searchBar;
}

- (KKScrollVerticalView *)searchView
{
    if (!_searchView) {
        _searchView = [[KKScrollVerticalView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.topView.frame) * 0.7,40 )];
        _searchView.delegate = self;
        _searchView.backgroundColor = [UIColor whiteColor];
        _searchView.layer.cornerRadius = 22;
        _searchView.layer.borderWidth = 0.5;
        _searchView.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        _searchView.infoArray = @[@"抖音热门歌曲",@"经典老歌",@"郭德纲相声专场",@"单田芳经典",@"张作霖大传"];
    }
    return _searchView;
}

- (UIImageView *)historyImg
{
    if (!_historyImg) {
        _historyImg = [[UIImageView alloc]init];
        _historyImg.image = [UIImage imageNamed:@"xmlahistory_white"];
        _historyImg.userInteractionEnabled = YES;
        
        UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(checkHistory)];
        [_historyImg addGestureRecognizer:tap];
    }
    return _historyImg;
}


- (UIScrollView *)bigScrollView {
    if (!_bigScrollView) {
        _bigScrollView = [UIScrollView new];
        _bigScrollView.showsHorizontalScrollIndicator = NO;
        _bigScrollView.scrollsToTop = NO;
        _bigScrollView.pagingEnabled = YES;
        _bigScrollView.delegate = self;
        _bigScrollView.bounces = NO;
        _bigScrollView.scrollEnabled = NO;
        _bigScrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _bigScrollView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
