//
//  XVPasswordViewController.m
//  fastservice
//
//  Created by xuning on 2/4/24.
//  Copyright © 2024 FastService. All rights reserved.
//

#import "XVPasswordViewController.h"
#import "XVInputFieldView.h"
#import "XVWebViewController.h"

@interface XVPasswordViewController ()

@property (nonatomic, strong) UILabel *titleLabel;

// 手机号
@property (nonatomic, strong) XVInputFieldView *phoneView;

@property (nonatomic,copy) NSString *phone;

// 验证码
@property (nonatomic, strong) XVInputFieldView *smsCodeView;
// 图片验证码
@property (nonatomic, strong) XVInputFieldView *imgCodeView;

@property (nonatomic,copy) NSString *imgCode;
// 密码
@property (nonatomic, strong) XVInputFieldView *passwordView;

@property (nonatomic, copy) NSString *uuid; //
@property (nonatomic, strong) YYLabel *protocolLabel;

@property (nonatomic,strong ) NSTimer *timer;



@property (nonatomic, strong) UIButton *sureButton;


@end

@implementation XVPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    [self loadPicVerfData];
    
    [self updateDeviceToken];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
    //ctrl ＋ i 格式化
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:IMG(@"iconPark-left 1 Copy 1")];

}
- (void)back {
    [self dismissViewControllerAnimated:YES completion:^{
        [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    }];

}


- (void)setupUI {
    
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self.view).mas_offset(30);
    }];
    
    
    [self.view addSubview:self.phoneView];
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).mas_offset(29);
        make.left.mas_equalTo(self.view).mas_offset(30);
        make.right.mas_equalTo(self.view).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];
    [self.view addSubview:self.imgCodeView];
    [self.imgCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.phoneView.mas_bottom).mas_offset(31);
        make.left.mas_equalTo(self.view).mas_offset(30);
        make.right.mas_equalTo(self.view).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];

    [self.view addSubview:self.smsCodeView];
    [self.smsCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.imgCodeView.mas_bottom).mas_offset(31);
        make.left.mas_equalTo(self.view).mas_offset(30);
        make.right.mas_equalTo(self.view).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];

    
    [self.view addSubview:self.passwordView];
    [self.passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.smsCodeView.mas_bottom).mas_offset(31);
        make.left.mas_equalTo(self.view).mas_offset(30);
        make.right.mas_equalTo(self.view).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];
    
    
    [self.view addSubview:self.sureButton];
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).mas_offset(66);
        make.right.mas_equalTo(self.view).mas_offset(-66);
        make.height.mas_equalTo(44);
        make.top.mas_equalTo(self.passwordView.mas_bottom).mas_offset(64);
    }];
    kViewBorderRadius(self.sureButton, 10, 0, [UIColor clearColor]);

    
}
- (void)loadPicVerfData{
    
    self.uuid = [AppTools kfwUUID];
    
    NSString *urlStr = S(@"%@%@?uu_id=%@",[AFNetworkingClient baseURLString],SS_SMS_PIC_CODE,self.uuid);
    [self.imgCodeView.picCodeButton sd_setImageWithURL:URL(urlStr) forState:UIControlStateNormal placeholderImage:[UIImage new] options:SDWebImageRefreshCached];
}
//更新上传DeviceToken
- (void)updateDeviceToken{
    [[AFNetworkingClient sharedClient] runPost:SS_SMS_CODEW parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    } failure:^(NSURLSessionDataTask *task, NSError *error){
    }];
}

// 获取验证码逻辑
- (void)loadVerifycode:(int)voice{
    
    if (StringIsNullOrEmpty(self.phone)) {
        [MBProgressHUD showMessage:@"请填写手机号"];
        return;
    }
    
    if (![AppTools isValidMobeilTelWithString:self.phone]) {
        return;
    }
    
    
    if (StringIsNullOrEmpty(self.imgCode)) {
        [MBProgressHUD showMessage:@"请输入图片验证码"];
        return;
    }
    
    [self seconderyValidate:nil voice:voice];
}

