IVTLoginViewController.m 13.5 KB
//
//  IVTLoginViewController.m
//  IVTMeLiveTwo
//
//  Created by XRG on 16/8/12.
//  Copyright © 2016年 QLQ. All rights reserved.
//

#import "IVTLoginViewController.h"
#import "NSString+IVTMeString.h"
#import "WXApi.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/TencentApiInterface.h>
#import "WeiboSDK.h"
#import "AppDelegate.h"
#import "XMPPManager.h"
#import "RootTabBarController.h"

@interface IVTLoginViewController ()<UITextFieldDelegate>
{
    UIButton *captchaButton;
    UITextField  *mobileField;
    UITextField  *captchaField;
    UIButton *loginButton;
    
    NSInteger countdown;
    dispatch_source_t timer;
}
@end

@implementation IVTLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    
    [self timerCount];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap)];
    [self.view addGestureRecognizer:tap];
}

//注册登录页面
- (void)initUI{
    __unsafe_unretained typeof (self) wself = self;

    
    UIImageView *headView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MeLoginHead"]];
    [self.view addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wself.view.mas_top).with.offset(62.0f);
        make.centerX.equalTo(wself.view.mas_centerX);
        make.height.mas_equalTo(120.0f);
    }];
    
    
    UIImageView *inputPhoneView = [[UIImageView alloc]init];
    inputPhoneView.image =[UIImage imageNamed:@"请输入手机号框"];
    inputPhoneView.userInteractionEnabled = YES;
    [self.view addSubview:inputPhoneView];
    [inputPhoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wself.view.mas_top).with.offset(210);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(259.0f, 39.0f));
    }];
    
    
    mobileField = [[UITextField alloc]init];
    mobileField.backgroundColor = [UIColor clearColor];
    mobileField.placeholder = @"请输入手机号";
    [mobileField setValue:UIColorFromRGBAlphaHex(0xA0A0A0, 1.0) forKeyPath:@"_placeholderLabel.textColor"];
    mobileField.font = [UIFont systemFontOfSize:15];
    mobileField.keyboardType = UIKeyboardTypeNumberPad;
    mobileField.delegate = self;
    [inputPhoneView addSubview:mobileField];
    [mobileField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(inputPhoneView.mas_leading).with.offset(43);
        make.size.mas_equalTo(CGSizeMake(200, 39));
        make.top.equalTo(wself.view.mas_top).with.offset(210);
        
    }];
    
    UIImageView *captchaView = [[UIImageView alloc]init];
    captchaView.image =[UIImage imageNamed:@"输入验证码框"];
    captchaView.userInteractionEnabled  = YES;
    [self.view addSubview:captchaView];
    [captchaView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(inputPhoneView.mas_bottom).with.offset(10);
        make.leading.equalTo(inputPhoneView.mas_leading);
        make.size.mas_equalTo(CGSizeMake(151.5f, 39.5f));
    }];
    
    captchaField = [[UITextField alloc]init];
    captchaField.backgroundColor = [UIColor clearColor];
    captchaField.placeholder = @"请输入验证码";
    [captchaField setValue:UIColorFromRGBAlphaHex(0xA0A0A0, 1.0) forKeyPath:@"_placeholderLabel.textColor"];
    captchaField.font = [UIFont systemFontOfSize:15];
    captchaField.keyboardType = UIKeyboardTypeNumberPad;
    captchaField.delegate = self;
    [captchaView addSubview:captchaField];
    [captchaField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(captchaView.mas_leading).with.offset(43.0f);
        make.size.mas_equalTo(CGSizeMake(110, 39));
        make.top.equalTo(inputPhoneView.mas_bottom).with.offset(10);
        
    }];
    
    
    captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [captchaButton.layer setMasksToBounds:YES];
    [captchaButton.layer setCornerRadius:2.0]; //设置矩形四个圆角半径
    [captchaButton setBackgroundColor:UIColorFromRGBAlphaHex(0xffa800, 1.0)];
    [captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    captchaButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [captchaButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:captchaButton];
    [captchaButton addTarget:self action:@selector(captchaClick:) forControlEvents:UIControlEventTouchUpInside];
    [captchaButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(97.0f, 39.0f));
        make.top.equalTo(inputPhoneView.mas_bottom).with.offset(10);
        make.leading.equalTo(captchaView.mas_trailing).with.offset(11);
    }];
    
    //登录
    loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"MeLogin_normal"] forState:UIControlStateNormal];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"MeLoginHL"] forState:UIControlStateHighlighted];
    [self.view addSubview:loginButton];
    [loginButton addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(259.0f, 38.0f));
        make.top.equalTo(captchaButton.mas_bottom).with.offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    UIImageView *loginOtherView = [[UIImageView alloc]init];
    loginOtherView.image =[UIImage imageNamed:@"MeLoginOther"];
    [self.view addSubview:loginOtherView];
    [loginOtherView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loginButton.mas_bottom).with.offset(27);
        make.centerX.equalTo(wself.view);
        make.size.mas_equalTo(CGSizeMake(165, 15));
    }];
    
    UIView *thirdPartyLoginView = [[UIView alloc]init];
    [self.view addSubview:thirdPartyLoginView];
    [thirdPartyLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loginOtherView.mas_bottom).offset(10);
        make.left.equalTo(wself.view.mas_left);
        make.right.equalTo(wself.view.mas_right);
        make.height.mas_equalTo(70);
    }];
    CGFloat space = (kScreenWidth - 3*70)/4;
    /**
     *  微信
     */
    UIButton *weChatLoginButton = [[UIButton alloc]init];
    weChatLoginButton.frame = CGRectMake(space, 0, 70, 70);
    [weChatLoginButton setImage:[UIImage imageNamed:@"微信"] forState:UIControlStateNormal];
    
    [weChatLoginButton addTarget:self action:@selector(doWechatLoginButton) forControlEvents:UIControlEventTouchUpInside];
    [thirdPartyLoginView addSubview:weChatLoginButton];
    
    weChatLoginButton.hidden = ![WXApi isWXAppInstalled];
    
    /**
     *  QQ
     */
    UIButton *qqLoginButton = [[UIButton alloc]init];
    qqLoginButton.frame = CGRectMake(weChatLoginButton.frame.origin.x + weChatLoginButton.frame.size.width + space, 0, 70, 70);
    [qqLoginButton setImage:[UIImage imageNamed:@"qq"] forState:UIControlStateNormal];
    [qqLoginButton addTarget:self action:@selector(doQQLoginButton) forControlEvents:UIControlEventTouchUpInside];
    [thirdPartyLoginView addSubview:qqLoginButton];
    
    /**
     *  新浪微博
     */
    UIButton *sinaLoginButton = [[UIButton alloc]init];
    sinaLoginButton.frame = CGRectMake(qqLoginButton.frame.origin.x + qqLoginButton.frame.size.width + space, 0, 70, 70);
    [sinaLoginButton setImage:[UIImage imageNamed:@"微博"] forState:UIControlStateNormal];
    
    [sinaLoginButton addTarget:self action:@selector(doSinaLoginButton) forControlEvents:UIControlEventTouchUpInside];
    [thirdPartyLoginView addSubview:sinaLoginButton];
    
    sinaLoginButton.hidden = ![WeiboSDK isWeiboAppInstalled];
}

