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

#import "SLChangeMobileVc.h"
#import "SLVerifiButton.h"

@interface SLChangeMobileVc ()
@property (weak, nonatomic) IBOutlet UITextField *mobileTextField;

@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet SLVerifiButton *codeBtn;

@end

@implementation SLChangeMobileVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"手机号";
    //  获取到clearbutton 可以获取样式上
    UIButton *btn = [self.mobileTextField valueForKey:@"_clearButton"];
    [btn setImage:ImageName(@"icon_clear_circle") forState:UIControlStateNormal];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (IBAction)codeBtnClick:(id)sender {
    [self.view endEditing:YES];
    NSString *phoneStr = self.mobileTextField.text;
    if (!phoneStr.length) {
        [ZFToast ShowWithMessage:@"请输入手机号"];
        return;
    }
    if (phoneStr.length != 11) {
        [ZFToast ShowWithMessage:@"手机号输入有误"];
        return;
    }
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[SLHttpCenter SharedInstance] getWithUrl:@"/api/Token/GetPhoneValidateCode" parameter:@{@"phone" : phoneStr} success:^(id responseObject) {
        SLVerifiButton *btn = (SLVerifiButton *)sender;
        [btn startTiming];
        [self.codeTextField becomeFirstResponder];
        [hub hideAnimated:YES];
    } failure:^(SPRequestError *error) {
        [hub hideAnimated:YES];
    }];
}

- (IBAction)submitBtnClick:(id)sender {
    [self.view endEditing:YES];
    NSString *phoneStr = self.mobileTextField.text;
    NSString *codeStr = self.codeTextField.text;
    if (!phoneStr.length) {
        [ZFToast ShowWithMessage:@"请输入手机号"];
        return;
    }
    if (phoneStr.length != 11) {
        [ZFToast ShowWithMessage:@"手机号输入有误"];
        return;
    }
    if (!codeStr.length) {
        [ZFToast ShowWithMessage:@"请输入验证码"];
        return;
    }
    [[SLHttpCenter SharedInstance] postWithUrl:@"/api/Token/UpdateUserPhone" parameter:@{@"phone" : phoneStr, @"code" : codeStr} success:^(id responseObject) {
        [ZFToast ShowWithMessage:@"修改成功"];
        NSDictionary *dataDict = [responseObject objectForKey:@"data"];
        SLLoginInfo *loginModel = [SLLoginInfo mj_objectWithKeyValues:dataDict];
        SLLoginInfo *newLoginModel = [SLGlobalInfo SharedInstance].loginInfo;
        newLoginModel.user.phone = loginModel.user.phone;
        newLoginModel.token = loginModel.token;
        [SLGlobalInfo SharedInstance].loginInfo = newLoginModel;
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(SPRequestError *error) {
        
    }];
}

@end
