//
//  LIstenHistoryViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/7/10.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "LIstenHistoryViewController.h"
#import "XBYStatusLabel.h"
#import "AlbumHistoryController.h"
#import "TrackHistoryController.h"

@interface LIstenHistoryViewController ()<UIScrollViewDelegate>
{
    CGFloat lastContentOffset;
}

@property (nonatomic, strong)UIScrollView*smallScrollView;

@property (nonatomic, strong)UIScrollView* bigScrollView;

@property (nonatomic, strong)UIView* blueView;

@property (nonatomic, strong)NSArray* titleArray;

@property (nonatomic, strong)NSMutableArray* lbArray;

@property (nonatomic, strong)NSMutableArray* childVcs;

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

@end

@implementation LIstenHistoryViewController

//- (void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//    // 禁用返回手势
//    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//    }
//}
//
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    // 开启返回手势
//    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
//    }
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"收听历史";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //init
    self.currentIndex = -1;
    self.titleArray = @[@"专辑",@"听单"];
    self.lbArray = [NSMutableArray array];
    self.childVcs = [NSMutableArray array];
    [self navConfig];
    
    [self.view addSubview:self.smallScrollView];
    [self.view addSubview:self.bigScrollView];
    
    [self setupSmallScrollView];
    [self setupBigScrollView];
    [self setDefaultController];
    
    
}

- (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];
    
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight , 50, 44);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setTitle:@"返回" 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];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    
    
    
    
    //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);
    }];
}

#pragma mark -Private Method
- (void)setupSmallScrollView
{
   // CGFloat labelW = [ScreenWidth/(self.titleArray.count>4?4:self.titleArray.count)];
    
    CGFloat labelX,labelY,labelW = 0, labelH = 50;
    for (int i = 0; i < self.titleArray.count; i++) {
        NSString*title = self.titleArray[i];
        labelX = i * labelW;
        labelW =ScreenWidth /self.titleArray.count;
        XBYStatusLabel *label = [[XBYStatusLabel alloc]initWithFrame:CGRectMake(labelX, labelY, labelW, labelH)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor colorWithHex:0x4d4d4d];
        label.text = title;
        label.tag = i;
        label.userInteractionEnabled = YES;
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapAction:)]];
        [self.smallScrollView addSubview:label];
        [self.lbArray addObject:label];
        if (i == 0) {
            UIView*blueView = [[UIView alloc]init];
            blueView.backgroundColor = K_MainColor;
            blueView.frame = CGRectMake(0, 46, 80, 4);
            blueView.center = CGPointMake(label.center.x, blueView.center.y);
            [self.smallScrollView addSubview:blueView];
            self.blueView = blueView;
        }
    }
    
    
}
- (void)setupBigScrollView {
    
    for (int i = 0; i < self.titleArray.count; i++) {
        if (i == 0) {
            AlbumHistoryController*vc = [AlbumHistoryController new];
            [self.childVcs addObject:vc];
        }else if (i == 1){
            TrackHistoryController*vc = [TrackHistoryController new];
            [self.childVcs addObject:vc];
        }
        
    }

    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.lbArray firstObject];
    lable.scale = 1.0;
}



