CNLiveLoginViewController.m 14.4 KB
//
//  CNLiveLoginViewController.m
//  CNLiveScioLive
//
//  Created by Xiaowen Zhang on 2018/9/19.
//  Copyright © 2018年 CNLive. All rights reserved.
//

#import "CNLiveLoginViewController.h"
#import "CNLiveRegisterViewController.h"
#import "CNLiveForgotPasswordViewController.h"

#import "CNLiveLoginInputView.h"
#import "CNLiveThirdLoginView.h"
#import "ZXWUserModel.h"

@interface CNLiveLoginViewController ()
@property (nonatomic, strong) CNLiveLoginInputView *account;
@property (nonatomic, strong) CNLiveLoginInputView *pwd;
@end

@implementation CNLiveLoginViewController
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if([User_Defaults objectForKey:@"user_phone"] && [User_Defaults objectForKey:@"user_phone"] != nil && ![[User_Defaults objectForKey:@"user_phone"] isEqualToString:@""]){
        _account.textField.text = [User_Defaults objectForKey:@"user_phone"];
    }else if([User_Defaults objectForKey:@"user_email"] && [User_Defaults objectForKey:@"user_email"] != nil && ![[User_Defaults objectForKey:@"user_email"] isEqualToString:@""]){
        _account.textField.text = [User_Defaults objectForKey:@"user_email"];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavigationBar];
    [self setUpSubControllers];

    // Do any additional setup after loading the view.
}
#pragma mark - UI
- (void)setUpNavigationBar{
    
    self.navigationController.navigationBar.barTintColor = Color_Blue;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

    //左
    UIButton *headerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
    headerButton.layer.cornerRadius = 2.0;
    headerButton.layer.masksToBounds = true;
    [headerButton setImage:[UIImage imageNamed:@"cnlive_white_back"] forState:UIControlStateNormal];
    [headerButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headerButton];
    self.navigationItem.title = CustomStr(@"Login");
    
}
- (void)setUpSubControllers{
    
    _account = [[CNLiveLoginInputView alloc] initWithPic:@"cnlive_phone_email" placeholder:[NSString stringWithFormat:@"%@/%@", CustomStr(@"PhoneNumber"), CustomStr(@"Email")] type:CNLiveButtonTypeNormal];
    [self.view addSubview:_account];
    [_account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(15);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.height.offset(40);
        
    }];
    
    _pwd = [[CNLiveLoginInputView alloc] initWithPic:@"cnlive_password" placeholder:CustomStr(@"Password") type:CNLiveButtonTypeTextEntry];
    [self.view addSubview:_pwd];
    [_pwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_account.mas_bottom).with.offset(15);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.height.offset(40);
        
    }];
    
    UIButton *loginButton = [[UIButton alloc] init];
    loginButton.tag = 10000;
    loginButton.layer.cornerRadius = 5.0;
    loginButton.layer.masksToBounds = true;
    [loginButton addTarget:self action:@selector(clicekdButton:) forControlEvents:UIControlEventTouchUpInside];
    [loginButton setTitle:CustomStr(@"Login") forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:17];
    loginButton.backgroundColor = Color_Blue;
    [self.view addSubview:loginButton];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_pwd.mas_bottom).with.offset(20);
        make.left.equalTo(self.view.mas_left).with.offset(10);
        make.right.equalTo(self.view.mas_right).with.offset(-10);
        make.height.offset(40);

    }];
    
    UIButton *registerButton = [[UIButton alloc] init];
    registerButton.tag = 10001;
    registerButton.layer.cornerRadius = 2.0;
    registerButton.layer.masksToBounds = true;
    [registerButton addTarget:self action:@selector(clicekdButton:) forControlEvents:UIControlEventTouchUpInside];
    [registerButton setTitle:CustomStr(@"SignUp") forState:UIControlStateNormal];
    [registerButton setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
    registerButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:registerButton];

    [registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(loginButton.mas_left).with.offset(0);
        make.top.equalTo(loginButton.mas_bottom).with.offset(15);
        make.width.offset(120);
        make.height.offset(25);

    }];
    
    UIButton *pwdButton = [[UIButton alloc] init];
    pwdButton.tag = 10002;
    [pwdButton addTarget:self action:@selector(clicekdButton:) forControlEvents:UIControlEventTouchUpInside];
    [pwdButton setTitle:CustomStr(@"ForgotPassword") forState:UIControlStateNormal];
    [pwdButton setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
    pwdButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:pwdButton];

    [pwdButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(loginButton.mas_right).with.offset(0);
        make.top.equalTo(loginButton.mas_bottom).with.offset(15);
        make.width.offset(120);
        make.height.offset(25);
        
    }];
    
    NSArray *pics = @[@"cnlive_wechat", @"cnlive_qq", @"cnlive_weibo"];
    CNLiveThirdLoginView *thirdLoginView = [[CNLiveThirdLoginView alloc]initWithFrame:CGRectMake(0, MainScreenHeight-100-NavBarContentHeight-TabBarHeight, MainScreenWidth, 100)];
    thirdLoginView.btns = pics;
    thirdLoginView.block = ^(NSInteger tag) {
        [self loginThirdParty:tag];
    };
    [self.view addSubview:thirdLoginView];

    
}
- (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.
}
*/
#pragma mark - Action
- (void)allResignFirstResponder{
    [_account.textField resignFirstResponder];
    [_pwd.textField resignFirstResponder];

}

