//
//  ALBindPhoneController.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/13.
//  Copyright © 2018年 Gengmei. All rights reserved.
//

#import "ALBindPhoneController.h"
#import "GMAreaCodeCell.h"
#import "GMSignInManager.h"
#import "ALCountryNumPickView.h"
#import "ALConfigObject.h"

typedef NS_OPTIONS(NSUInteger, DelegateType) {
    DelegateTypeStopEditting,
    DelegateTypeCodeLabeValue
};

@protocol GMBindPhoneTextFViewDelegate <NSObject>

- (void)notificationEndEditMethod:(DelegateType)type text:(NSString *)text;

@end

@interface GMBindPhoneTextFView : GMView
/** 左边图片 */
@property (nonatomic, strong) GMImageView *icon;
/** 右边textField */
@property (nonatomic, strong) GMTextField *contentTexF;
/** 区号label */
@property (nonatomic, strong) GMLabel *quhaoLabel;
/** 区号下角标 */
@property (nonatomic, strong) GMImageView *quhaoImage;
/** 覆盖的button */
@property (nonatomic, strong) UIButton *totalButton;
/** 底部线 */
@property (nonatomic, strong) UIView *bottomView;
/** 第一行重新布局 */
@property (nonatomic, assign) BOOL isChangeFrame;

@property (nonatomic, weak) id<GMBindPhoneTextFViewDelegate>delegate;

@end

@implementation GMBindPhoneTextFView

- (void)setup
{
    [super setup];

    [self setUI];
    
    [self setLayout];
}

- (void)setUI
{
    [self addSubview:self.icon];
    [self addSubview:self.contentTexF];
    [self addSubview:self.quhaoLabel];
    [self addSubview:self.quhaoImage];
    [self addSubview:self.totalButton];
}

- (void)setLayout
{
    [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(16);
        make.left.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(13.5, 18));
    }];
    [self.quhaoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.icon.mas_right).offset(8);
        make.centerY.equalTo(self.icon.mas_centerY);
    }];
    [self.quhaoImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.quhaoLabel.mas_right);
        make.centerY.equalTo(self.icon.mas_centerY);
    }];
    [self.totalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.quhaoLabel.mas_left);
        make.height.equalTo(self.quhaoLabel.mas_height);
        make.right.equalTo(self.quhaoImage.mas_right);
        make.centerY.equalTo(self.quhaoLabel.mas_centerY);
    }];
    
    self.bottomView = [self addBottomLine];
}

#pragma mark--setter
- (void)setIsChangeFrame:(BOOL)isChangeFrame
{
    if (isChangeFrame == YES)
    {
        self.quhaoLabel.hidden = NO;
        self.quhaoImage.hidden = NO;
        self.totalButton.hidden = NO;
        [self.contentTexF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(14);
            make.bottom.mas_equalTo(-20);
            make.left.equalTo(self.quhaoImage.mas_right).offset(10);
            make.height.mas_equalTo(20);
            make.right.mas_equalTo(0);
        }];
    }
    else
    {
        self.quhaoLabel.hidden = YES;
        self.quhaoImage.hidden = YES;
        self.totalButton.hidden = YES;
        [self.contentTexF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(16);
            make.bottom.mas_equalTo(-18);
            make.left.equalTo(self.icon.mas_right).offset(8);
            make.height.mas_equalTo(20);
            make.right.mas_equalTo(0);
        }];
    }
}

#pragma mark--click Method
- (void)selectCountryMethod:(GMButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(notificationEndEditMethod:text:)]) {
        [self.delegate notificationEndEditMethod:DelegateTypeStopEditting text:nil];
    }
    //点开pickView时候改变箭头方向
    self.quhaoImage.image = [UIImage imageNamed:@"me_up_arrow"];

    [self endEditing:YES];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];    
    NSDictionary *data = [user objectForKey:@"phoneAreaKey"];
    ALConfigObject *model;
    if (data) {
        model = [[ALConfigObject alloc] initWithDictionary:data error:nil];
    }
    ALCountryNumPickView *pickView =[[ALCountryNumPickView alloc] initWithComponentDataArray:model.phoneArea];
    __weak __typeof(self)weakSelf = self;
    pickView.getPickerValue = ^(BOOL isChange, NSString *codeStr) {
        if (isChange) {
            weakSelf.quhaoLabel.text = codeStr;
        }
        //关闭pickView时候改变箭头方向
        weakSelf.quhaoImage.image = [UIImage imageNamed:@"me_down_arrow"];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:pickView];
}

#pragma mark--getter
- (GMImageView *)icon
{
    if (!_icon) {
        _icon = [[GMImageView alloc] init];
    }
    return _icon;
}

