//
//  SLPickView.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/14.
//

#import "SLPickView.h"
#import "PGPickerView.h"

@interface SLPickView()<PGPickerViewDelegate, PGPickerViewDataSource>

@property(nonatomic, strong) UIView *toolView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIView *titleBgView;

@property(nonatomic, strong) UIButton *cancelBtn;

@property(nonatomic, strong) UIButton *sureBtn;

@property(nonatomic, strong) PGPickerView *datePicker;

@property (nonatomic, strong) NSMutableArray<NSArray *> *dataArr;

@property (nonatomic, strong) NSMutableArray *selComponent;

@property (nonatomic, strong) NSString *selResult;
@end

@implementation SLPickView

- (nonnull id)initWithPickerData:(nonnull NSMutableArray<NSArray *> *)dataArr
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        self.dataArr = dataArr;
        [self confignUI];
        [self.datePicker selectRow:0 inComponent:0 animated:YES];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenDatePickView)];
        [self addGestureRecognizer:tap];
    }
    return self;
}


- (void)setTitleLabelText:(NSString *)text {
    self.titleLabel.text = text;
}

- (void)setComponentTitles:(NSArray *)titles {
    [self.titleBgView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
        obj = nil;
    }];
    if (titles.count > 1) {
        self.selComponent = [NSMutableArray arrayWithArray:titles];
        [self.titleBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(34);
        }];
        self.titleBgView.backgroundColor = SLColor(@"#F2F3F7");
        NSMutableArray *views = [NSMutableArray array];
        [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
            label.text = obj;
            label.backgroundColor = [UIColor whiteColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont systemFontOfSize:15];
            [self.titleBgView addSubview:label];
            [views addObject:label];
        }];
        [views mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
        [views mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleBgView);
            make.bottom.equalTo(self.titleBgView.mas_bottom).offset(-1);
        }];
        SLTargetModel *tarModel = [SLGlobalInfo SharedInstance].targetModel;
        [self.dataArr enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            __block NSInteger i = 0;
            NSString *score = @"";
            if (tarModel && self.dataArr.count == [tarModel getTargetScoreArr].count) {
                score = [tarModel getTargetScoreArr][idx];
            }
            [obj enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isEqualToString:score]) {
                    i = idx;
                    *stop = YES;
                }
            }];
            [self.datePicker selectRow:i ?: obj.count * 0.55 inComponent:idx animated:YES];
        }];
        
    }
}

#pragma PGPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(PGPickerView *)pickerView {
    return self.dataArr.count;
}

- (NSInteger)pickerView:(PGPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [[self.dataArr objectAtIndex:component] count];
}
#pragma  PGPickerViewDelegate
- (nullable NSString *)pickerView:(PGPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSArray *arr = [self.dataArr objectAtIndex:component];
    NSString *str = [arr objectAtIndex:row];
    return str;
}

- (void)pickerView:(PGPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSArray *arr = [self.dataArr objectAtIndex:component];
    NSString *str = [arr objectAtIndex:row];
    self.selResult = str;
    if (self.selComponent.count) {
        [self.selComponent replaceObjectAtIndex:component withObject:str];
        __block CGFloat total = 0;
        [self.selComponent enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            total += [obj floatValue];
        }];
        self.selResult = [NSString stringWithFormat:@"%.1f", total / self.selComponent.count];
        self.titleLabel.text = [NSString stringWithFormat:@"目标分数：%.1f", total / self.selComponent.count];
    }
}

- (CGFloat)pickerView:(PGPickerView *)pickerView upLineHeightForComponent:(NSInteger)component
{
    return 1.0f;
}

- (CGFloat)pickerView:(PGPickerView *)pickerView downLineHeightForComponent:(NSInteger)component
{
    return 1.0f;
}

- (void)cancelBtnClick
{
    [self hiddenDatePickView];
}

- (void)sureBtnClick
{
    if (self.resultBlock) {
        self.resultBlock(self.selResult, self.selComponent);
    }
    [self removeFromSuperview];
}

- (void)hiddenDatePickView
{
    [self removeFromSuperview];
}

- (void)show
{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
}

- (void)drawRect:(CGRect)rect {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.toolView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(8 , 8)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.toolView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.toolView.layer.mask = maskLayer;
}

- (void)confignUI
{
    
    [self.datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.mas_bottom).offset(-kSafeAreaBottom);
        make.height.equalTo(@(216));
    }];
    
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.titleBgView.mas_top).offset(0);
        make.height.equalTo(@(44));
    }];
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.toolView);
        make.left.equalTo(self.toolView.mas_left).offset(6);
        make.width.equalTo(@(63));
    }];
    
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.toolView);
        make.right.equalTo(self.toolView.mas_right).offset(-6);
        make.width.equalTo(@(63));
    }];
    
    [self.titleBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.datePicker.mas_top).offset(0);
        make.height.mas_equalTo(0);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.toolView);
    }];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectZero];
    lineView.backgroundColor = SLColor(@"#F2F3F7");
    [self.toolView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.toolView);
        make.bottom.equalTo(self.toolView.mas_bottom).offset(-1);
        make.height.mas_equalTo(1);
    }];
}

- (UIView *)toolView
{
    if (!_toolView) {
        _toolView = [[UIView alloc] initWithFrame:CGRectZero];
        _toolView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_toolView];
    }
    return _toolView;
}

- (UIButton *)cancelBtn
{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.toolView addSubview:_cancelBtn];
    }
    return _cancelBtn;
}

- (UIButton *)sureBtn
{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_sureBtn setTitle:@"保存" forState:UIControlStateNormal];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.toolView addSubview:_sureBtn];
    }
    return _sureBtn;
}

- (PGPickerView *)datePicker {
    if (!_datePicker) {
        _datePicker = [[PGPickerView alloc] initWithFrame:CGRectZero];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.textFontOfOtherRow = [UIFont systemFontOfSize:16];
        _datePicker.textFontOfSelectedRow = [UIFont systemFontOfSize:16];
        _datePicker.delegate = self;
        _datePicker.dataSource = self;
        _datePicker.lineBackgroundColor = SLBgColor;
        [self addSubview:_datePicker];
    }
    return _datePicker;
}

- (UIView *)titleBgView {
    if (!_titleBgView) {
        _titleBgView = [[UIView alloc] initWithFrame:CGRectZero];
        _titleBgView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_titleBgView];
    }
    return _titleBgView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [self.toolView addSubview:_titleLabel];
    }
    return _titleLabel;
}
@end
