//
//  lookForPasswordViewController.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/3/18.
//  Copyright © 2016年 Mac Book DQ02. All rights reserved.
//

#import "lookForPasswordViewController.h"
#import "LoginViewController.h"
#import "lookForPWNextVC.h"
#import "AFNetworking.h"
#import "MyMD5.h"

#define kMargin 10 //间距
#define kScreenwidth [UIScreen mainScreen].bounds.size.width
#define kScreenheight [UIScreen mainScreen].bounds.size.height
#define kheight kScreenheight*0.065
#define knavBarHeight self.navigationController.navigationBar.frame.size.height  //获取导航栏的高度

@interface lookForPasswordViewController () <UITextFieldDelegate> {
    //未登录状态下（以下4个字段）
    NSString *type;
    NSString *key;
    NSString *time;
    NSString *sign;
    //获取验证码字段(手机号码)
    UITextField *phoneTF; //输入手机号
    UITextField *inputIdentifyingCode; //输入验证码
    UIButton *getIdentifyingCodeBtn; //获取验证码
    UIButton *nextBtn; //注册按钮
    
    //接收验证码
    NSString *receiveIdentifyingCode;
}

@property (nonatomic, assign) NSInteger second;
@property (nonatomic, assign) NSTimer *timer;

@property (nonatomic, strong) UILabel *identifyingCodeWarningLabel;
@property (nonatomic, strong) UILabel *isRegisteredLabel;

@end

@implementation lookForPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _second = 60;
    
    self.view.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.99];
    //设定导航栏标题
    self.navigationItem.title = @"找回密码";
//    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
//    //设定导航栏的颜色
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
    
    [Manager setNavi:self.navigationController.navigationBar];
    
    
    //用push推过来后，仍然可以重新设定导航栏左边的按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(lookForPasswordBackIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
#pragma mark - UI布局（UITextField包括 输入手机号，输入验证码。UIButton包括 获取验证码，下一步）
    phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    [phoneTF addTarget:self action:@selector(phoneIsClicked) forControlEvents:(UIControlEventEditingDidEnd)];
    phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    phoneTF.delegate = self;
    phoneTF.placeholder = @"请输入手机号";
    phoneTF.backgroundColor = [UIColor whiteColor];
    phoneTF.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:phoneTF];
    
    //添加手机号码输入正误的提示标签
    _identifyingCodeWarningLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(phoneTF.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _identifyingCodeWarningLabel.textAlignment = NSTextAlignmentRight;
    _identifyingCodeWarningLabel.textColor = [UIColor redColor];
    _identifyingCodeWarningLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_identifyingCodeWarningLabel];
    
    //验证码输入文本框
    inputIdentifyingCode = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(phoneTF.frame) + 2*kMargin, ((phoneTF.frame.size.width - kMargin)/3)*2, kheight)];
    inputIdentifyingCode.placeholder= @"验证码";
    inputIdentifyingCode.borderStyle = UITextBorderStyleRoundedRect;
    inputIdentifyingCode.backgroundColor = [UIColor whiteColor];
    inputIdentifyingCode.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:inputIdentifyingCode];
    
    // 验证码输入正误的提示标签
    _codeWarningLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputIdentifyingCode.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _codeWarningLab.textAlignment = NSTextAlignmentRight;
    _codeWarningLab.textColor = [UIColor redColor];
    _codeWarningLab.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_codeWarningLab];
    
    //验证码获取按钮
    getIdentifyingCodeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    getIdentifyingCodeBtn.frame = CGRectMake(CGRectGetMaxX(inputIdentifyingCode.frame) + kMargin, CGRectGetMaxY(phoneTF.frame) + 2*kMargin, (phoneTF.frame.size.width - kMargin)/3, kheight);
    getIdentifyingCodeBtn.backgroundColor = [UIColor whiteColor];
    [getIdentifyingCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getIdentifyingCodeBtn setTitleColor:[UIColor colorWithRed:34.0/255 green:205.0/255 blue:119.0/255 alpha:1] forState:(UIControlStateNormal)];
    [getIdentifyingCodeBtn addTarget:self action:@selector(getIdentifyCodeBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:getIdentifyingCodeBtn];
    
    //下一步按钮
    nextBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    nextBtn.frame = CGRectMake(kMargin, CGRectGetMaxY(inputIdentifyingCode.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight);
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [nextBtn addTarget:self action:@selector(nextBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    nextBtn.backgroundColor = [UIColor blackColor];
    [self.view addSubview:nextBtn];
    _isLegal = NO;
}

#pragma mark - 实时监控phone文本框编辑事件，
- (void)phoneIsClicked {
     self.isClickIdentify = NO;
    _identifyingCodeWarningLabel.text = @"";
    [self identifyPhoneInputField];
    
    
}

#pragma mark 操作验证码之前，先要验证文本框输入内容是否正确
-( BOOL)identifyPhoneInputField
{
    
    if (phoneTF.text.length < 11 || phoneTF.text.length > 11) {
        //给出提示框
        _identifyingCodeWarningLabel.text = @"手机号码不能为空且为11位";
        _isLegal = NO;
        return NO;
    }
    
    //判断号码是否合法
    BOOL isCorrectPhone =[Manager checkTelNumber:phoneTF.text];
    if (isCorrectPhone == NO) {
        _identifyingCodeWarningLabel.text = @"无效手机号码";
         _isLegal = NO;
        return NO;
    }
    
    
    NSDictionary *dicx;
    type = @"Ios";
    key = @".5Xf_01KXd352s177Jx3wxXc074poII";
    time = @"yyyyMMddHHmmss";
    //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
    NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time, type, key];
    sign = [MyMD5 md5:str];
    dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"phone" : phoneTF.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/phoneapi",localRequestUrl];
    
    [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"lookCode = %@", responseObject[@"code"]);
        //4025表示已经注册过  4026表示未注册过   4021表示手机号码异常
        if ([responseObject[@"code"] isEqualToString:@"4025"]) {
            
            _isLegal = YES;
            if (self.isClickIdentify) {
                //表示按了获取验证码按钮，号码已注册，表示可以进行验证码请求
                [self lookIdentifyCodeRequest];
            }
            return;
        }else if ([responseObject[@"code"] isEqualToString:@"4021"])
        {
            _isLegal = NO;
            _identifyingCodeWarningLabel.text = @"该手机号码异常";
            return;
        }else if ([responseObject[@"code"] isEqualToString:@"4026"])
        {
            _isLegal = NO;
            _identifyingCodeWarningLabel.text = @"该手机号码未注册过";
            return;
        }
        
        _isLegal = NO;
        _identifyingCodeWarningLabel.text = @"";
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"不做处理");
    }];
    
    return _isLegal;
}

