//
//  YMCustomSegment.m
//  PCDBank
//
//  Created by Gusont on 2020/10/26.
//  Copyright © 2020 YMBank. All rights reserved.
//
#define CustomSegmentBtnTag 888
#define CustomSegmentLineViewTag 275


#import "SLCustomSegment.h"

@interface SLCustomSegment ()

@property (nonatomic, strong) NSMutableArray * titleArray;

@end

@implementation SLCustomSegment

- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSArray *)titleArray
{
    if (self = [super initWithFrame:frame]) {
        self.titleArray = [NSMutableArray arrayWithArray:titleArray];
        if (_titleArray.count <= 0) return self;
        
        self.cornerRadius = 4.0f;
        self.borderWidth = 1.0f;
        _normalBackgroundColor = [UIColor whiteColor];
        _selectBackgroundColor = [UIColor redColor];
        _titleNormalColor = [UIColor lightGrayColor];
        _titleSelectColor = [UIColor blueColor];
        _selectIndex = 0;
        _normalTitleFont = 14.0f;
        _selectTitleFont = 23.0f;
        
        [self setUI];
    }
    return self;
}

- (void)setUI
{
    self.clipsToBounds = YES;
    self.layer.borderColor = self.selectBackgroundColor.CGColor;
    
    CGFloat itemWidth = (1.0 * self.frame.size.width - 20) / _titleArray.count;
    for (int i = 0; i < _titleArray.count; i ++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(itemWidth * i + 10, 6, itemWidth, self.frame.size.height - 12);
        button.clipsToBounds = YES;
        button.layer.cornerRadius = button.frame.size.height / 2.0;
        button.tag = CustomSegmentBtnTag + i;
        
        [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateNormal font:_normalTitleFont color:_titleNormalColor];
        [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateSelected font:_selectTitleFont color:_titleSelectColor];
        
        [button setBackgroundImage:[self createImageWithColor:_normalBackgroundColor] forState:UIControlStateNormal];
        [button setBackgroundImage:[self createImageWithColor:_normalBackgroundColor] forState:UIControlStateHighlighted];
        [button setBackgroundImage:[self createImageWithColor:_selectBackgroundColor] forState:UIControlStateSelected];
        
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:button];
        [self sendSubviewToBack:button];
        
        if (_selectIndex == i) {
            button.selected = YES;
            button.userInteractionEnabled = NO;
        }
        
        if (i == _titleArray.count - 1) continue;
        
//        UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(itemWidth * (i + 1), 0, 1, self.frame.size.height)];
//        lineView.tag = CustomSegmentLineViewTag + i;
//        lineView.backgroundColor = _selectBackgroundColor;
//        [self addSubview:lineView];
        
    }
}

- (void)buttonClick:(UIButton *)button
{
    if (button.tag - CustomSegmentBtnTag == _selectIndex) return;
    
    UIButton * oldButton = (UIButton *)[self viewWithTag:_selectIndex + CustomSegmentBtnTag];
    if (oldButton) {
        oldButton.selected = NO;
        oldButton.userInteractionEnabled = YES;
        /** 因为selected改变 所有要重新设置titl **/
        [self setBtnTitleNormalOrSelectFont:oldButton buttonTitle:_titleArray[_selectIndex] state:UIControlStateNormal font:_selectTitleFont color:[button.titleLabel textColor]];
    }
    button.selected = YES;
    button.userInteractionEnabled = NO;
    
    _selectIndex = button.tag - CustomSegmentBtnTag;
     [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[_selectIndex] state:UIControlStateSelected font:_selectTitleFont color:_titleSelectColor];
    if (_delegate && [_delegate respondsToSelector:@selector(customSegmentSelectIndex:)]) {
        [_delegate customSegmentSelectIndex:_selectIndex];
    }
    
}

- (void)setCornerRadius:(CGFloat)cornerRadius
{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = cornerRadius;
}
- (void)setBorderWidth:(CGFloat)borderWidth
{
    _borderWidth = borderWidth;
    self.layer.borderWidth = borderWidth;
}
#pragma mark - 设置item背景颜色
- (void)setNormalBackgroundColor:(UIColor *)normalBackgroundColor
{
    if (normalBackgroundColor == _normalBackgroundColor) return;
    
    _normalBackgroundColor = normalBackgroundColor;
    for (int i = 0; i < self.titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            [button setBackgroundImage:[self createImageWithColor:normalBackgroundColor] forState:UIControlStateNormal];
            [button setBackgroundImage:[self createImageWithColor:normalBackgroundColor] forState:UIControlStateHighlighted];
        }
    }
}

