//
//  SLRoleLabelView.m
//  SLAiELTS
//
//  Created by Gusont on 2023/2/28.
//

#import "SLRoleLabelView.h"
#import "SLCustomSegment.h"
#import "SLNuisdkPlay.h"
#import "SLRoleappearanceView.h"
#import "SLDatePickView.h"
#import "PGDatePickManager.h"
#import "SLPickView.h"
#import "SLImagePickerAndUpload.h"

@interface SLRoleLabelView ()<YMCustomSegmentDelegate, UITextFieldDelegate>

@property (nonatomic, assign) SLRoleModelType roleLabelType;

@property (nonatomic, strong) RoleModel *roleModel;

@property (nonatomic, strong) SLNuisdkPlay *play;

@property (nonatomic, strong) SLImagePickerAndUpload *imageUpload;

@end

@implementation SLRoleLabelView

- (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)addContentView {
    [[NSBundle mainBundle] loadNibNamed:@"SLRoleLabelView" owner:self options:nil];
    self.contentView.frame = self.bounds;
    [self addSubview:self.contentView];
    self.contentView.backgroundColor = UIColor.clearColor;
}

- (void)confignWithRoleType:(SLRoleModelType)roleType :(RoleModel *)roleModel {
    NSArray *arr = @[];
    NSString *titleStr = @" ";
    NSString *subTitleStr = @"  ";
    self.roleLabelType = roleType;
    self.roleModel = roleModel;
    self.nameBgView.hidden = YES;
    switch (roleType) {
        case SLRoleSex:
        {
            arr = @[@[@"男性",@"女性"]];
            titleStr = @"选择你的助教老师的性别";
        }
            break;
        case SLRoleappearance:
        {
            arr = @[@[@"头发",@"皮肤", @"眼睛"]];
            titleStr = @"选择你的助教老师的形象造型";
            SLRoleappearanceView *appearanceView = [self creatRoleappearanceView];
            [appearanceView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self);
                make.left.mas_equalTo(20);
                make.height.mas_equalTo(140);
                make.bottom.equalTo(self.mas_bottom).offset(-76);
            }];
        }
            break;
        case SLRoleLanguage:
        {
            arr = @[@[@"快", @"中", @"慢"], @[@"美音", @"英音"], @[@"女性", @"男性"],];
            titleStr = @"请设置你的AI语音";
            subTitleStr = @"语音聊天将播放此声音";
//            [self confignWithRoleLanguage];
        }
            break;
        case SLRoleName:
        {
            arr = @[];
            [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:SLCustomSegment.class]) {
                    [obj removeFromSuperview];
                    obj = nil;
                }
            }];
            self.nameBgView.hidden = NO;
            titleStr = @"为你的AI助教取名";
            subTitleStr = @"AI助教将使用次名称与你对话";
        }
            break;
        case SLUserInfo:
        {
            arr = @[];
            [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:SLCustomSegment.class]) {
                    [obj removeFromSuperview];
                    obj = nil;
                }
            }];
            self.infoBgView.hidden = NO;
            titleStr = @"请设置你的信息";
            subTitleStr = @"性别选择后无法更改";
            self.subTitleLabel.textColor = SLColor(@"#8E8E93");
            self.camearImageView.hidden = NO;
            WS(weakSelf);
            [self.camearImageView addTapWithBlock:^{
                [weakSelf.imageUpload willShowActionSheet];
            }];
            self.logoImageView.image = ImageName(@"icon_user_head");
            SLCustomSegment *segmentView = [self creatSegmentViewWith:kSCREEN_WIDTH - 32];
            [segmentView removeFromSuperview];
            [self.sexSelBgView addSubview:segmentView];
            [segmentView setTitlesWithArray:@[@"女性", @"男性"]];
            segmentView.selectIndex = 0;
            [segmentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.sexSelBgView);
            }];
            
        }
            break;
        default:
            break;
    }
    self.titleLabel.text = titleStr;
    self.subTitleLabel.text = subTitleStr;
    if (arr.count) {
        [arr enumerateObjectsUsingBlock:^(NSArray *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SLCustomSegment *segmentView = [self creatSegmentViewWith:kSCREEN_WIDTH - 40];
            CGFloat h = (arr.count - idx - 1) * 78;
//            if (roleType == SLRoleLanguage) {
//                h += 128;
//            }
//            [segmentView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.centerX.equalTo(self);
//                make.left.mas_equalTo(20);
//                make.height.mas_equalTo(58);
//                make.bottom.equalTo(self.mas_bottom).offset(-(12 + h));
//            }];
            [segmentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self);
                make.left.mas_equalTo(20);
                make.height.mas_equalTo(58);
                make.top.equalTo(self.logoImageView.mas_bottom).offset((6 + h));
            }];
            [segmentView setTitlesWithArray:obj];
            if (roleType == SLRoleLanguage && idx == 0) {
                segmentView.selectIndex = 1;
            }else {
                segmentView.selectIndex = 0;
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self play];
            });
        }];
    }
}

- (void)confignWithRoleLanguage {
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.backgroundColor = [UIColor colorWithRed:199 / 255.0 green:235 / 255.0 blue:253 / 255.0 alpha:1];
    [cancelBtn setTitle:@"试听语音" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:SLColor(@"#1677FF") forState:UIControlStateNormal];
    cancelBtn.layer.borderColor = [SLBlueColor CGColor];
    cancelBtn.layer.borderWidth = 1.0f;
    cancelBtn.layer.cornerRadius = 24.0f;
    [cancelBtn addTarget:self action:@selector(payBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.left.mas_equalTo(22);
        make.height.mas_equalTo(48);
        make.bottom.mas_equalTo(self.mas_bottom).offset(-12);
    }];
}