- (GMTextField *)contentTexF
{
    if (!_contentTexF) {
        _contentTexF = [[GMTextField alloc] init];
        _contentTexF.font = [UIFont gmFont:16];
        _contentTexF.keyboardType = UIKeyboardTypeNumberPad;        
        _contentTexF.textColor = [UIColor blackColor];
        _contentTexF.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _contentTexF;
}

- (GMLabel *)quhaoLabel
{
    if (!_quhaoLabel) {
        _quhaoLabel = [GMLabel labelWithTextColor:UIColor.bodyText fontSize:17];
        _quhaoLabel.text = @"+86";
    }
    return _quhaoLabel;
}

- (GMImageView *)quhaoImage
{
    if (!_quhaoImage) {
        _quhaoImage = [[GMImageView alloc]initWithImage:[UIImage imageNamed:@"me_down_arrow"]];
        _quhaoImage.userInteractionEnabled = YES;
    }
    return _quhaoImage;
}

- (UIButton *)totalButton
{
    if (!_totalButton) {
        _totalButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_totalButton addTarget:self action:@selector(selectCountryMethod:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _totalButton;
}

@end

@interface ALBindPhoneController ()<GMBindPhoneTextFViewDelegate>
/** 获取验证码 */
@property (nonatomic, strong) GMButton *sendVerificationButton;
/** 承载验证码那一行的view textField + button */
@property (nonatomic, strong) GMView *verifyView;
/** 计时器 */
@property (nonatomic, strong) dispatch_source_t timer;
/** 确定按钮 */
@property (nonatomic, strong) GMButton *verificationButton;
/** 输入手机号的textField */
@property (nonatomic, strong) GMBindPhoneTextFView *phoneView;
/** 输入验证码的textField */
@property (nonatomic, strong) GMBindPhoneTextFView *codeView;
/** 底部文字 */
@property (nonatomic, strong) GMLabel *tipLabel;

@end

@implementation ALBindPhoneController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNav];
    
    [self setUI];
    
    [self setLayout];
}

#pragma mark--setUI
- (void)setNav
{
    self.title = @"绑定手机号";
}

- (void)setUI
{
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.phoneView];
    [self.view addSubview:self.verifyView];
    [self.verifyView addSubview:self.codeView];
    [self.verifyView addSubview:self.sendVerificationButton];
    [self.view addSubview:self.verificationButton];
    [self.view addSubview:self.tipLabel];
}
- (void)setLayout
{
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.top.equalTo(self.navigationBar.mas_bottom).offset(25);
    }];
    
    [self.verifyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(50);
        make.top.equalTo(self.phoneView.mas_bottom);
    }];
    
    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(-90);
        make.centerY.mas_equalTo(0);
    }];
    
    [self.sendVerificationButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.codeView.mas_right).offset(5);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(35);
        make.right.mas_equalTo(0);
    }];
    
    [self.verificationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.bottom.equalTo(self.view.mas_safeBottom).offset(-20);
        make.height.mas_equalTo(44);
    }];
    
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.codeView.mas_left);
        make.top.equalTo(self.codeView.mas_bottom).offset(16);
        make.height.mas_equalTo(14);
    }];
}
#pragma mark--delegate

- (void)notificationEndEditMethod:(DelegateType)type text:(NSString *)text
{
    switch (type) {
        case DelegateTypeStopEditting:
            [self.view endEditing:YES];
            break;
        case DelegateTypeCodeLabeValue:
            self.codeView.quhaoLabel.text = text;
            break;
        default:
            break;
    }
}

#pragma mark--click Method
/**
 *  @brief  发送验证码
 *  @param sender id类型参数
 */
- (void)sendVerificationButtonClicked:(id)sender
{
    if (![self.phoneView.contentTexF.text isNonEmpty]) {
        [self toast:@"手机号不能为空"];
        return;
    }else if (![NSString isPureInt: self.phoneView.contentTexF.text]) {
        [self toast: @"请输入正确的手机号码"];
        return;
    }
    __weak __typeof(self)weakSelf = self;
    [GMSignInManager sendVerifyCodeAccount_type:(ALSignInTypePhone) vfcType:(ALVfcTypeBind) email:nil phone:self.phoneView.contentTexF.text finishBlock:^(NSString *message, BOOL success, id data) {
        [self hideLoading];
        if (success) {
            NSString * newPhone = weakSelf.phoneView.contentTexF.text;
            [weakSelf toast:[NSString stringWithFormat:@"验证码已发送至【%@】请注意查收",newPhone]];
            NSString *code = (NSString *)data;
            weakSelf.codeView.contentTexF.text = code;
            // 添加触发定时器
            [weakSelf addSendCodeTimer];
        } else {
            weakSelf.sendVerificationButton.userInteractionEnabled = YES;
            [GMHudModule toast:message];
        }
    }];
    
}
/**
 * 倒计时逻辑
 */
- (void)addSendCodeTimer
{
    __weak __typeof(self)weakSelf = self;
    //触发定时器
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(self.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf.sendVerificationButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                weakSelf.sendVerificationButton.userInteractionEnabled = YES;
                [weakSelf.sendVerificationButton setTitleColor:RGBCOLOR_HEX(0x0093FF) forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout % 60;
            if (seconds == 0) {
                seconds = 60;
            }
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf.sendVerificationButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                weakSelf.sendVerificationButton.userInteractionEnabled = NO;
                [weakSelf.sendVerificationButton setTitleColor:UIColor.auxiliaryTextLight forState:UIControlStateNormal];
                
            });
            timeout--;
        }
    });
    dispatch_resume(weakSelf.timer);
}
/**
 *  @brief  验证手机号
 *  @param sender id类型参数
 */