- (void)setSelectBackgroundColor:(UIColor *)selectBackgroundColor
{
    if (selectBackgroundColor == _selectBackgroundColor) return;
    
    _selectBackgroundColor = selectBackgroundColor;
    for (int i = 0; i < self.titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            [button setBackgroundImage:[self createImageWithColor:selectBackgroundColor] forState:UIControlStateSelected];
        }
        
        UIView * lineView = [self viewWithTag:CustomSegmentLineViewTag + i];
        if (lineView) {
            lineView.backgroundColor = selectBackgroundColor;
        }
    }
    
    self.layer.borderColor = selectBackgroundColor.CGColor;
}
#pragma mark - 设置字体颜色
- (void)setTitleNormalColor:(UIColor *)titleNormalColor
{
    if (titleNormalColor == _titleNormalColor) return;
    
    _titleNormalColor = titleNormalColor;
    for (int i = 0; i < self.titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateNormal font:_normalTitleFont color:titleNormalColor];
        }
    }
}

- (void)setTitleSelectColor:(UIColor *)titleSelectColor
{
    if (titleSelectColor == _titleSelectColor) return;
    
    _titleSelectColor = titleSelectColor;
    for (int i = 0; i < self.titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateNormal font:_normalTitleFont color:_titleNormalColor];
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateSelected font:_selectTitleFont color:_titleSelectColor];
        }
    }
}
#pragma mark - 设置字体大小
- (void)setNormalTitleFont:(CGFloat)normalTitleFont
{
    if (normalTitleFont == _normalTitleFont) return;
    
    _normalTitleFont = normalTitleFont;
    for (int i = 0; i < self.titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateNormal font:normalTitleFont color:_titleNormalColor];
        }
    }
}
- (void)setSelectTitleFont:(CGFloat)selectTitleFont
{
    if (selectTitleFont == _selectTitleFont) return;
    
    _selectTitleFont = selectTitleFont;
    for (int i = 0; i < self.titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:UIControlStateSelected font:selectTitleFont color:_titleSelectColor];
        }
    }
}
#pragma mark - 设置title
- (void)setTitleString:(NSString *)titleString withTag:(NSInteger)tag{
    
    if (titleString == _titleArray[tag]) return;
    [_titleArray replaceObjectAtIndex:tag withObject:titleString];
    UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + tag];
    if (button) {
        [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[tag] state:button.state font:_selectTitleFont color:_titleSelectColor];
    }
}
- (void)setTitlesWithArray:(NSArray *)array{

    [_titleArray removeAllObjects];
    _titleArray = [NSMutableArray arrayWithArray:array];
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
        obj = nil;
    }];
    [self setUI];
//    for (int i = 0; i < self.titleArray.count; i ++) {
//        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
//        if (button) {
//            [self setBtnTitleNormalOrSelectFont:button buttonTitle:_titleArray[i] state:button.state font:_selectTitleFont color:[button.titleLabel textColor]];
//        }
//        if (button.state) {
//            NSLog(@"%@",button.currentTitle);
//        }
//    }
}
- (void)setBtnTitleNormalOrSelectFont:(UIButton *)button buttonTitle:(NSString *)buttonTitle state:(UIControlState)state font:(CGFloat )font color:(UIColor *)color
{
    NSDictionary * dic = @{
                           NSFontAttributeName : [UIFont fontWithName:@"Helvetica" size:font],
                           NSForegroundColorAttributeName : color
                           };
    NSAttributedString * attributedTitle = [[NSAttributedString alloc] initWithString:buttonTitle attributes:dic];
    [button setAttributedTitle:attributedTitle forState:state];
}
#pragma mark - 选中的item
- (void)setSelectIndex:(NSInteger)selectIndex
{
    if (selectIndex >= _titleArray.count || _selectIndex == selectIndex) return;
    
    _selectIndex = selectIndex;
    for (int i = 0; i < _titleArray.count; i ++) {
        UIButton * button = (UIButton *)[self viewWithTag:CustomSegmentBtnTag + i];
        if (button) {
            button.selected = selectIndex == i ? YES : NO;
            button.userInteractionEnabled = selectIndex == i ? NO : YES;
        }
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(NSMutableArray *)titleArray{

    if (_titleArray == nil) {
        _titleArray = [NSMutableArray new];
    }
    return _titleArray;
}
- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
@end