//二次验证 发送验证码
- (void)seconderyValidate:(NSDictionary *)result voice:(int)voice{
    NSMutableDictionary *pDic = [NSMutableDictionary dictionaryWithDictionary:result];
    [pDic setAnyObject:self.phone forKey:@"mobile"];
    [pDic setObject:@(1) forKey:@"type"]; //0 注册或者登陆  1 忘记密码
    [pDic setObject:@(voice) forKey:@"voice"];
    [AppTools ccodeBase64Encode:pDic];
    [pDic setAnyObject:self.uuid forKey:@"uu_id"];
    [pDic setAnyObject:self.imgCode forKey:@"imageCode"];
    showIndicator(YES, @"获取中", nil);
    IMP_BLOCK_SELF(XVPasswordViewController);
    [[AFNetworkingClient sharedClient] runPost:SS_SMS_PIC_CODE parameters:pDic success:^(NSURLSessionDataTask *task, id responseObject) {
        if (StringNotNullAndEmpty([responseObject objectForKey:@"respcd"]) &&[[responseObject objectForKey:@"respcd"] isEqualToString:@"0000"]) {
            
            block_self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:block_self selector:@selector(verCodeAciton) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:block_self.timer forMode:NSRunLoopCommonModes];
            [block_self.timer fire];
            [MBProgressHUD showMessage:@"请查收"];
        }else{
            [MBProgressHUD showMessage:[responseObject objectForKey:@"resperr"]];
        }
        showIndicator(NO, nil, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        showAlertMessage(@"获取异常!");
        showIndicator(NO, nil, nil);
    }];
}

//六十秒倒计时
- (void)verCodeAciton{
    static int a = 60;
    self.smsCodeView.smsCodeButton.enabled = NO;
    [self.smsCodeView.smsCodeButton setTitle:S(@"%ds",a) forState:UIControlStateNormal];
    
    //语音标签
    self.smsCodeView.voiceLabel.hidden = NO;
    self.smsCodeView.voiceLabel.text = S(@"收不到验证码？%d秒后来个语音验证码吧",a);
    
    a -= 1;
    if (a == -1) {
        [self.smsCodeView.smsCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.smsCodeView.smsCodeButton.enabled = YES;
        self.smsCodeView.smsCodeButton.backgroundColor = COLOR_THEMEGRENN;
        a = 60;
        
        self.smsCodeView.voiceLabel.userInteractionEnabled = YES;
        self.smsCodeView.voiceLabel.text = @"收不到验证码？来个语音验证吧";
        self.smsCodeView.voiceLabel.textColor = BLUE_COLOR;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lbVoiceTapClick:)];
        [self.smsCodeView.voiceLabel addGestureRecognizer:tap];
    }
    
}

//语音验证码
- (void)lbVoiceTapClick:(UITapGestureRecognizer *)tap{
    //图形验证
    [self loadVerifycode:1];
}