- (void)sendLoginRequest:(UIButton *)btn{
    [self allResignFirstResponder];

    NSRange range = [_account.textField.text rangeOfString:@"@"];
    if(range.location == NSNotFound) {
        if (![_account.textField.text isValidMobile]) {
            [AlertViewTool showHUDViewText:CustomStr(@"PhoneNumberError")];
            btn.userInteractionEnabled = YES;
            return;
        }
    } else {
        if (![_account.textField.text isValidEmail]) {
            [AlertViewTool showHUDViewText:CustomStr(@"EmailError")];
            return;
        }
    }
    
    if(![_pwd.textField.text isValidPassWordLegal]){
        [AlertViewTool showHUDViewText:CustomStr(@"PasswordError")];
        btn.userInteractionEnabled = YES;
        return;
        
    }
#pragma mark - CNLiveUserSystemSDK 登录
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        btn.userInteractionEnabled = YES;
        return;
    }
    [AlertViewTool showHUDView];

    [CNLiveUserSystemCenter loginWithUserName:_account.textField.text password:_pwd.textField.text frmId:nil success:^(NSDictionary *result) {
        [AlertViewTool hideHUDView];

        if ([result[@"errorCode"] integerValue] == 0) {
            ZXWUserInformation *share = [ZXWUserInformation shareZXWUserInformation];
            share.model = [[ZXWUserModel alloc] initWithDictionary:result[@"data"]];
            [[ZXWUserInformation shareZXWUserInformation] saveToken:@""];
            [[ZXWUserInformation shareZXWUserInformation] saveUser_id:@""];
            [[ZXWUserInformation shareZXWUserInformation] setIsLoginSuccess:YES];
            
            [[ZXWUserInformation shareZXWUserInformation] saveUser_name:result[@"data"][@"nickName"]];
            [[ZXWUserInformation shareZXWUserInformation] saveUser_pwd:self->_pwd.textField.text];
            [[ZXWUserInformation shareZXWUserInformation] saveUser_phone:result[@"data"][@"mobile"]];
            [[ZXWUserInformation shareZXWUserInformation] saveUser_email:result[@"data"][@"email"]];
            [[ZXWUserInformation shareZXWUserInformation] saveUser_headimgUrlString:result[@"data"][@"faceUrl"]];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessful object:nil];

            [AlertViewTool showHUDViewText:CustomStr(@"LoginSuccess") block:^{
                btn.userInteractionEnabled = YES;
                [self goBack];
            }];

        } else {
            [AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
            btn.userInteractionEnabled = YES;
            
        }

    } failure:^(NSDictionary *errorDic) {
        [AlertViewTool hideHUDView];
        [AlertViewTool showHUDViewText:errorDic[@"errorMessage"]];
        btn.userInteractionEnabled = YES;

    }];
}