- (IBAction)datePickViewBtnClick:(id)sender {
    [self datePickViewSel];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.nickName) {
        self.roleModel.userName = textField.text;
    }
    if (textField == self.nameTextField) {
        self.roleModel.dataName = textField.text;
    }
}

- (void)datePickViewSel {
    SLDatePickerDO *itemDo = [[SLDatePickerDO alloc] init];
    itemDo.format = @"yyyy年MM月dd日";
    itemDo.maxDateString = [NSString getCurrentDayWithFormatter:itemDo.format timeDiff:24 * 3600 * 0];
    SLDatePickView *datePick = [[SLDatePickView alloc] initWithStyle:SLDatePickerYMD pickerData:itemDo];
    WS(weakSelf);
    datePick.resultBlock = ^(NSString * _Nullable str) {
        weakSelf.breaTextField.text = str;
        weakSelf.roleModel.birthday = str;
        [weakSelf endEditing:YES];
    };
    [datePick setTitleLabelText:@"设置出生日期"];
    [datePick show];
}

- (void)payBtnClick {
    if (_play) {
        [_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:self.roleModel finshBlock:^{
                
            }];
        });
    }
}

- (void)customSegmentSelectIndex:(NSInteger)selectIndex title:(nonnull NSString *)title {
    [self endEditing:YES];
    //最好构造模型
    NSDictionary *dict = [RoleModel roleModelDict];
    NSString *value = [dict objectForKey:title];
    switch (self.roleLabelType) {
        case SLRoleSex:
        {
            self.roleModel.dataSex = value;
        }
            break;
        case SLRoleappearance:
        {
            SLRoleappearanceView *view = (SLRoleappearanceView *)[self viewWithTag:222233];
            
            switch (selectIndex) {
                case 0:
                {
                    [view confignWith:selectIndex colors:@[SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor]];
                }
                    break;
                case 1:
                {
                    [view confignWith:selectIndex colors:@[UIColor.redColor,UIColor.redColor,UIColor.redColor,SLBgColor,UIColor.redColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,UIColor.redColor,UIColor.redColor]];
                }
                    break;
                case 2:
                {
                    [view confignWith:selectIndex colors:@[UIColor.blueColor,UIColor.blueColor,SLBgColor,SLBgColor,UIColor.blueColor,SLBgColor,SLBgColor,SLBgColor,SLBgColor,UIColor.blueColor,SLBgColor,UIColor.blueColor,UIColor.blueColor,SLBgColor]];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case SLRoleLanguage:
        {   //XXXXXXXXXX
            if ([title containsString:@"音"]) {
                self.roleModel.language = value;
            }else if ([title containsString:@"性"]) {
                self.roleModel.dataSex = value;
            }else {
                self.roleModel.speechRate = value;
            }
            [self payBtnClick];
        }
            break;
        case SLRoleName:
        {
            
        }
            break;
        case SLUserInfo:
        {
            self.roleModel.sex = value;
        }
            break;
        default:
            break;
    }
}

- (SLCustomSegment *)creatSegmentViewWith:(CGFloat)width
{
    CGFloat sHeight = 58;
    SLCustomSegment *segment = [[SLCustomSegment alloc] initWithFrame:CGRectMake(0, 0, width, sHeight) titleArray:@[@"男",@"女"]];
    segment.normalTitleFont = 17;
    segment.selectTitleFont = 17;
    segment.cornerRadius = 29.0f;
    segment.backgroundColor = SLColor(@"#F5F8F7");
    segment.tag = 110022;
    segment.delegate = self;
    segment.normalBackgroundColor = [UIColor clearColor];
    segment.selectBackgroundColor = SLColor(@"#1677FF");
    segment.titleNormalColor = SLColor(@"#8E8E93");
    segment.titleSelectColor = [UIColor whiteColor];
    segment.borderWidth = 0.0f;
    [self addSubview:segment];
    return segment;
}

- (SLRoleappearanceView *)creatRoleappearanceView {
    SLRoleappearanceView *view = [[SLRoleappearanceView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [SLBlackColor colorWithAlphaComponent:0.3];
    view.clipsToBounds = YES;
    view.layer.cornerRadius = 20.0f;
    view.tag = 222233;
    [self addSubview:view];
    view.selBlock = ^(NSInteger selIdx, UIColor *color) {
        switch (selIdx) {
            case 0:
            {
                
            }
                break;
            case 2:
            {
                
            }
                break;
            case 3:
            {
                
            }
                break;
                
            default:
                break;
        }
    };
    return view;
}

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

- (SLImagePickerAndUpload *)imageUpload {
    if (!_imageUpload) {
        _imageUpload = [[SLImagePickerAndUpload alloc] init];
        WS(weakSelf);
        _imageUpload.uploadBlock = ^(NSString *imageUrl) {
            weakSelf.roleModel.userHead = imageUrl;
            NSString *headImgUrl = [NSString stringWithFormat:@"%@%@",[SLHttpCenter SharedInstance].serverUrl, imageUrl];
            [weakSelf.logoImageView sd_setImageWithURL:[NSURL URLWithString:headImgUrl]];
            [weakSelf.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(100);
            }];
            weakSelf.logoImageView.layer.cornerRadius = 50;
        };
    }
    return _imageUpload;
}


@end
