//
//  RDSLoginPwdCodeVC.m
//  SmartLightForBigFish
//
//  Created by coderYK on 2017/11/17.
//  Copyright © 2017年 RD. All rights reserved.
//

#import "RDSLoginPwdCodeVC.h"
#import "RDSLoginVerifyCodeVC.h"
#import "RDSResetPwdVC.h"
#import "RDSRootControl.h"
#import "YJJTextField.h"
#import "UIView+RDSClip.h"
#import "NSString+Hash.h"// md5
#import "NSString+verify.h"
#import "RDSSetPwdVC.h"
#import "RDSResetPwdVC.h"

#import <AuthenticationServices/AuthenticationServices.h>

@interface RDSLoginPwdCodeVC ()<UITextFieldDelegate,ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>


@property (weak, nonatomic) IBOutlet UILabel *welcomeLab;
@property (weak, nonatomic) IBOutlet UIButton *logoBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *resetPwdBtn;
@property (weak, nonatomic) IBOutlet UITextField *accountTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;

@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *accountView;
@property (weak, nonatomic) IBOutlet UIView *pwdView;

@property (nonatomic, assign) int pwdClickCount;
@end

@implementation RDSLoginPwdCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.fd_prefersNavigationBarHidden = YES;
    
    // 设置导航栏字体颜色 从这里跳转的VC
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:RDSThemeColor,
    NSFontAttributeName:[UIFont systemFontOfSize:17]}];
    
    [self p_initUI];
    
    [self p_addObserver];
    
    // 这是rootControl 自动登录时会先进入这个页面，所有先隐藏
    if(!self.isPushVc){
        self.view.alpha = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.view.alpha = 1;
        });
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self p_textFill];
    _agreeBtn.selected = NO;
    _pwdClickCount = 0;
}


- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    _bottomView.layer.cornerRadius = SCREEN_WIDTH*40;
    _accountView.layer.cornerRadius = _accountView.rds_height/2;
    _pwdView.layer.cornerRadius = _pwdView.rds_height/2;
    _loginBtn.layer.cornerRadius = _loginBtn.rds_height/2;
//    _loginBtn.layer.masksToBounds = YES;
    
//    [_loginBtn rds_addShadowAndCornerRadius:_loginBtn.rds_height/2 shadowOpacity:0.5f shadowRadius:2 shadowColor:RDSThemeColor];
}

#pragma mark - Action

- (IBAction)p_onPwdBtnClick:(UIButton *)sender {
    
    _pwdClickCount ++;
    
    if(_pwdClickCount == 10){
    
        TheDataManager.isTest = !TheDataManager.isTest;
        
        
        NSString *msg;
        if(TheDataManager.isTest){
            msg = @"切换开发环境";
        }else{
            msg = @"切换生产环境";
        }
        [RDSHudShower showBottomToast:msg];
        DDLog(@"%@", msg);
        
        _pwdClickCount = 0;
    }
}

// 阅读同意
- (IBAction)p_onAgreeBtnClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
}

// 跳转验证码登录
- (IBAction)p_onVerifyCodeLogin {
        
    if(_isPushVc){
        [self popViewControllerAnimated:YES];
    }else{
        RDSLoginVerifyCodeVC *vc = [[RDSLoginVerifyCodeVC alloc] init];
        vc.isPushVc = YES;
        [self pushViewController:vc animated:YES];
    }
}

// 忘记密码
- (IBAction)p_toForgetPwd {
    
    RDSResetPwdVC *resetPwdVC = [[RDSResetPwdVC alloc] init];
    [self pushViewController:resetPwdVC animated:YES];
}

// 登录
- (IBAction)p_onLogin {
    
    NSString* userName = self.accountTF.text;
    NSString* password = self.pwdTF.text;
    
    if (![userName isPhoneNum]) {
        [RDSHudShower showBottomToast:@"请输入正确的手机号码"];
        return;
    }
    else if (password.length == 0){
        [RDSHudShower showBottomToast:@"请输入密码"];
        return;
    }
    else if (!self.agreeBtn.isSelected){
        [RDSHudShower showBottomToast:@"请先阅读并同意用户协议"];
        return;
    }
    
    // md5加密
    NSString *pwdMd5 = [password md5String];
    
    [RDSHudShower showWithStatus:@"正在登录中..." autoDismiss:NO];

    [RDSDemoApiHelper rds_loginWithPwdPhone:userName password:pwdMd5 success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }
        else{
            [RDSHudShower dismissHUD];
            [RDSRootControl shareControl].isLoginSuccess = YES;
            
            NSDictionary *data = responseObject[@"data"];
            TheDataManager.token = [NSString stringWithFormat:@"%@ %@",data[@"token_type"], data[@"access_token"]];
            TheDataManager.isFirstLogin = [data[@"app_first_login"] boolValue];
            TheDataManager.pwd = password;
        }
        
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
}