- (void)clicekdButton:(UIButton *)btn{
    switch (btn.tag) {
        case 10000:
        {
            btn.userInteractionEnabled = NO;
            [self sendLoginRequest:btn];
        }
            break;
        case 10001:
        {
            CNLiveRegisterViewController *vc = [CNLiveRegisterViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 10002:
        {
            //忘记密码
            //http://my.cnlive.com/cnlive_ucloud/static/yhcloud/verifyMode.html?appId=38_ivkou3xi05
            CNLiveWebViewController *vc = [CNLiveWebViewController new];
            vc.navTitle = CustomStr(@"ResetPassword");
            vc.url = [NSString stringWithFormat:@"http://my.cnlive.com/cnlive_ucloud/static/yhcloud/verifyMode.html?appId=%@",CNLiveAppId];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}

 - (void)loginThirdParty:(NSInteger)tag {
#pragma mark - CNLiveUserSystemSDK 第三方登录
     if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
         [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
         return;
     }
    // 平台类型
    SSDKPlatformType type = SSDKPlatformTypeUnknown;
    NSString *plat = [NSString string];
    switch (tag) {
        case 1000:
            type = SSDKPlatformTypeWechat;
            plat = @"3";
            break;
        case 1001:
            type = SSDKPlatformTypeQQ;
            plat = @"2";
            break;
        case 1002:
            type = SSDKPlatformTypeSinaWeibo;
            plat = @"1";
            break;
        default:
            break;
    }
     
    [ShareSDK getUserInfo:type onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        switch (state) {
            case SSDKResponseStateSuccess: {
                // 准备登录参数
                [CNLiveUserSystemCenter thirdPartyLoginWithThirdPartyPlatType:plat thirdPartyId:user.uid nickName:user.nickname gender:nil location:nil faceUrl:user.icon frmId:nil success:^(NSDictionary *result) {
                    if ([result[@"errorCode"] integerValue] == 0) {
                                                
                        ZXWUserInformation *share = [ZXWUserInformation shareZXWUserInformation];
                        share.model = [[ZXWUserModel alloc] initWithDictionary:result[@"data"]];
                        
                        [[ZXWUserInformation shareZXWUserInformation] saveToken:result[@"data"][@"token"]];
                        [[ZXWUserInformation shareZXWUserInformation] saveUser_id:@""];
                        [[ZXWUserInformation shareZXWUserInformation] setIsLoginSuccess:YES];
                        
                        [[ZXWUserInformation shareZXWUserInformation] saveUser_name:result[@"data"][@"nickName"]];
                        [[ZXWUserInformation shareZXWUserInformation] saveUser_pwd:self->_pwd.textField.text];
                        [[ZXWUserInformation shareZXWUserInformation] saveUser_phone:result[@"data"][@"mobile"]];
                        [[ZXWUserInformation shareZXWUserInformation] saveUser_email:result[@"data"][@"email"]];
                        [[ZXWUserInformation shareZXWUserInformation] saveUser_headimgUrlString:result[@"data"][@"faceUrl"]];
                        [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessful object:nil];

                        [AlertViewTool showHUDViewText:CustomStr(@"LoginSuccess") block:^{
                            [self goBack];

                        }];
                        
                    } else {
                        [AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];

                        
                    }
                } failure:^(NSDictionary *errorDic) {
                    [AlertViewTool showHUDViewText:errorDic[@"errorMessage"]];
                }];
                break;
            }
            case SSDKResponseStateFail:
                [AlertViewTool showHUDViewText:CustomStr(@"LoginFailure")];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [AlertViewTool hideHUDView];
                });
                break;
            case SSDKResponseStateCancel:
                [AlertViewTool showHUDViewText:CustomStr(@"CancelLogin")];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [AlertViewTool hideHUDView];
                });
                break;
            default:{
                
            }
                break;
        }
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self allResignFirstResponder];
    
}
@end