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

#import "SLModifyNicknameVc.h"
#import "SLChangeMobileVc.h"

@interface SLModifyNicknameVc ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nickNameTextField;
@property (weak, nonatomic) IBOutlet UIButton *clearBtn;

@end

@implementation SLModifyNicknameVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = NSLocalizedString(@"修改昵称", nil);
    YMBarButtonItem *rightBarItem = [[YMBarButtonItem alloc] initWithTitle:NSLocalizedString(@"保存  ", nil) target:self action:@selector(preserveBtnClick)];
    rightBarItem.titleInsets = UIEdgeInsetsMake(0, 0, 0, 20);
    self.navigationBar.rightBarButtonItem = rightBarItem;
    self.nickNameTextField.delegate = self;
    self.clearBtn.hidden = YES;
    if (self.isAiNickName) {
        self.nickLabel.text = NSLocalizedString(@"AI昵称", nil);
    }
}

- (IBAction)clearBtnClick:(id)sender {
    self.nickNameTextField.text = @"";
    self.clearBtn.hidden = YES;
}

- (void)preserveBtnClick {
    [self.view endEditing:YES];
    if (!self.nickNameTextField.text.length) {
        [ZFToast ShowWithMessage:@"请输入昵称"];
        return;
    }
    NSString *url = self.isAiNickName ? @"/api/User/UpdateAIName" : @"/api/User/UpdateName";
    NSDictionary *params = self.isAiNickName ? @{@"aiName" : self.nickNameTextField.text} : @{@"name" : self.nickNameTextField.text};
    [[SLHttpCenter SharedInstance] getWithUrl:url parameter:params success:^(id responseObject) {
        [ZFToast ShowWithMessage:@"保存成功"];
        if (self.isAiNickName) {
            RoleModel *newRoleModel = [SLGlobalInfo SharedInstance].roleModel;
            newRoleModel.aiName = self.nickNameTextField.text;
            [SLGlobalInfo SharedInstance].roleModel = newRoleModel;
        }else {
            SLLoginInfo *newLoginModel = [SLGlobalInfo SharedInstance].loginInfo;
            newLoginModel.user.userName = self.nickNameTextField.text;
            [SLGlobalInfo SharedInstance].loginInfo = newLoginModel;
        }
    } failure:^(SPRequestError *error) {
        
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    self.clearBtn.hidden = !toBeString.length;
    if (toBeString.length > 12) {
        return NO;
    }
    return YES;
}


@end
