//
//  MFPageTitleView.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2019/11/30.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "MFPageTitleView.h"
#import "UIView+frameAdjust.h"

@interface MFPageTitleView ()
{
   
}

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)UIView* line;

@property (nonatomic, strong)UIView* indicatorView;

@property (nonatomic, strong)NSArray<NSString *> *titles;

@property (nonatomic, strong)MFPageTitleViewConfig* config;

@property (nonatomic, assign)int selectedIndex;

//存储标题按钮的数组
@property (nonatomic, strong)NSMutableArray<UIButton *> *btnArr;

//标记按钮下标
@property (nonatomic, assign)NSInteger signBtnIndex;
//按钮的总宽度
@property (nonatomic,assign)CGFloat allBtnWidth;
@property (nonatomic, strong)UIButton* lastBtn;
@property (nonatomic,assign)CGFloat totalExtraWidth;

@end

@implementation MFPageTitleView
#pragma mark - life cycle
- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray *)titles config:(MFPageTitleViewConfig *)config
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.frame = frame;
        if (titles.count < 1) {
            [[NSException exceptionWithName:@"MFPagingView" reason:@"标题数组元素不能为0" userInfo:nil] raise];
        }
        self.titles = titles;
        self.config = config;
        self.selectedIndex = config.selectedIndex;
        self.btnArr = [[NSMutableArray alloc]init];
        [self setupUI];
        
    }
    return self;
}

- (void)dealloc
{
    NSLog(@"MFPageTitleView被销毁了");
}

- (void)setupUI
{
    UIView *tempView = [[UIView alloc]initWithFrame:CGRectZero];
    [self addSubview:tempView];
    [self addSubview:self.scrollView];
    if (self.config.showBottomSeparator) {
        [self addSubview:self.line];
    }
    [self.scrollView insertSubview:self.indicatorView atIndex:0];
    [self setupButtons];
}

- (void)setupButtons
{
   __block CGFloat totalTextWidth = 0;
    WeakSelf
    // 计算所有按钮的文字宽度
    for (NSString* title in self.titles) {
        CGFloat tempWidth = [title MF_widthWithfont:self.config.titleFont size:CGSizeMake(0, 0)];
        totalTextWidth += tempWidth;
    }
    
    // 所有按钮文字宽度 ＋ 按钮之间的间隔
    self.allBtnWidth = self.config.spacingBetweenButtons *(self.titles.count + 1) + totalTextWidth;
    
    CGFloat count = (CGFloat)self.titles.count;
    
    if (self.allBtnWidth <= self.width) {
      __block  CGFloat btnX = 0;
      __block  CGFloat btnY = 0;
      __block  CGFloat btnH = self.height;
        
        [self.titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGFloat btnW = self.width / count;
            CGFloat tempWidth = [obj MF_widthWithfont:self.config.titleFont size:CGSizeMake(0, 0)] + self.config.spacingBetweenButtons;
            if (tempWidth > btnW) {
                CGFloat extraWidth = tempWidth - btnW;
                btnW = tempWidth;
                totalTextWidth += extraWidth;
            }
            
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
            btnX += btnW;
            btn.tag = idx;
            [btn setTitle:obj forState:UIControlStateNormal];
            [btn setTitleColor:self.config.titleColor forState:UIControlStateNormal];
            [btn setTitleColor:self.config.titleSelectedColor forState:UIControlStateSelected];
            btn.titleLabel.font = self.config.titleFont;
            [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
            [weakSelf.scrollView addSubview:btn];
            [weakSelf.btnArr addObject:btn];
        }];
        
        self.scrollView.contentSize = CGSizeMake(self.width + _totalExtraWidth, 0);
    }else {
        __block  CGFloat btnX = 0;
        __block  CGFloat btnY = 0;
        __block  CGFloat btnH = self.height;
        
        [self.titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGFloat btnW = [obj MF_widthWithfont:self.config.titleFont size:CGSizeMake(0, 0)] + self.config.spacingBetweenButtons;
            UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
            btnX += btnW;
            btn.tag = idx;
            [btn setTitle:obj forState:UIControlStateNormal];
            [btn setTitleColor:self.config.titleColor forState:UIControlStateNormal];
            [btn setTitleColor:self.config.titleSelectedColor forState:UIControlStateSelected];
            btn.titleLabel.font = self.config.titleFont;
            [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
            [weakSelf.scrollView addSubview:btn];
            [weakSelf.btnArr addObject:btn];
        }];
        
        UIView *view = self.scrollView.subviews.lastObject;
        CGFloat scrollViewWidth = view.maxX;
        self.scrollView.contentSize = CGSizeMake(scrollViewWidth, 0);
        
        
    }
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    UIButton* lastBtn = self.btnArr.lastObject;
    if (lastBtn.tag >= self.selectedIndex && self.selectedIndex >= 0) {
        [self btnDidClick:self.btnArr[self.selectedIndex]];
    }else{
        return;
    }
}




