//
//  ALSignInView.m
//  GMAlpha
//
//  Created by Mikasa on 2018/11/13.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALSignInView.h"
#import "ALRegisterViewController.h"
#import "ALLoginViewController.h"
#import "ALRegisterSetPwdViewController.h"
#import "UIView+SafeArea.h"
#import "GMSignInManager.h"
#import "ALQAWebViewController.h"
#import "AppDelegate+ViewControl.h"


@interface ALSignInView()<UITextFieldDelegate>
@property (nonatomic, strong) GMImageView *headerView;
@property (nonatomic, strong) GMImageView *headeImageView;// 头部图片
@property (nonatomic, strong) GMLabel *titleLabel;// 标题
@property (nonatomic, strong) GMView *inputView;// 输入框
@property (nonatomic, strong) GMTextField *userNameField;
@property (nonatomic, strong) GMTextField *pwdField;
@property (nonatomic, strong) GMTextField *codeField;
@property (nonatomic, strong) GMButton *sendCodeButton;// 发送验证码
@property (nonatomic, strong) GMButton *eventButton;// 操作按钮
@property (nonatomic, strong) GMButton *goToPageButton;// 前往其他操作

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation ALSignInView

- (instancetype)init {
    if (self = [super init]) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:self.userNameField];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:self.pwdField];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:self.codeField];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setup {
    
    [super setup];
    
    self.backgroundColor = [UIColor whiteColor];
    
    GMImageView *headerView = [GMImageView new];
    headerView.image = [UIImage imageNamed:@"register_bg"];
    [self addSubview:headerView];
    self.headerView = headerView;
    
    GMImageView *headeImageView = [GMImageView new];
    headeImageView.image = [UIImage imageNamed:@"register_icon"];
    [self.headerView addSubview:headeImageView];
    self.headeImageView = headeImageView;
    
    GMLabel *titleLabel = [GMLabel new];
    titleLabel.font = [UIFont gmBoldFont:24];
    titleLabel.textColor = UIColor.headlineText;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.text = @"注册";
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    GMView *inputView = [GMView new];
    [self addSubview:inputView];
    self.inputView = inputView;
    
    GMTextField *userNameField = [GMTextField new];
    userNameField.font = [UIFont gmFont:16];
    userNameField.returnKeyType = UIReturnKeyNext;
    userNameField.placeholder = @"请输入邮箱";
    userNameField.delegate = self;
    [userNameField addBottomLine];
    [self.inputView addSubview:userNameField];
    self.userNameField = userNameField;
    
    GMTextField *pwdField = [GMTextField new];
    pwdField.font = [UIFont gmFont:16];
    pwdField.placeholder = @"请输入密码";
    pwdField.returnKeyType = UIReturnKeyDone;
    pwdField.delegate = self;
    pwdField.secureTextEntry = YES;
    [pwdField addBottomLine];
    [self.inputView addSubview:pwdField];
    self.pwdField = pwdField;
    
    GMTextField *codeField = [GMTextField new];
    codeField.font = [UIFont gmFont:16];
    codeField.placeholder = @"请查看验证码并输入";
    codeField.returnKeyType = UIReturnKeyDone;
    codeField.delegate = self;
    [codeField addBottomLine];
    
    [self.inputView addSubview:codeField];
    self.codeField = codeField;
    
    // 发送验证码
    GMButton *sendCodeButton = [GMButton new];
    sendCodeButton.titleLabel.font = [UIFont gmFont:16];
    sendCodeButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [sendCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [sendCodeButton setBackgroundColor:[UIColor clearColor] forState:UIControlStateNormal];
    [sendCodeButton addTarget:self action:@selector(sendCodeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [sendCodeButton setTitleColor:RGBCOLOR_HEX(0x0093FF) forState:UIControlStateNormal];
    [self.inputView addSubview:sendCodeButton];
    self.sendCodeButton = sendCodeButton;
    
    // 注册 / 登陆
    GMButton *eventButton = [GMButton new];
    eventButton.titleLabel.font = [UIFont gmFont:16];
    eventButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [eventButton setTitle:@"注册" forState:UIControlStateNormal];
    [eventButton addTarget:self action:@selector(eventButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [eventButton setTitleColor:RGBCOLOR_HEX(0xFFFFFF) forState:UIControlStateNormal];
    [eventButton setBackgroundColor:RGBCOLOR_HEX(0x0093FF) forState:UIControlStateNormal];
    [eventButton setBackgroundColor:[UIColor colorWithHex:0x0093FF alpha:0.4] forState:UIControlStateDisabled];
    eventButton.layer.masksToBounds = YES;
    eventButton.layer.cornerRadius = 20.0f;
    eventButton.enabled = NO;
    [self addSubview:eventButton];
    self.eventButton = eventButton;
    
    // 前往其他操作
    GMButton *goToPageButton = [GMButton new];
    [goToPageButton setTitleColor:RGBCOLOR_HEX(0x0093FF) forState:UIControlStateNormal];
    [goToPageButton setTitle:@"已有账号去登录" forState:UIControlStateNormal];
    goToPageButton.titleLabel.font = [UIFont gmFont:14];
    goToPageButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [goToPageButton addTarget:self action:@selector(goToPageButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:goToPageButton];
    self.goToPageButton = goToPageButton;
    
    [self addSubViewContraints];
}

- (void)addSubViewContraints {
    
    __weak __typeof(self)weakSelf = self;
    
    CGFloat top = [AppDelegate navigation].navigationBar.height + UIView.safeAreaInsetsTop;
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(top + 175 + 10);
    }];
    
    [self.headeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(221, 175));
        make.centerX.mas_equalTo(weakSelf.mas_centerX);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headeImageView.mas_bottom).offset(5);
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(25);
    }];
    
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(30);
        make.height.mas_equalTo(112);
    }];
    
    [self.userNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.left.right.top.mas_equalTo(0);
    }];
    
    [self.pwdField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(self.userNameField.mas_bottom).offset(1);
    }];
    
    [self.codeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(56);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(self.userNameField.mas_bottom).offset(1);
    }];
    
    [self.sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(40);
        make.centerY.mas_equalTo(self.codeField);
    }];
    
    [self.eventButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-(UIView.safeAreaInsetsBottom+20));
        make.left.mas_equalTo(22);
        make.right.mas_equalTo(-22);
        make.height.mas_equalTo(41);
    }];
    
    [self.goToPageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.inputView.mas_bottom).offset(15);
        make.right.mas_equalTo(-30);
        make.width.mas_equalTo(98);
        make.height.mas_equalTo(15);
    }];
}

