//
//  KBSearchSectionHeader.m
//  keyBoard
//

#import "KBSearchSectionHeader.h"
#import "KBAlert.h"

@interface KBSearchSectionHeader ()
@property (nonatomic, strong, readwrite) UILabel *titleLabel;
@property (nonatomic, strong, readwrite) UIButton *trashButton;
@end

@implementation KBSearchSectionHeader

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
        _confirmColor = [UIColor redColor];
        _cancelColor = [UIColor blackColor];
    }
    return self;
}

- (void)setupUI {
    self.backgroundColor = [UIColor whiteColor];

    [self addSubview:self.titleLabel];
    [self addSubview:self.trashButton];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(16);
        make.centerY.equalTo(self);
        make.right.lessThanOrEqualTo(self.trashButton.mas_left).offset(-8);
    }];

    [self.trashButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.right.equalTo(self).offset(-16);
        make.width.height.mas_equalTo(24);
    }];
}

- (void)tapTrash {
    // 弹出确认框：是否删除所有历史记录
    __weak typeof(self) weakSelf = self;
    [KBAlert confirmTitle:@"清空历史"
                  message:@"是否删除所有历史记录？"
                       ok:@"确定"
                   cancel:@"取消"
                  okColor:weakSelf.confirmColor
              cancelColor:weakSelf.cancelColor
                completion:^(BOOL ok) {
                    if (ok && weakSelf.onTapTrash) {
                        weakSelf.onTapTrash();
                    }
                }];
}

- (void)configWithTitle:(NSString *)title showTrash:(BOOL)showTrash {
    self.titleLabel.text = title;
    self.trashButton.hidden = !showTrash;
}

#pragma mark - Lazy

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
        _titleLabel.textColor = [UIColor colorWithHex:0x1B1F1A];
    }
    return _titleLabel;
}

- (UIButton *)trashButton {
    if (!_trashButton) {
        _trashButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_trashButton setImage:[UIImage systemImageNamed:@"trash"] forState:UIControlStateNormal];
        _trashButton.tintColor = [UIColor colorWithHex:0x9A9A9A];
        [_trashButton addTarget:self action:@selector(tapTrash) forControlEvents:UIControlEventTouchUpInside];
    }
    return _trashButton;
}

@end
