//
//  SLMySpeedView.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/10.
//

#import "SLMySpeedView.h"
#import "UIButton+TitleAndImageLayout.h"
#import "SLCustomSegment.h"
#import "SLNuisdkPlay.h"

@interface SLMySpeedView()<YMCustomSegmentDelegate>

@property (nonatomic, strong)SLCustomSegment *segment;

@property (nonatomic, strong)SLNuisdkPlay *play;

@property (nonatomic, strong)SLCustomSegment *segment1;

@end

@implementation SLMySpeedView

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self addContentView];
    }
    return self;
}

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

- (void)drawRect:(CGRect)rect {
    [self.speedBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:0];
}

- (void)addContentView {
    [[NSBundle mainBundle] loadNibNamed:@"SLMySpeedView" owner:self options:nil];
    self.contentView.frame = self.bounds;
    [self addSubview:self.contentView];
    self.speedBtn.backgroundColor = [SLBlueColor colorWithAlphaComponent:0.1];
    self.speedBtn.layer.borderColor = [UIColor colorFormString:@"#1677FF"].CGColor;
    self.speedBtn.layer.borderWidth = 1.0f;
    self.speedBtn.layer.cornerRadius = 13.0f;
    
    self.segment = [self creatSegmentViewWith:@[@"简单", @"中等", @"困难"]];
    [self.segment updateWithSpacing:2 topHeight:3];
    self.segment.delegate = nil;
    [self.segmentBgView addSubview:self.segment];
    
    self.segment1 = [self creatSegmentViewWith:@[@"慢", @"中", @"快"]];
//    self.segment1.userInteractionEnabled = NO;
//    self.segment1.delegate = nil;
    [self.segment1 updateWithSpacing:2 topHeight:3];
    [self.segment1BgView addSubview:self.segment1];
    
    WS(weakSelf);
    [self.KVOController observe:[SLGlobalInfo SharedInstance] keyPath:@"roleModel" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
        [weakSelf uploadSpeedView];
    }];
}

- (void)uploadSpeedView {
    SLCustomSegment *segment = self.segment1;
    segment.delegate = nil;
    __block NSString *keyStr = @"";
    NSString *speechRate = [SLGlobalInfo SharedInstance].roleModel.speechRate;
    if (speechRate) {
        [[RoleModel roleSpeedModelDict] enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:speechRate]) {
                keyStr = key;
                *stop = YES;
            }
        }];
        NSInteger idx = [segment.titleArray indexOfObject:keyStr];
        segment.selectIndex = idx;
    }else {
        segment.selectIndex = 1;
    }
    segment.delegate = self;
}


- (IBAction)speedBtnClick:(id)sender {
    __block UIButton *btn = sender;
    btn.selected = !btn.selected;
    if (btn.selected) {
        WS(weakSelf);
        [self.play startTTSWith:SLDefaultPlay roleModel:[SLGlobalInfo SharedInstance].roleModel finshBlock:^{
            weakSelf.speedBtn.selected = !weakSelf.speedBtn.selected;
            [weakSelf setNeedsDisplay];
        }];
    }else {
        [self.play stopNuisdkPlay];
    }
    [self setNeedsDisplay];
}

- (void)customSegmentSelectIndex:(NSInteger)selectIndex title:(NSString *)title {
    [self.play stopNuisdkPlay];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.play startTTSWith:SLDefaultPlay roleModel:[SLGlobalInfo SharedInstance].roleModel finshBlock:^{
            
        }];
    });
    NSString *speechRate = [[RoleModel roleSpeedModelDict] objectForKey:title];
    if ([SLGlobalInfo SharedInstance].loginInfo && speechRate) {
        [[SLHttpCenter SharedInstance] getWithUrl:@"/api/User/UpdateSpeechRate" parameter:@{@"speechRate" : speechRate} success:^(id responseObject) {
            [ZFToast ShowWithMessage:@"保存成功"];
            [SLGlobalInfo SharedInstance].roleModel.speechRate = speechRate;
            if (self.speedBtn.isSelected) {
                [self speedBtnClick:self.speedBtn];
            }
        } failure:^(SPRequestError *error) {
            
        }];
    }
}

- (SLCustomSegment *)creatSegmentViewWith:(NSArray *)titleArray
{
    SLCustomSegment *segment = [[SLCustomSegment alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH - 39, 32 * KScaleW) titleArray:titleArray];
    segment.normalTitleFont = 13;
    segment.selectTitleFont = 13;
    segment.cornerRadius = 16.0f;
    segment.backgroundColor = [[UIColor colorFormString:@"#767680"] colorWithAlphaComponent:0.12];
    segment.tag = 110022;
    segment.normalBackgroundColor = [UIColor clearColor];
    segment.selectBackgroundColor = [UIColor whiteColor];
    segment.titleNormalColor = [UIColor colorFormString:@"#8E8E93"];
    segment.delegate = self;
    segment.titleSelectColor = [UIColor blackColor];
    return segment;
}

- (SLNuisdkPlay *)play {
    if (!_play) {
        _play = [[SLNuisdkPlay alloc] init];
    }
    return _play;
}
@end