- (void)setSignInEvent:(ALSignInEvent)signInEvent {
    
    _signInEvent = signInEvent;
    
    if (signInEvent == ALSignInEventLogin) {
        _pwdField.hidden = NO;
        _codeField.hidden = YES;
        _sendCodeButton.hidden = YES;
        _titleLabel.text = @"登录";
        [_eventButton setTitle:@"登录" forState:UIControlStateNormal];
        [_goToPageButton setTitle:@"没有账号去注册" forState:UIControlStateNormal];
    } else {
        _pwdField.hidden = YES;
        _codeField.hidden = NO;
        _sendCodeButton.hidden = NO;
        _titleLabel.text = @"注册";
        [_eventButton setTitle:@"注册" forState:UIControlStateNormal];
        [_goToPageButton setTitle:@"已有账号去登录" forState:UIControlStateNormal];
    }
}


#pragma mark - ButtonClick
- (void)eventButtonClick {
    
    
    if (self.signInEvent == ALSignInEventLogin) {

        [Phobos track:@"login_click_login"];
        
        // 登录
        [self loginWithAccount];

    } else {
        
        [Phobos track:@"register_click_register"];
        
        [self endEditing:YES];
        if (![self validateEmail]) return;
        
        if (![self validateCode]) return;
        
        ALRegisterSetPwdViewController *loginCtrl = [[ALRegisterSetPwdViewController alloc] init];
        loginCtrl.viewModel.email = self.userNameField.text;
        loginCtrl.viewModel.vfc_code = self.codeField.text;
        [[AppDelegate navigation] pushViewController:loginCtrl animated:YES];
    }
}

// 引导去注册/登录
- (void)goToPageButtonClick {
    
    if (self.signInEvent == ALSignInEventLogin) {
        
        [[AppDelegate navigation] popViewControllerAnimated:YES];
        
    } else {
        
        ALLoginViewController *loginCtrl = [[ALLoginViewController alloc] init];
        [[AppDelegate navigation] pushViewController:loginCtrl animated:YES];
    }
}

