//
//  CustomSegView.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/11/6.
//  Copyright © 2015年 Xummer. All rights reserved.
//

#import "CustomSegView.h"
#define BeginBtnTag  2000000

@interface CustomSegView ()
{
    UIView *_bgView;
    NSInteger _currentBtnTag;
}
@property (nonatomic,copy)NSArray *segArr;
@end



@implementation CustomSegView
- (instancetype)initWithFrame:(CGRect)frame withArr:(NSArray *)arr{
    self = [super initWithFrame:frame];
    if (self) {
        self.segArr = arr;
        [self bulidLayout];
    }
    return self;
}

- (void)bulidLayout{
    _bgView = [[UIView alloc]initWithFrame:self.bounds];
    _bgView.layer.borderWidth = 1;
    _bgView.layer.borderColor = ReportColor.CGColor;
    _bgView.layer.cornerRadius = 5;
    _bgView.layer.masksToBounds = YES;
    [self addSubview:_bgView];
    _bgView.clipsToBounds = YES;
    _currentBtnTag = 0;
    CLog(@"%f",_bgView.width);
    CGFloat width = _bgView.width/self.segArr.count;
    for (NSInteger i = 0; i < self.segArr.count; i++) {
        IBTCustomButtom *segBtn = [IBTCustomButtom buttonWithType:UIButtonTypeCustom];
        segBtn.frame = CGRectMake(width*i, 0, width, _bgView.height);
        segBtn.titleLabel.font = GXF_FIFTEENTEN_SIZE;
        [segBtn setTitleColor:ReportColor forState:UIControlStateNormal];
        segBtn.tag = BeginBtnTag + i;
        [segBtn setTitle:self.segArr[i] forState:UIControlStateNormal];
        [segBtn addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bgView addSubview:segBtn];
        if (i == 0) {
            segBtn.backgroundColor = ReportColor;
            [segBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _currentBtnTag = i+ BeginBtnTag;
        }
        
        if (i < self.segArr.count - 1) {
            [segBtn addRightBorderWithWidth:1 color:ReportColor];
        }
    }
}
- (void)segClick:(UIButton *)btn{
    if (btn.tag != _currentBtnTag) {
        //获取上一个Btn
        IBTCustomButtom *beforeBtn = (IBTCustomButtom *)[_bgView viewWithTag:_currentBtnTag];
        if ([beforeBtn isKindOfClass:[UIButton class]] && beforeBtn) {
            beforeBtn.backgroundColor = RGBA(1, 1, 1, 0);
            [beforeBtn setTitleColor:ReportColor forState:UIControlStateNormal];
        }
        btn.backgroundColor = ReportColor;
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _currentBtnTag = btn.tag;
        if ([self.delegate respondsToSelector:@selector(customSegOneClick:)]) {
            [self.delegate customSegOneClick:btn.titleLabel.text];
        }
    }else{
        if ([self.delegate respondsToSelector:@selector(customSegTwoClick:)]) {
            [self.delegate customSegTwoClick:btn.titleLabel.text];
        }
    }
}
@end