#pragma mark - 导航栏左边按钮被点击后，触发的方法
- (void)lookForPasswordBackIsClicked {
    
    if (_timer && [_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    
    [self.navigationController pushViewController:loginVC animated:YES];
    
}

#pragma mark - 获取验证码按钮点击后，触发方法。
- (void)getIdentifyCodeBtnIsClicked:(UIButton *)sender {
    self.isClickIdentify = YES;
    _identifyingCodeWarningLabel.text = @"";
    if (_timer && [_timer isValid]) {
        //表示计时器正在运行，不能再点击了
        return;
    }
    
     [self identifyPhoneInputField];
    
}


#pragma mark --找回密码请求
-(void)lookIdentifyCodeRequest
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimerBegins) userInfo:nil repeats:YES];
    NSDictionary *dicx;
    type = @"Ios";
    key = @".5Xf_01KXd352s177Jx3wxXc074poII";
    time = @"yyyyMMddHHmmss";
    //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
    NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time, type, key];
    sign = [MyMD5 md5:str];
    dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"phone" : phoneTF.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/smsapi",localRequestUrl];
    
    
    [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject[@"data"][@"verifycode"]);
        receiveIdentifyingCode = responseObject[@"data"][@"verifycode"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //弹出提示框“获取验证码失败”；
        [FileDownloadTool alert:@"获取验证码失败" view:self.view];
    }];

}


#pragma mark - 点击下一步按钮后，触发的方法
- (void)nextBtnIsClicked:(UIButton *)sender {
    _codeWarningLab.text = @"";
    if (!_isLegal) {
        _identifyingCodeWarningLabel.text = @"手机号码有误";
        return;
    }
    if (_isLegal && ![receiveIdentifyingCode isEqualToString:inputIdentifyingCode.text]) {
        //手机号码输入符合规则，但是验证码和接收到的不一样
        _codeWarningLab.text = @"验证码不匹配";
    }
    
    if (_isLegal && [inputIdentifyingCode.text isEqualToString:@""]) {
        //手机号码输入符合规则，但是验证码和接收到的不一样
        _codeWarningLab.text = @"验证码不能为空";
    }
    
    if (_isLegal && [receiveIdentifyingCode isEqualToString:inputIdentifyingCode.text]) {
        if ( _timer && [_timer isValid]) {
            [_timer invalidate];
            _timer = nil;
        }
        //跳转到下一个页面。
        lookForPWNextVC *nextVC = [[lookForPWNextVC alloc] init];
        nextVC.userName = phoneTF.text;
        [self.navigationController pushViewController:nextVC animated:YES];
    }
   
}

#pragma mark - UITextFieldDelegate Methods
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    return [self validateNumber:string];
    
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0  || phoneTF.text.length >= 11) {
            res = NO;
            break;
        }
        i++;
    }
    
    return res;
}




#pragma mark - 计时器开始工作
- (void)TimerBegins {
    _second --;
    NSLog(@"second%ld", (long)_second);
    [getIdentifyingCodeBtn setTitle:[NSString stringWithFormat:@"%.2ld秒", (long)_second] forState:(UIControlStateNormal)];
    if (_second == 0) {
        [_timer invalidate];
        _timer = nil;
        [getIdentifyingCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        _second = 60;
    }
}

-(void)dealloc
{
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    
}


/////////////////////////////////////////////
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #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