// 发送验证码
- (void)sendCodeButtonClick {
    
    [self sendVerifyCode];
    
}

#pragma mark - NetWork Data
// 登录
- (void)loginWithAccount {
    
    [self endEditing:YES];
    if (![self validateEmail] || ![self validatePwd]) return;
    
    [GMSignInManager loginWithAccount_type:ALSignInTypeEmail email:self.userNameField.text phone:@"" pwd:self.pwdField.text finishBlock:^(NSString *message, BOOL success, id data) {
        [GMHudModule toast:message];
    }];
}

// 发送验证码
- (void)sendVerifyCode {
    
    if (![self validateEmail]) return;
    
    self.sendCodeButton.userInteractionEnabled = NO;
    [self endEditing:YES];
    __weak __typeof(self)weakSelf = self;
    [GMSignInManager sendVerifyCodeAccount_type:ALSignInTypeEmail vfcType:ALVfcTypeRegister email:self.userNameField.text phone:@"" finishBlock:^(NSString *message, BOOL success, id data) {
        [GMHudModule hideLoading];
        if (success) {
            // 添加触发定时器
            [weakSelf addSendCodeTimer];
        } else {
            weakSelf.sendCodeButton.userInteractionEnabled = YES;
        }
        [GMHudModule toast:message];
    }];
}

#pragma mark - private method
// 校验文本输入
- (BOOL)validateEmail {
    NSString *email = self.userNameField.text;
    if (email.length == 0) {
        [GMHudModule toast:@"邮箱不能为空"];
        [self.userNameField becomeFirstResponder];
        return NO;
    }
    if (![NSString isValidateEmail:email]) {
        [GMHudModule toast: @"请输入正确的邮箱账号"];
        [self.userNameField becomeFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)validatePwd {
    NSString *pwdString = self.pwdField.text;
    if (![pwdString isNonEmpty]) {
        [GMHudModule toast:@"请输入密码"];
        [self.pwdField becomeFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)validateCode {
    if (![self.codeField.text isNonEmpty]) {
        self.sendCodeButton.enabled = YES;
        [GMHudModule toast:@"验证码不能为空"];
        [self.codeField becomeFirstResponder];
        return NO;
    }
    return YES;
}

// 添加触发器
- (void)addSendCodeTimer {
    
    __weak __typeof(self)weakSelf = self;
    //触发定时器
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    weakSelf.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(weakSelf.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(weakSelf.timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(weakSelf.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf.sendCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                [weakSelf.sendCodeButton setTitleColor:RGBCOLOR_HEX(0x0093FF) forState:UIControlStateNormal];
                weakSelf.sendCodeButton.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60;
            if (seconds == 0) {
                seconds = 60;
            }
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf.sendCodeButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                [weakSelf.sendCodeButton setTitleColor:RGBCOLOR_HEX(0x999999) forState:UIControlStateNormal];
                weakSelf.sendCodeButton.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(weakSelf.timer);
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSString *text = textField.text;
    if (![text isNonEmpty]) {
        return NO;
    }
    [textField resignFirstResponder];
    if (textField == self.userNameField) {
        if (self.signInEvent == ALSignInEventLogin) {
            [self.pwdField becomeFirstResponder];
        } else {
            [self.codeField becomeFirstResponder];
        }
    } else {
        [self eventButtonClick];
    }
    
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self endEditing:YES];
}

#pragma mark - NSNotificationCenter
- (void)textChange:(NSNotification *)notifi {
    
    [self eventButtonEnable];
}

- (void)eventButtonEnable {
    if (self.signInEvent == ALSignInEventLogin) {
        if ([self.userNameField.text isNonEmpty] && [self.pwdField.text isNonEmpty]) {
            self.eventButton.enabled = YES;
        } else {
            self.eventButton.enabled = NO;
        }
    } else {
        if ([self.userNameField.text isNonEmpty] && [self.codeField.text isNonEmpty]) {
            self.eventButton.enabled = YES;
        } else {
            self.eventButton.enabled = NO;
        }
    }
}

@end