- (void)verificationButtonClicked:(id)sender {
    
    //textField的验证
    self.verificationButton.enabled = NO;
    if (![self.phoneView.contentTexF.text isNonEmpty])
    {
        self.verificationButton.enabled = YES;
        [self toast:@"手机号不能为空"];
        return;
    }
    else if (![NSString isPureInt:self.phoneView.contentTexF.text])
    {
        self.verificationButton.enabled = YES;
        [self toast: @"请输入正确的手机号码"];
        return;
    }
    if (![self.codeView.contentTexF.text isNonEmpty]) {
        self.verificationButton.enabled = YES;
        [self toast:@"验证码不能为空"];
        return;
    }
    //收起键盘
    [self.view endEditing:YES];
    NSString *phoneStr = [NSString stringWithFormat:@"%@-%@",self.phoneView.quhaoLabel.text,self.phoneView.contentTexF.text];
    __weak __typeof(self)weakSelf = self;
    [self showLoading:nil];
    [GMSignInManager bindAccount:(ALSignInTypePhone) email:nil phone:phoneStr code:self.codeView.contentTexF.text userId:[GMLoginManager shareInstance].user.userId finishBlock:^(NSString *message, BOOL success, id data) {
        [weakSelf hideLoading];
        [weakSelf toast:message];
        weakSelf.verificationButton.enabled = YES;
        if (success)
        {
            if (weakSelf.removeTipBlock != nil) {
                weakSelf.removeTipBlock();
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            
        }
    }];
    
    //    //bind_type   0->修改联系人手机号   1->绑定手机号
    //    NSString *numberWithAreaCode = [NSString stringWithFormat:@"%@%@", _areaCodeLabel.text, self.phoneTF.text];
    //    NSDictionary * dic = @{@"phone":numberWithAreaCode,
    //                           @"bind_type":@(1),
    //                           @"active_code":self.verificationTF.text};
    //
    //    __weak typeof(self)self = self;
    //    [self showLoading:nil];
    //    [self.viewModel VerifyPhoneNumberWithParameters:dic successBlock:^(id responseObject) {
    //        self.verificationButton.enabled = YES;
    //        [self toast:responseObject[@"message"]];
    //
    //        // 隐藏键盘，避免不必要的bug发生
    //        [self.view endEditing:YES];
    //
    //        NSInteger error = [responseObject[@"error"] integerValue];
    //        if (error == 0) {
    //            [self successBindAccountPhone];
    //        }
    //    } failBlock:^(NSString *errorMsg) {
    //        self.verificationButton.enabled = YES;
    //        [self toast:@"绑定手机号失败,请检查网络"];
    //    }];
}
- (GMBindPhoneTextFView *)phoneView
{
    if (!_phoneView) {
        _phoneView = [[GMBindPhoneTextFView alloc] init];
        _phoneView.delegate = self;
        _phoneView.contentTexF.placeholder = @"请输入手机号码";
        _phoneView.icon.image = [UIImage imageNamed:@"me_bind_phone"];
        _phoneView.isChangeFrame = YES;
    }
    return _phoneView;
}

- (GMView *)verifyView
{
    if (!_verifyView) {
        _verifyView = [GMView new];
        _verifyView.backgroundColor = [UIColor whiteColor];
        [_verifyView addBottomLine];
    }
    return _verifyView;
}

- (GMBindPhoneTextFView *)codeView
{
    if (!_codeView) {
        _codeView = [[GMBindPhoneTextFView alloc] init];
        _codeView.delegate = self;
        _codeView.bottomView.hidden = YES;
        _codeView.icon.image = [UIImage imageNamed:@"me_bind_code"];
        _codeView.contentTexF.placeholder = @"请输入验证码";
        _codeView.isChangeFrame = NO;
    }
    return _codeView;
}

- (GMButton *)sendVerificationButton
{
    if (!_sendVerificationButton) {
        _sendVerificationButton = [GMButton buttonWithTitle:@"获取验证码" backgroundColor:nil titleFontSize:16 titleColor:RGBCOLOR_HEX(0x0093ff)];
        [_sendVerificationButton addTarget:self action:@selector(sendVerificationButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendVerificationButton;
}

- (GMButton *)verificationButton
{
    if (!_verificationButton) {
        _verificationButton = [GMButton buttonWithCustomType:GMButtonTypeGreenSemicircle];
        [_verificationButton setTitle:@"确定" forState:UIControlStateNormal];
        _verificationButton.titleLabel.font = [UIFont gmFont:16];
        [_verificationButton setBackgroundColor:RGBCOLOR_HEX(0x0093ff) forState:UIControlStateNormal];
        _verificationButton.clipsToBounds = YES;
        _verificationButton.layer.cornerRadius = 5;
        [_verificationButton addTarget:self action:@selector(verificationButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _verificationButton;
}

- (GMLabel *)tipLabel
{
    if (!_tipLabel) {
        _tipLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextLight fontSize:13];
        _tipLabel.text = @"绑定手机才能发布内容啦～";
    }
    return _tipLabel;
}

@end