- (void)doTap{
    [self.view endEditing:YES];
}
//textField的字数控制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *behoverString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([textField isEqual:mobileField]) {
        if (behoverString.length > 11) {
            return NO;
        }
        if ([behoverString isMobileNumber]) {
            captchaButton.enabled  = YES;
            
            if (captchaField.text.length==4) {
                loginButton.enabled = YES;
            }
        }
    }
    
    if ([textField isEqual:captchaField]) {
        if (range.location >= 4) {
            return NO;
        }
    }
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [mobileField resignFirstResponder];
    [captchaField resignFirstResponder];
    return NO;
}
#pragma mark - 点击获取验证码
-(void)captchaClick:(id)sender{
    if (mobileField.text.length > 0 && [mobileField.text isMobileNumber]) {

        captchaButton.enabled = NO;
        [self performSelector:@selector(timeEnough:) withObject:nil afterDelay:60.0];

        [HUDUtil showLoading];
        [self.view endEditing:YES];
        [[IVTNetworkAPIClient sharedClient] getCaptchaWithPhone:mobileField.text success:^(NSDictionary *successData) {
            countdown = 60;
            dispatch_resume(timer);
            [HUDUtil showSuccess:@"验证码已发送"];
            
            [captchaField becomeFirstResponder];
            
        } error:^(NSDictionary *successData) {
            NSString *msg = successData[@"description"];
            [HUDUtil showError:msg];
            captchaButton.enabled = YES;
            countdown = 0;
        } failure:^(NSError *failureError) {
            [HUDUtil showError:@"网络异常"];
            captchaButton.enabled = YES;
            countdown = 0;
        }];
    }else{
        [HUDUtil showError:@"请输入手机号,并再次请求验证码"];
    }
}

