//
//  FFPasswordViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/7/1.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "FFPasswordViewController.h"
#import "Constants.h"
#import "Tools.h"
#import "RandomCustomKeyborad.h"

#define TIMECOUNT 60
@interface FFPasswordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *tf_password;
@property (weak, nonatomic) IBOutlet UITextField *tf_password2;
@property (weak, nonatomic) IBOutlet UITextField *tf_phone;
@property (weak, nonatomic) IBOutlet UITextField *tf_code;
@property (weak, nonatomic) IBOutlet UIButton *btn_resetPassword;




@end

@implementation FFPasswordViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor],
                                                                      NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:17]}];
    
    _tf_password.inputView =[[RandomCustomKeyborad alloc] initWithInputView:_tf_password];
    _tf_password2.inputView =[[RandomCustomKeyborad alloc] initWithInputView:_tf_password2];
    
    [_tf_password addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_tf_password2 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_tf_phone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_tf_code addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

#pragma mark - UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField.inputView isKindOfClass:[RandomCustomKeyborad class]]) {
        [((RandomCustomKeyborad *)textField.inputView) createAndShowRandomNumberPadKeyboardWithSwitchButtonStatus:YES];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - event reponse
- (void)back
{
    NSLog(@"返回了");
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)getVerificationCode:(UIButton *)sender {
    
    if (self.tf_password.text.length < 6 || self.tf_password.text.length > 18) {
        [SVProgressHUD showErrorWithStatus:@"密码不能少于6位或大于18位"];
        return;
    }
    
    if (![self.tf_password.text isEqualToString:self.tf_password2.text]) {
        [SVProgressHUD showErrorWithStatus:@"两次输入的密码必须一致"];
        return;
    }
    
    if (![Tools isMobileNumber:self.tf_phone.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入有效的手机号"];
        return;
    }
    
    
    
    [logNetModel getLogMessage1:nil andTelephone:self.tf_phone.text andTag:1002 completionHandle:^(lodModel *model, NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"网络状态差"];
            return ;
        }
        if([model.code isEqualToString:@"0"]){
            __block NSInteger second = TIMECOUNT;
            //(1)
            dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            //(2)
            dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
            //(3)
            dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
            //(4)
            dispatch_source_set_event_handler(timer, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (second == 0) {
                        sender.userInteractionEnabled = YES;
                        [sender setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                        [sender setTitleColor:RGBCOLOR(23, 123, 206) forState:UIControlStateNormal];
                        second = TIMECOUNT;
                        //(6)
                        dispatch_cancel(timer);
                    } else {
                        sender.userInteractionEnabled = NO;
                        [sender setTitle:[NSString stringWithFormat:@"%ld秒后重新获取",(long)second] forState:UIControlStateNormal];
                        [sender setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                        second--;
                    }
                });
            });
            //(5)
            dispatch_resume(timer);
        }else{
            codeSelected *code = [codeSelected MustTakeReturn:[model.code intValue]];
            [code returnCodeMethod];
        }
    }];
}
- (IBAction)resetPasswordClick:(UIButton *)sender {
    
    if (self.tf_password.text.length < 6 || self.tf_password.text.length > 18) {
        [SVProgressHUD showErrorWithStatus:@"密码不能少于6位或大于18位"];
        return;
    }
    
    if (![self.tf_password.text isEqualToString:self.tf_password2.text]) {
        [SVProgressHUD showErrorWithStatus:@"两次输入的密码必须一致"];
        return;
    }
    
    if (![Tools isMobileNumber:self.tf_phone.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入有效的手机号"];
        return;
    }
    
    if (self.tf_code.text.length != 4) {
        [SVProgressHUD showErrorWithStatus:@"请输入有效的验证码"];
        return;
    }
    
    if (![Tools detectionIsPasswordQualified:_tf_password.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入8-12位字母和数字组合的密码"];
        return;
    }
    
    NSString *path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/resetPassword"];
    
    [SVProgressHUD show];
    [logNetModel getLogMessage2:path andTelephone:_tf_phone.text andValidate:_tf_code.text andCusPassword:_tf_password2.text completionHandle:^(lodModel *model, NSError *error) {
        NSLog(@"%@",model.code);
        [SVProgressHUD dismiss];
        if ([model.code isEqualToString:@"0"] ) {
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstlog"];
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            codeSelected *code = [codeSelected MustTakeReturn:[model.code intValue]];
            [code returnCodeMethod];
        }
    }];
}

- (void)textFieldDidChange:(UITextField *)textField{
    
    if ([textField isEqual:_tf_phone]) {
        if (textField.text.length >=11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }else if ([textField isEqual:_tf_code]){
        if (textField.text.length >=4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }else if ([textField isEqual:_tf_password]){
        if (textField.text.length >=18) {
            [SVProgressHUD showErrorWithStatus:@"只能输6到18位密码"];
            textField.text = [textField.text substringToIndex:18];
        }
    }else if ([textField isEqual:_tf_password2]){
        if (textField.text.length >=18) {
            [SVProgressHUD showErrorWithStatus:@"只能输6到18位密码"];
            textField.text = [textField.text substringToIndex:18];
        }
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