//滚动标题选中按钮居中
- (void)scrollCenter:(UIButton *)selectedBtn
{
    CGFloat offsetX = selectedBtn.centerX - self.width * 0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    
    CGFloat maxOffsetX = self.scrollView.contentSize.width - self.width;
    
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
    
}
//改变按钮的选择状态
- (void)changeSelectedButton:(UIButton *)button
{
    if (!self.lastBtn) {
        [button setSelected:YES];
        self.lastBtn = button;
    }else if (self.lastBtn && self.lastBtn == button){
        [button setSelected:YES];
    }else if (self.lastBtn && self.lastBtn != button){
        [self.lastBtn setSelected:NO];
        [button setSelected:YES];
        self.lastBtn = button;
    }
}


#pragma mark - public methods
- (void)setPageTitleView:(CGFloat)progress originalIndex:(NSInteger)originalIndex targetIndex:(NSInteger)targetIndex
{
    UIButton *originalBtn = self.btnArr[originalIndex];
    UIButton *targetBtn = self.btnArr[targetIndex];
    self.signBtnIndex = targetBtn.tag;
    [self scrollCenter:targetBtn];
    //处理指示器的逻辑
    if (self.allBtnWidth <= self.width) {
        if (_totalExtraWidth > 0) {
            [self indicatorScrollAtScroll:progress originalBtn:originalBtn targetBtn:targetBtn];
        }else {
            [self indicatorScrollAtStatic:progress originalBtn:originalBtn targetBtn:targetBtn];
        }
    }else{
         [self indicatorScrollAtScroll:progress originalBtn:originalBtn targetBtn:targetBtn];
    }
}