-(void)timeEnough:(UIButton *)btn{
    captchaButton.enabled = YES;
}


- (void)timerCount {
    countdown = 60;
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        [captchaButton setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)countdown] forState:UIControlStateDisabled];
        if (countdown == 0) {
            dispatch_suspend(timer);
            [captchaButton setTitle:@"重新发送" forState:UIControlStateDisabled];
            [captchaButton setTitle:@"重新发送" forState:UIControlStateNormal];
            [captchaButton setEnabled:YES];
        } else {
            countdown--;
        }
    });
}
#pragma mark - 手机登录实现
-(void)loginClick:(id)sender{
    if ([mobileField.text isMobileNumber] && captchaField.text.length > 0) {

        loginButton.enabled = NO;
        
        [HUDUtil showLoading];
        [self.view endEditing:YES];

        [[IVTNetworkAPIClient sharedClient] loginWithPhone:mobileField.text captcha:captchaField.text success:^(NSDictionary *successData) {
            
            [[XMPPManager sharedInstance] loginWithUserId:[IVTAccountTool getUserId] pwd:captchaField.text];
            
            [IVTAccountTool getFollowListRequest];
            
            [HUDUtil showSuccess:@"登录成功"];

            [self dismissViewControllerAnimated:YES completion:nil];
        } error:^(NSDictionary *successData) {
            NSString *msg = successData[@"description"];
            [HUDUtil showError:msg];
            
            loginButton.enabled = YES;

        } failure:^(NSError *failureError) {
            [HUDUtil showError:@"网络异常"];
            loginButton.enabled = YES;

        }];
    } else {
        [HUDUtil showError:@"请输入手机号或验证码"];
    }
}
//微信登录
- (void)doWechatLoginButton{
    [self.view endEditing:YES];
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc]init];
        req.scope = @"snsapi_userinfo,snsapi_base";
        req.state = @"mijiazhibo";
        [WXApi sendReq:req];
        [RootTabBarController tabBarVC].isBinding = YES;
    }
}
//qq登录
- (void)doQQLoginButton{
    [self.view endEditing:YES];

    NSArray *permissions = [NSArray arrayWithObjects: kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,kOPEN_PERMISSION_ADD_SHARE,nil];
    [[AppDelegate appDelegate].tencentOAuth authorize:permissions inSafari:NO];
    [[AppDelegate appDelegate].tencentOAuth accessToken];
    [[AppDelegate appDelegate].tencentOAuth openId];
    
    [RootTabBarController tabBarVC].isBinding = YES;
}
//新浪登录
- (void)doSinaLoginButton{
    [self.view endEditing:YES];

    if ([WeiboSDK isWeiboAppInstalled]) {
        WBAuthorizeRequest *request = [WBAuthorizeRequest request];
        request.redirectURI = kSina_RedirectURI;
        request.scope = @"all";
        request.userInfo = @{@"SSO_From": @"IVTLoginViewController",
                             @"Other_Info_1": [NSNumber numberWithInt:123],
                             @"Other_Info_2": @[@"obj1", @"obj2"],
                             @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
        [WeiboSDK sendRequest:request];
        
        [RootTabBarController tabBarVC].isBinding = YES;
    }
}


- (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