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

#import "lookForPWNextVC.h"
#import "lookForPasswordViewController.h"
#import "LoginViewController.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.055
#define knavBarHeight self.navigationController.navigationBar.frame.size.height  //获取导航栏的高度
#define isBtnWH 30 //是否同意协议按钮的宽度 高度。

@interface lookForPWNextVC () {
    //未登录状态下（以下4个字段）
    NSString *type;
    NSString *key;
    NSString *time;
    NSString *sign;
    //找回密码字段
    NSString *login_type;
    UITextField *inputNewPWTF; //输入密码
    UITextField *confirmNewPWTF; //确认密码
    UIButton *sureBtn; //注册按钮
}

@property (nonatomic, strong) UILabel *lenghtWarningLabel;
@property (nonatomic, strong) UILabel *isSameWarningLabel;

@end

@implementation lookForPWNextVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.99];
     self.navigationItem.title = @"找回密码";
    
//    //改变导航栏的渲染颜色
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
//    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
    
    
    [Manager setNavi:self.navigationController.navigationBar];
    
    
    //用push推过来后，仍然可以重新设定导航栏左边的按钮 backIsClicked
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(backIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
#pragma - UI布局（包括UITextField， 输入新密码，确认新密码，UIButton，确定按钮）
    inputNewPWTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    [inputNewPWTF addTarget:self action:@selector(lengthIsLegal) forControlEvents:(UIControlEventEditingDidEnd)];
    inputNewPWTF.placeholder = @"输入新密码";
    inputNewPWTF.secureTextEntry = YES;
    inputNewPWTF.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputNewPWTF];
    
    confirmNewPWTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputNewPWTF.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    confirmNewPWTF.placeholder = @"确认新密码";
    confirmNewPWTF.secureTextEntry = YES;
    confirmNewPWTF.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:confirmNewPWTF];

    sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    sureBtn.frame = CGRectMake(kMargin, CGRectGetMaxY(confirmNewPWTF.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sureBtn addTarget:self action:@selector(sureBtnIsClicked:) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.backgroundColor = [UIColor blackColor];
    [self.view addSubview:sureBtn];
    
}

#pragma mark - 判断密码的长度是否在6-16之间
- (void)lengthIsLegal {
    [_lenghtWarningLabel removeFromSuperview];
    if (inputNewPWTF.text.length < 6 || inputNewPWTF.text.length > 16) {
        [_isSameWarningLabel removeFromSuperview];
        _lenghtWarningLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputNewPWTF.frame), kScreenwidth - 2 *kMargin, 2 * kMargin)];
        _lenghtWarningLabel.text = @"密码的长度为6到16个字符";
        _lenghtWarningLabel.textAlignment = NSTextAlignmentRight;
        _lenghtWarningLabel.textColor = [UIColor redColor];
        _lenghtWarningLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:_lenghtWarningLabel];
    }
    
}

#pragma mark - 导航栏左边按钮被点击后，触发的方法
- (void)backIsClicked {
    lookForPasswordViewController *lookForPWVC = [[lookForPasswordViewController alloc] init];
    [self.navigationController pushViewController:lookForPWVC animated:YES];
}

#pragma mark - 点击确定按钮，跳转到登录页面
- (void)sureBtnIsClicked:(UIButton *)sender {
    [_isSameWarningLabel removeFromSuperview];
    if (![inputNewPWTF.text isEqualToString:confirmNewPWTF.text]) {
        [_lenghtWarningLabel removeFromSuperview];
        _isSameWarningLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(confirmNewPWTF.frame), kScreenwidth - 2 *kMargin, 2 * kMargin)];
        _isSameWarningLabel.text = @"两次密码输入不一致，请重新输入";
        _isSameWarningLabel.textAlignment = NSTextAlignmentRight;
        _isSameWarningLabel.textColor = [UIColor redColor];
        _isSameWarningLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:_isSameWarningLabel];
        
    } else if (inputNewPWTF.text.length == 0 || confirmNewPWTF.text.length == 0) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"修改密码失败！" message:@"请确认密码输入正确！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertVc addAction:action];
        [self presentViewController:alertVc animated:YES completion:nil];
        
    } else {
        
        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];
        login_type = @"1";
        dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"login_type" : login_type, @"name" : self.userName, @"pwds" : inputNewPWTF.text};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
         NSString *postStr = [NSString stringWithFormat:@"%@/terminal/forgotpwds",localRequestUrl];
        [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
             if ([responseObject[@"status"] isEqualToString:@"9002"]) {
                 LoginViewController *loginVC = [[LoginViewController alloc] init];
                 [self.navigationController pushViewController:loginVC animated:YES];
             }
           
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //弹出提示框“修改密码失败”；
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"修改密码失败！" message:@"请重试！" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertVc addAction:action];
            [self presentViewController:alertVc animated:YES completion: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