#pragma mark - UIScrollViewDelegate
/** 滚动结束后调用（代码导致） */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    // 获得索引
    NSUInteger index = scrollView.contentOffset.x / self.bigScrollView.frame.size.width;
    
    // 滚动标题栏
    XBYStatusLabel *titleLable = (XBYStatusLabel *)self.lbArray[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.lbArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx != index) {
            XBYStatusLabel *temlabel = self.lbArray[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.lbArray[(int)value];
    
//    CGPoint center = titleLabel.center;
    
   // CGPoint center2 = self.blueLineView.center;
    
    //self.blueLineView.center = CGPointMake(center.x, center2.y);
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//全局变量记录滑动前的contentOffset
   //lastContentOffset = scrollView.contentOffset.y;//判断上下滑动时
   
    lastContentOffset = scrollView.contentOffset.x;//判断左右滑动时
}

/** 正在滚动 */
- (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.lbArray[leftIndex];
    labelLeft.scale = scaleLeft;
    
    
    // 考虑到最后一个板块，如果右边已经没有板块了 就不在下面赋值scale了
    if (rightIndex < self.lbArray.count) {
        XBYStatusLabel *labelRight = self.lbArray[rightIndex];
        labelRight.scale = scaleRight;
    }
    
    if (scrollView.contentOffset.x > lastContentOffset ){
        CGRect frame = self.blueView.frame;
        
        CGFloat x1 = (ScreenWidth/2- 80)/2;
        CGFloat x2 =(ScreenWidth/2- 80)/2 + ScreenWidth/2;
//        CGFloat x3 = ScreenWidth - (ScreenWidth/2- 80)/2;
        CGFloat sum1 = x2 - x1 - 80;
        CGFloat sum2 = 80;
        CGFloat sum3 = ScreenWidth/2- 80;
        CGFloat sum = sum1 + sum2 +sum3;
        CGFloat scale1 = sum1/sum;
        CGFloat scale2 = (sum1+sum2)/sum;
        CGFloat scale3 = (sum1 + sum2 + sum3)/sum;
        if (value >=0 && value <= scale1) {
            frame.size.width = 80 + value* sum;
        }else if (value > scale1 && value <= scale2 ){
            frame.origin.x = x1 + (value - scale1) * sum;
        }else if (value > scale2 && value <= scale3){
            
            frame.size.width = sum1 + sum2 - (value - scale2)* sum;
            frame.origin.x = x1 + sum2 + (value - scale2)* sum;
        }
        self.blueView.frame = frame;
    }else{
        CGRect frame = self.blueView.frame;
        
        CGFloat x1 = (ScreenWidth/2- 80)/2;
        CGFloat x2 =(ScreenWidth/2- 80)/2 + ScreenWidth/2;
//        CGFloat x3 = ScreenWidth - (ScreenWidth/2- 80)/2;
        CGFloat sum1 = x2 - x1 - 80;
        CGFloat sum2 = 80;
        CGFloat sum3 = ScreenWidth/2- 80;
        CGFloat sum = sum1 + sum2 +sum3;
        CGFloat scale1 = sum1/sum;
        CGFloat scale2 = (sum1+sum2)/sum;
        CGFloat scale3 = (sum1 + sum2 + sum3)/sum;
        if (value >=0 && value <= scale1) {
            frame.size.width = 80 + value* sum;
            frame.origin.x = x1;
        }else if (value > scale1 && value <= scale2 ){
            frame.origin.x = x1 + (value - scale1) * sum;
            NSLog(@"%.2f",frame.origin.x);
        }else if (value > scale2 && value <= scale3){
            
            frame.size.width = sum1 + sum2 - (value - scale2)* sum;
            frame.origin.x = x1 + sum2 + (value - scale2)* sum;
        }
        self.blueView.frame = frame;
        
    }
    
    
//    if (scrollView.contentOffset.x < lastContentOffset ){
//        //向右
//        NSLog(@"左滑");
//        CGRect frame = self.blueView.frame;
//       CGFloat minX = CGRectGetMinX(frame);
//       CGFloat Width = CGRectGetWidth(frame);
//       CGFloat scale = ( lastContentOffset -scrollView.contentOffset.x)/ScreenWidth;
//       if (minX > (ScreenWidth/2 -  (ScreenWidth/2 - 80)/2)) {
//               frame.origin.x = (ScreenWidth/2 - 80)/2 + ScreenWidth/2 - scale * ScreenWidth/2;
//               frame.size.width = 80 +scale * ScreenWidth/2 ;
//          }else{
//              frame.origin.x = (ScreenWidth/2 - 80)/2;
//               frame.size.width = 80 +( ScreenWidth -(lastContentOffset-scrollView.contentOffset.x))/2 ;  ;
//        }
//
//      self.blueView.frame = frame;
//
//    } else if (scrollView.contentOffset.x > lastContentOffset ){
//        //向左
//        NSLog(@"右滑");
//        CGRect frame = self.blueView.frame;
//        CGFloat minX = CGRectGetMinX(frame);
//        CGFloat Width = CGRectGetWidth(frame);
//        CGFloat scale = (scrollView.contentOffset.x - lastContentOffset)/ScreenWidth;
//        if ((minX + Width) < (ScreenWidth/2 + (ScreenWidth/2 - 80)/2)) {
//             frame.size.width = 80 +scale * ScreenWidth/2 ;
//        }else{
//            frame.origin.x = (ScreenWidth/2 - 80)/2 + (scrollView.contentOffset.x - lastContentOffset)/2;
//             frame.size.width = 80 +( ScreenWidth -(scrollView.contentOffset.x - lastContentOffset))/2 ;
//        }
//
//        self.blueView.frame = frame;
//    }
    
    
}

#pragma mark - event reposne
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)labelTapAction:(UIGestureRecognizer *)tap{
    XBYStatusLabel *titlelable = (XBYStatusLabel *)tap.view;
    if (titlelable.tag == _currentIndex) {
      return;
    }
    
    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];
    
    
    
    _currentIndex = titlelable.tag;
    
}


#pragma mark - getters
- (UIScrollView *)smallScrollView
{
    if (!_smallScrollView) {
        _smallScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 50)];
        _smallScrollView.contentSize = CGSizeMake(ScreenWidth/2 * 2, 50);
        _smallScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _smallScrollView;;
}

- (UIScrollView *)bigScrollView
{
    if (!_bigScrollView) {
        _bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.smallScrollView.frame), ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - 50)];
        _bigScrollView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _bigScrollView.showsHorizontalScrollIndicator = NO;
        _bigScrollView.contentSize = CGSizeMake(ScreenWidth * 2, ScreenHeight - cl_kNavigationBarHeight - 50);
        _bigScrollView.delegate = self;
        _bigScrollView.pagingEnabled = YES;
        _bigScrollView.bounces = NO;
    }
    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