#pragma mark - private methods
- (void)indicatorScrollAtStatic:(CGFloat)progress originalBtn:(UIButton *)originalBtn targetBtn:(UIButton *)targetBtn
{
    if (progress >= 0.8) {
        [self changeSelectedButton:targetBtn];
    }
    
    /// 计算 indicatorView 偏移量
    CGFloat targetBtnTextWidth = [targetBtn.currentTitle MF_widthWithfont:self.config.titleFont size:CGSizeZero];
    CGFloat targetBtnIndicatorX = targetBtn.maxX - targetBtnTextWidth - 0.5 * (self.width/self.titles.count -targetBtnTextWidth);
    CGFloat originalBtnTextWidth = [originalBtn.currentTitle MF_widthWithfont:self.config.titleFont size:CGSizeZero];
    CGFloat originalBtnIndicatorX = originalBtn.maxX - originalBtnTextWidth - 0.5 * (self.width/self.titles.count - originalBtnTextWidth);
    
    CGFloat totalOffsetX = targetBtnIndicatorX - originalBtnIndicatorX;
    
    CGFloat btnWidth = self.width/self.titles.count;
    CGFloat targetBtnRightTextX = targetBtn.maxX - 0.5 * (btnWidth - targetBtnTextWidth);
    CGFloat originalBtnRightTextX = originalBtn.maxX - 0.5 * (btnWidth - originalBtnTextWidth);
    CGFloat totalRightTextDistance = targetBtnRightTextX - originalBtnRightTextX;
    
    CGFloat offsetX = totalOffsetX * progress;
    CGFloat distance = progress * (totalRightTextDistance - totalOffsetX);
    
    CGRect frame = self.indicatorView.frame;
       
    frame.origin.x = originalBtnIndicatorX + offsetX;
       
    self.indicatorView.frame = frame;
    
    CGFloat tempIndicatorWidth = originalBtnTextWidth + distance;
    
    if (tempIndicatorWidth >= targetBtn.width) {
        CGFloat moveTotalX = targetBtn.x - originalBtn.x;
        CGFloat moveX = moveTotalX * progress;
        CGPoint center = self.indicatorView.center;
        
        center.x = originalBtn.centerX + moveX;
        
        self.indicatorView.center = center;
    }else{
        CGRect frame = self.indicatorView.frame;
           
        frame.size.width = tempIndicatorWidth;
           
        self.indicatorView.frame = frame;
    }
    

}
- (void)indicatorScrollAtScroll:(CGFloat)progress originalBtn:(UIButton *)originalBtn targetBtn:(UIButton *)targetBtn
{
    if (progress >= 0.8) {
        [self changeSelectedButton:targetBtn];
    }
    
    CGFloat totalOffsetX = targetBtn.x - originalBtn.x;
    
    CGFloat totalDistance = targetBtn.maxX - originalBtn.maxX;
    
    CGFloat offsetX = 0;
    CGFloat distance = 0;
    
    CGFloat targetBtnTextWidth = [targetBtn.currentTitle MF_widthWithfont:self.config.titleFont size:CGSizeZero];
    CGFloat tempIndicatorWidth = targetBtnTextWidth;
    
    if (tempIndicatorWidth >= targetBtn.width) {
        offsetX = totalOffsetX * progress;
        distance = progress * totalDistance - totalOffsetX;
        
        
    }else{
        offsetX = totalOffsetX * progress + 0.5 * self.config.spacingBetweenButtons;
        distance = progress * (totalDistance - totalOffsetX) - self.config.spacingBetweenButtons;
    }
    
    CGRect frame = self.indicatorView.frame;
    
    frame.origin.x = originalBtn.x + offsetX;
    
    frame.size.width = originalBtn.width + distance;
    
    self.indicatorView.frame = frame;
}


#pragma mark - event response
- (void)btnDidClick:(UIButton *)sender
{
    [self changeSelectedButton:sender];
    
    [self scrollCenter:sender];
    
    if (self.allBtnWidth > self.width || self.totalExtraWidth > 0) {
        [self scrollCenter:sender];
    }
    
    [UIView animateWithDuration:0.1 animations:^{
        
        CGRect frame = self.indicatorView.frame;
        frame.size.width = [sender.currentTitle MF_widthWithfont:self.config.titleFont size:CGSizeMake(0, 0)];
        
        self.indicatorView.frame = frame;
        
        CGPoint center = self.indicatorView.center;
        
        center.x = sender.centerX;
        
        self.indicatorView.center = center;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(selectedIndexInPageTitleView:selectedIndex:)]) {
            [self.delegate selectedIndexInPageTitleView:self selectedIndex:sender.tag];
        }
        self.signBtnIndex = sender.tag;
    }];
    
}



#pragma mark - getters and setters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}
//底部分割线
- (UIView *)line
{
    if (!_line) {
        _line = [[UIView alloc]initWithFrame:CGRectMake(0, self.height - 1, self.width, 1)];
        _line.backgroundColor = K_RGB(244, 244, 244);
    }
    return _line;
}
//指示器
- (UIView *)indicatorView
{
    if (!_indicatorView) {
        _indicatorView = [[UIView alloc]initWithFrame:CGRectMake(0, self.scrollView.height - 3, 0, 2)];
        _indicatorView.backgroundColor = self.config.indicatorColor;
    }
    return _indicatorView;
}


- (NSArray *)titles
{
    if (!_titles) {
        _titles = @[];
    }
    return _titles;
}

- (MFPageTitleViewConfig *)config
{
    if (!_config) {
        _config = [[MFPageTitleViewConfig alloc]init];
    }
    return _config;
}


- (void)setSelectedIndex:(int)selectedIndex
{
    if (_selectedIndex != selectedIndex) {
        _selectedIndex = selectedIndex;
        [self btnDidClick:self.btnArr[_selectedIndex]];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/







@end