- (void)registerButtonClick {
    
    NSMutableDictionary * pdic = [[NSMutableDictionary alloc]init];
    
    
    if (StringIsNullOrEmpty(self.phoneView.textField.text)) {
        [MBProgressHUD showMessage:@"请填入手机号"];
        return;
    }
    if (![AppTools isValidMobeilTelWithString:self.phoneView.textField.text]) {
        return;
    }
    if (StringIsNullOrEmpty(self.smsCodeView.textField.text)) {
        [MBProgressHUD showMessage:@"请填入验证码"];
        return;
    }
    
    if (StringIsNullOrEmpty(self.passwordView.textField.text)) {
        [MBProgressHUD showMessage:@"请输入密码"];
        return;
    }

    
    [pdic setAnyObject:self.phoneView.textField.text forKey:@"mobile"];
    [pdic setAnyObject:@"" forKey:@"nickname"];
    [pdic setAnyObject:self.passwordView.textField.text forKey:@"password"];
    [pdic setAnyObject:self.smsCodeView.textField.text forKey:@"pin"];
    
 

    NSLog(@"%@",pdic);
    IMP_BLOCK_SELF(XVPasswordViewController);
    showIndicator(YES, @"提交中", nil);
    showFullView(YES, self);
    NSURLSessionTask * task2 = [[AFNetworkingClient sharedClient] runPost:SS_FORGET_PWD parameters:pdic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([MyNetWork isSuccessServerData:responseObject]) {
            [block_self.navigationController popViewControllerAnimated:YES];
            [block_self back];
            [MBProgressHUD showMessage:@"提交成功"];
        }else{
            [MBProgressHUD showMessage:[responseObject objectForKey:@"resperr"]];
        }
        showIndicator(NO, nil, nil);
        showFullView(NO, block_self);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        showIndicator(NO, nil, nil);
        showFullView(NO, block_self);
    }];
    
}



- (UILabel *)titleLabel {
    if(_titleLabel == nil) {
        _titleLabel = [[UILabel alloc]initWithText:@"找回密码" textColor:F_3D3B4F_COLOR textAlignment:NSTextAlignmentLeft fontSize:24];
    }
    return _titleLabel;
}

//
- (XVInputFieldView *)phoneView {
    if(_phoneView == nil) {
        _phoneView = [[XVInputFieldView alloc]initWithType:InputTypeNumber placeholder:@"请输入手机号"];
        IMP_BLOCK_SELF(XVPasswordViewController)
        _phoneView.textEditingChanged = ^(NSString * _Nonnull obj) {
            block_self.phone = obj;
            if (StringIsNullOrEmpty(obj) || StringIsNullOrEmpty(block_self.imgCode)) {
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:BB_3_COLOR];
                
            }else{
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:COLOR_THEMEGRENN];
            }
        };
    }
    return _phoneView;
}
- (XVInputFieldView *)smsCodeView {
    if(_smsCodeView == nil) {
        _smsCodeView = [[XVInputFieldView alloc]initWithType:InputTypeSmsCode placeholder:@"请输入验证码"];
        IMP_BLOCK_SELF(XVPasswordViewController)
        [_smsCodeView.smsCodeButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            [block_self loadVerifycode:0];
        }];
    }
    return _smsCodeView;
}

- (XVInputFieldView *)imgCodeView {
    if(_imgCodeView == nil) {
        _imgCodeView = [[XVInputFieldView alloc]initWithType:InputTypePicCode placeholder:@"请输入图片验证码"];
        IMP_BLOCK_SELF(XVPasswordViewController)
        [_imgCodeView.picCodeButton addBlockForControlEvents:(UIControlEventTouchUpInside) block:^(id  _Nonnull sender) {
            [block_self loadPicVerfData];
        }];
        
        _imgCodeView.textEditingChanged = ^(NSString * _Nonnull obj) {
            block_self.imgCode = obj;
            if (StringIsNullOrEmpty(obj) || StringIsNullOrEmpty(block_self.phone)) {
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:BB_3_COLOR];
            }else{
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:COLOR_THEMEGRENN];
            }
        };

    }
    return _imgCodeView;
}


- (XVInputFieldView *)passwordView {
    if(_passwordView == nil) {
        _passwordView = [[XVInputFieldView alloc]initWithType:InputTypePassword placeholder:@"请设置登录密码"];
    }
    return _passwordView;
}



- (UIButton *)sureButton {
    if(_sureButton == nil) {
        _sureButton = [[UIButton alloc]initWithTitle:@"确定" fontSize:16 titleColor:[UIColor whiteColor] bgColor:COLOR_THEMEGRENN];
        WS(weakSelf);
        [_sureButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
    
        }];
    }
    return _sureButton;
}

@end
