//
//  SLMikeSegment.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/6.
//

#import "SLMikeSegment.h"
#import "UIButton+TitleAndImageLayout.h"

#define SLMikeSegmentBtnTag 3888
#define SLMikeSegmentLineViewTag 3275


@interface SLMikeSegment ()

@property (nonatomic, strong) NSMutableArray<SLMikeSegmentModel *> * titleArray;

@property (nonatomic, assign) BOOL isHor;
@end

@implementation SLMikeSegment

- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSArray<SLMikeSegmentModel *> *)titleArray isHor:(BOOL)isHor {
    self.isHor = isHor;
    return [self initWithFrame:frame titleArray:titleArray];
}

- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSArray<SLMikeSegmentModel *> *)titleArray {
    if (self = [super initWithFrame:frame]) {
        self.titleArray = [NSMutableArray arrayWithArray:titleArray];
        if (_titleArray.count <= 0) return self;
        
        self.cornerRadius = 8.0f;
        self.borderWidth = 1.0f;
        _normalBackgroundColor = [UIColor colorFormString:@"#4C4C4C"];
        _selectBackgroundColor = [UIColor colorFormString:@"#4C4C4C"];
        _titleNormalColor = [UIColor whiteColor];
        _titleSelectColor = [UIColor whiteColor];
        _selectIndex = 0;
        _normalTitleFont = 13.0f;
        _selectTitleFont = 13.0f;
        
        [self setUI];
    }
    return self;
}

- (void)setUI
{
    self.clipsToBounds = YES;
    self.layer.borderColor = self.selectBackgroundColor.CGColor;
    
    CGFloat itemWidth = (!self.isHor ? self.frame.size.width : self.frame.size.height) / _titleArray.count;
    [self.titleArray enumerateObjectsUsingBlock:^(SLMikeSegmentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(itemWidth * idx, 0, itemWidth, self.frame.size.height);
        button.clipsToBounds = YES;
        button.tag = SLMikeSegmentBtnTag + idx;
        [self setBtnTitleNormalOrSelectFont:button buttonTitle:obj.segTitle state:UIControlStateNormal font:_normalTitleFont color:_titleNormalColor];
        
        [self setBtnTitleNormalOrSelectFont:button buttonTitle:obj.segTitle state:UIControlStateSelected font:_selectTitleFont color:_titleSelectColor];
        button.backgroundColor = _normalBackgroundColor;
        [button setImage:ImageName(obj.segImage) forState:UIControlStateNormal];
        
        [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:0];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (self.isHor) {
            button.frame = CGRectMake(0, itemWidth * idx, self.frame.size.width, itemWidth);
            if (idx != _titleArray.count - 1) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(44, itemWidth - 1, self.frame.size.width - 44, 1)];
                line.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.2];
                [button addSubview:line];
            }
            [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:8];
        }
        [self addSubview:button];
        [self sendSubviewToBack:button];
        
        if (idx == _titleArray.count - 1) *stop = YES;
    }];
}

- (void)buttonClick:(UIButton *)button
{
    if (_delegate && [_delegate respondsToSelector:@selector(customSegmentSelectIndex:title:)]) {
        [_delegate customSegmentSelectIndex:_selectIndex title:button.titleLabel.text];
    }
    SLMikeSegmentModel *model = _titleArray[button.tag - SLMikeSegmentBtnTag];
    if (self.mikeSegmentBlock) {
        self.mikeSegmentBlock(model);
    }
    
}

- (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:SLMikeSegmentBtnTag + 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:SLMikeSegmentBtnTag + i];
        if (button) {
            [button setBackgroundImage:[self createImageWithColor:selectBackgroundColor] forState:UIControlStateSelected];
        }
        
        UIView * lineView = [self viewWithTag:SLMikeSegmentLineViewTag + 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:SLMikeSegmentBtnTag + i];
        if (button) {
            SLMikeSegmentModel *model = _titleArray[_selectIndex];
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:model.segTitle 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:SLMikeSegmentBtnTag + i];
        if (button) {
            SLMikeSegmentModel *model = _titleArray[_selectIndex];
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:model.segTitle state:UIControlStateNormal font:_normalTitleFont color:_titleNormalColor];
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:model.segTitle 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:SLMikeSegmentBtnTag + i];
        if (button) {
            SLMikeSegmentModel *model = _titleArray[_selectIndex];
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:model.segTitle 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:SLMikeSegmentBtnTag + i];
        if (button) {
            SLMikeSegmentModel *model = _titleArray[_selectIndex];
            [self setBtnTitleNormalOrSelectFont:button buttonTitle:model.segTitle state:UIControlStateSelected font:selectTitleFont color:_titleSelectColor];
        }
    }
}
#pragma mark - 设置title
- (void)setTitleString:(NSString *)titleString withTag:(NSInteger)tag{
    SLMikeSegmentModel *model = _titleArray[tag];
    if (titleString == model.segTitle) return;
    [_titleArray replaceObjectAtIndex:tag withObject:model];
    UIButton * button = (UIButton *)[self viewWithTag:SLMikeSegmentBtnTag + tag];
    if (button) {
        [self setBtnTitleNormalOrSelectFont:button buttonTitle:model.segTitle 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:SLMikeSegmentBtnTag + 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:SLMikeSegmentBtnTag + i];
        if (button) {
            button.selected = selectIndex == i ? YES : NO;
            button.userInteractionEnabled = selectIndex == i ? NO : YES;
            if (selectIndex == i) {
                [self buttonClick:button];
            }
        }
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(NSMutableArray<SLMikeSegmentModel *> *)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