// 按钮选中时 显示密码
- (IBAction)p_onPwdShowBtnClick:(UIButton *)sender {
    
    _pwdTF.secureTextEntry = sender.selected;
    
    sender.selected = !sender.selected;

    
}

// 继续登录操作
- (void)p_onLoginSuccess {
    
    // 处理登录成功
    [RDSHudShower dismissHUD];
    //[Bugly setUserIdentifier:TheDataManager.user.telphone];
    
    [self p_handleUserInfo];
    [self p_changRootViewController];
}

- (void)p_handleUserInfo {
    
    
//    [kUserDefaults setObject:self.accountTF.text forKey:RDSUserNameUserDefaultKey];
//    NSString *pwdKey = [NSString stringWithFormat:@"%@%@",RDSPasswordUserDefaultKey, self.accountTF.text];
//    [RDSCacheHelper rds_cacheStringWithEncrypt:self.pwdTF.text forKey:pwdKey];
}

- (void)p_changRootViewController {
    
    [RDSRootControl shareControl].isLoginSuccess = YES; // 设置状态自动切换根控制器
}

- (void)p_alertError:(NSString *)error {
    
    [RDSHudShower dismissHUD];
    [self rds_alertMessage:error];
}




#pragma mark - UITextFieldDelegate

- (void)p_setupTF {
    
    self.accountTF.delegate = self;
    self.pwdTF.delegate = self;
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.accountTF) {
        [self.pwdTF becomeFirstResponder];
    }
    else {
        [self.pwdTF resignFirstResponder];
        [self p_onLogin];
    }
    return YES;
}

// 密文输入时，点击光标不清空
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 
//    NSString *updatedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// 
//    textField.text = updatedString;
// 
//    return NO;
//}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self.view endEditing:YES];
}

#pragma mark - UI
- (void)p_initUI {
    
    [self p_setupTF];
//    [self p_configServerType];
    
    _accountTF.placeholder = @"请输入手机号码";
    _pwdTF.placeholder = @"请输入您的密码";
    [_registerBtn setTitle:@"注册账户" forState:UIControlStateNormal];
    [_resetPwdBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    
    
}

- (void)p_textFill {
    
    _accountTF.text = TheDataManager.phone;
    if(!kNULLString(TheDataManager.pwd)){
        _pwdTF.text = TheDataManager.pwd;
    }
    
}


- (void)p_addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取处于焦点中的view
    
    NSArray *textFields = @[self.accountTF,self.pwdTF];
    UIView *focusView = nil;
    for (UITextField *view in textFields) {
        if ([view isFirstResponder]) {
            focusView = view;
            break;
        }
    }
    
    
    RDS_WEAKSELF(weakSelf)
    if (focusView) {
        //获取键盘弹出的时间
        double duration = [notification.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //获取键盘上端Y坐标
        CGFloat keyboardY = [notification.userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
        //获取输入框下端相对于window的Y坐标
        CGRect rect = [focusView convertRect:focusView.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
        CGPoint tmp = rect.origin;
        CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
        //计算二者差值
        CGFloat ty = keyboardY - inputBoxY;
        NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
        //差值小于0，做平移变换
        [UIView animateWithDuration:duration animations:^{
            if (ty < 0) {
                weakSelf.view.transform = CGAffineTransformMakeTranslation(0, ty);
            }
        }];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    //获取键盘弹出的时间
    double duration = [notification.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //还原
    
    RDS_WEAKSELF(weakSelf)
    [UIView animateWithDuration:duration animations:^{
        weakSelf.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

- (void)dealloc {
    DDLog(@"dealloc");
    [kNotificationCenter removeObserver:self];
}

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


@end
