//
//  SLRoleappearanceView.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/23.
//

#import "SLRoleappearanceView.h"

@interface SLRoleappearanceView()

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger selIdx;
@end

static NSInteger SLRoleappearanceColorTag = 160888;

@implementation SLRoleappearanceView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self confignView];
    }
    return self;
}

- (void)confignView {
    
}

- (void)colorBtnClick:(UIButton *)btn {
    if (self.selBlock) {
        self.selBlock(self.selIdx, btn.backgroundColor);
    }
}

- (void)confignWith:(NSInteger)selIdx colors:(NSArray<UIColor *> *)colors {
    self.selIdx = selIdx;
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
        obj = nil;
    }];
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.top.equalTo(self);
        make.width.mas_equalTo(294);
    }];
    [colors enumerateObjectsUsingBlock:^(UIColor * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = SLRoleappearanceColorTag + idx;
        btn.titleLabel.font = [UIFont systemFontOfSize:17];
        btn.layer.cornerRadius = 23.0f;
        btn.backgroundColor = obj;
        [btn addTarget:self action:@selector(colorBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        NSInteger x = idx % 4;
        NSInteger y = idx / 4;
        btn.frame = CGRectMake(12 + x * 75, 15 + y * 56, 46, 46);
        [self.scrollView addSubview:btn];
        if (idx == colors.count - 1) {
            self.scrollView.contentSize = CGSizeMake(294, CGRectGetMaxY(btn.frame) + 15);
        }
    }];
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.bounces = NO;
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

@end
