//
//  XVRegisterViewController.m
//  fastservice
//
//  Created by xuning on 2/4/24.
//  Copyright © 2024 FastService. All rights reserved.
//

#import "XVRegisterViewController.h"
#import "XVInputFieldView.h"
#import "XVWebViewController.h"

@interface XVRegisterViewController ()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIButton *accountButton;

@property (nonatomic, strong) UIButton *registerButton;

// 手机号
@property (nonatomic, strong) XVInputFieldView *phoneView;

@property (nonatomic,copy) NSString *phone;

// 验证码
@property (nonatomic, strong) XVInputFieldView *smsCodeView;
// 图片验证码
@property (nonatomic, strong) XVInputFieldView *imgCodeView;

@property (nonatomic,copy) NSString *imgCode;
// 密码
@property (nonatomic, strong) XVInputFieldView *passwordView;

@property (nonatomic, copy) NSString *uuid; //
@property (nonatomic, strong) YYLabel *protocolLabel;

@property (nonatomic,strong ) NSTimer *timer;

@property (nonatomic,assign) BOOL privacy;
@end

@implementation XVRegisterViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setNavigationBarsetBackgroundColor:COLOR_THEMEGRENN];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavigationBarsetBackgroundColor:COLOR_THEMEGRENN];
    self.view.backgroundColor =  COLOR_THEMEGRENN;
    
    [self setupUI];
    
    [self loadPicVerfData];
    
    [self updateDeviceToken];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
    //ctrl ＋ i 格式化
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:IMG(@"iconPark-left 1 Copy 1")];

}
- (void)back {
    [self dismissViewControllerAnimated:YES completion:^{
        [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    }];

}

- (BOOL)fd_interactivePopDisabled {
    return YES;
}

- (void)setupUI {
    
    [self.view addSubview:self.containerView];
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).mas_offset((120-KTOP_HEIGHT)*heightScale);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    [self.view layoutIfNeeded];
    [self.containerView addRoundedCorners:UIRectCornerTopLeft | UIRectCornerTopRight withRadii:CGSizeMake(50, 50)];
    
    [self.containerView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.containerView).mas_offset(37);
        make.top.mas_equalTo(self.containerView).mas_offset(108*heightScale);
    }];
    
    [self.containerView addSubview:self.accountButton];
    [self.accountButton sizeToFit];
    [self.accountButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.containerView).mas_offset(-31);
        make.centerY.mas_equalTo(self.titleLabel);
    }];
    
    [self.containerView addSubview:self.phoneView];
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).mas_offset(58*heightScale);
        make.left.mas_equalTo(self.containerView).mas_offset(30);
        make.right.mas_equalTo(self.containerView).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];
    
    [self.containerView addSubview:self.imgCodeView];
    [self.imgCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.phoneView.mas_bottom).mas_offset(31*heightScale);
        make.left.mas_equalTo(self.containerView).mas_offset(30);
        make.right.mas_equalTo(self.containerView).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];

    [self.containerView addSubview:self.smsCodeView];
    [self.smsCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.imgCodeView.mas_bottom).mas_offset(31*heightScale);
        make.left.mas_equalTo(self.containerView).mas_offset(30);
        make.right.mas_equalTo(self.containerView).mas_offset(-30);
        make.height.mas_equalTo(40);
    }];
    

    
    [self.containerView addSubview:self.passwordView];
    [self.passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.smsCodeView.mas_bottom).mas_offset(31*heightScale);
        make.left.mas_equalTo(self.containerView).mas_offset(30);
        make.right.mas_equalTo(self.containerView).mas_offset(-30);
        make.height.mas_equalTo(30);
    }];
    
    
    
    [self.containerView addSubview:self.protocolLabel];
    [self.protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.containerView.mas_safeAreaLayoutGuideBottom).mas_offset(-55*widthScale);
        make.left.right.mas_equalTo(self.containerView);
    }];

    
    [self.containerView addSubview:self.registerButton];
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.containerView).mas_offset(66);
        make.right.mas_equalTo(self.containerView).mas_offset(-66);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(self.protocolLabel.mas_top).mas_offset(-72*heightScale);
    }];
    kViewBorderRadius(self.registerButton, 10, 0, [UIColor clearColor]);
    

}
- (void)agreeClick:(UIButton *)button {
    button.selected = !button.selected;
    self.privacy = button.selected;
}

- (void)loadPicVerfData{
    
    self.uuid = [AppTools kfwUUID];
    
    NSString *urlStr = S(@"%@%@?uu_id=%@",[AFNetworkingClient baseURLString],SS_SMS_PIC_CODE,self.uuid);
    [self.imgCodeView.picCodeButton sd_setImageWithURL:URL(urlStr) forState:UIControlStateNormal placeholderImage:[UIImage new] options:SDWebImageRefreshCached];
}
//更新上传DeviceToken
- (void)updateDeviceToken{
    [[AFNetworkingClient sharedClient] runPost:SS_SMS_CODEW parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    } failure:^(NSURLSessionDataTask *task, NSError *error){
    }];
}

// 获取验证码逻辑
- (void)loadVerifycode:(int)voice{
    
    if (StringIsNullOrEmpty(self.phone)) {
        [MBProgressHUD showMessage:@"请填写手机号"];
        return;
    }
    
    if (![AppTools isValidMobeilTelWithString:self.phone]) {
        return;
    }
    
    
    if (StringIsNullOrEmpty(self.imgCode)) {
        [MBProgressHUD showMessage:@"请输入图片验证码"];
        return;
    }
    
    [self seconderyValidate:nil voice:voice];
}

//二次验证 发送验证码
- (void)seconderyValidate:(NSDictionary *)result voice:(int)voice{
    NSMutableDictionary *pDic = [NSMutableDictionary dictionaryWithDictionary:result];
    [pDic setAnyObject:self.phone forKey:@"mobile"];
    [pDic setObject:@(0) forKey:@"type"]; //0 注册或者登陆  1 忘记密码
    [pDic setObject:@(voice) forKey:@"voice"];
    [AppTools ccodeBase64Encode:pDic];
    [pDic setAnyObject:self.uuid forKey:@"uu_id"];
    [pDic setAnyObject:self.imgCode forKey:@"imageCode"];
    showIndicator(YES, @"获取中", nil);
    IMP_BLOCK_SELF(XVRegisterViewController);
    [[AFNetworkingClient sharedClient] runPost:SS_SMS_PIC_CODE parameters:pDic success:^(NSURLSessionDataTask *task, id responseObject) {
        if (StringNotNullAndEmpty([responseObject objectForKey:@"respcd"]) &&[[responseObject objectForKey:@"respcd"] isEqualToString:@"0000"]) {
            
            block_self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:block_self selector:@selector(verCodeAciton) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:block_self.timer forMode:NSRunLoopCommonModes];
            [block_self.timer fire];
            [MBProgressHUD showMessage:@"请查收"];
        }else{
            [MBProgressHUD showMessage:[responseObject objectForKey:@"resperr"]];
        }
        showIndicator(NO, nil, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        showAlertMessage(@"获取异常!");
        showIndicator(NO, nil, nil);
    }];
}

//六十秒倒计时
- (void)verCodeAciton{
    static int a = 60;
    self.smsCodeView.smsCodeButton.enabled = NO;
    [self.smsCodeView.smsCodeButton setTitle:S(@"%ds",a) forState:UIControlStateNormal];
    
    //语音标签
    self.smsCodeView.voiceLabel.hidden = NO;
    self.smsCodeView.voiceLabel.text = S(@"收不到验证码？%d秒后来个语音验证码吧",a);
    
    a -= 1;
    if (a == -1) {
        [self.smsCodeView.smsCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.smsCodeView.smsCodeButton.enabled = YES;
        self.smsCodeView.smsCodeButton.backgroundColor = COLOR_THEMEGRENN;
        a = 60;
        
        self.smsCodeView.voiceLabel.userInteractionEnabled = YES;
        self.smsCodeView.voiceLabel.text = @"收不到验证码？来个语音验证吧";
        self.smsCodeView.voiceLabel.textColor = BLUE_COLOR;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lbVoiceTapClick:)];
        [self.smsCodeView.voiceLabel addGestureRecognizer:tap];
    }
    
}

//语音验证码
- (void)lbVoiceTapClick:(UITapGestureRecognizer *)tap{
    //图形验证
    [self loadVerifycode:1];
}

- (void)registerButtonClick {
    
    NSMutableDictionary * pdic = [[NSMutableDictionary alloc]init];
    
    
    if (StringIsNullOrEmpty(self.phoneView.textField.text)) {
        [MBProgressHUD showMessage:@"请填入手机号"];
        return;
    }
    if (![AppTools isValidMobeilTelWithString:self.phoneView.textField.text]) {
        return;
    }
    if (StringIsNullOrEmpty(self.smsCodeView.textField.text)) {
        [MBProgressHUD showMessage:@"请填入验证码"];
        return;
    }
    
    if (StringIsNullOrEmpty(self.passwordView.textField.text)) {
        [MBProgressHUD showMessage:@"请输入密码"];
        return;
    }
    if (!self.privacy) {
        [MBProgressHUD showMessage:@"请阅读并同意快服务骑士协议及隐私协议"];
        return;
    }

    
    [pdic setAnyObject:self.phoneView.textField.text forKey:@"mobile"];
    [pdic setAnyObject:@"" forKey:@"nickname"];
    [pdic setAnyObject:self.passwordView.textField.text forKey:@"password"];
    [pdic setAnyObject:self.smsCodeView.textField.text forKey:@"pin"];
    
    [pdic setObject:S(@"%f", [AppConfig getLocationCoordinate].latitude) forKey:@"user_lat"];
    [pdic setObject:S(@"%f", [AppConfig getLocationCoordinate].longitude) forKey:@"user_lng"];
    
    [pdic setObject:@"" forKey:@"clientid"];
    
    [pdic setAnyObject:[AppConfig getLocationName] forKey:@"city"];
    [pdic setAnyObject:[AppConfig getDistrictName] forKey:@"district"];
    
    NSLog(@"%@",pdic);
    IMP_BLOCK_SELF(XVRegisterViewController);
    showIndicator(YES, @"注册中", nil);
    showFullView(YES, self);
    NSURLSessionTask * task2 = [[AFNetworkingClient sharedClient] runPost:SS_SIGN parameters:pdic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([MyNetWork isSuccessServerData:responseObject]) {
            
            
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)task.response;
            NSDictionary *dictionary = [httpResponse allHeaderFields];
            
            UserInfo * userInfo = [UserInfo mj_objectWithKeyValues:[responseObject objectForKey:@"data"]];
            
            userInfo.mobile = block_self.phoneView.textField.text;
            if (StringNotNullAndEmpty([dictionary objectForKey:@"Set-Cookie"])) {
                userInfo.cookie = [dictionary objectForKey:@"Set-Cookie"];
            }else{
                [TestClient dicMobClickStatistics:@"respNoCookie"];
            }
            
            [AppConfig setUser:userInfo];
            //环信登录
            NSString *spw = responseObject[@"data"][@"spw"];
            
            [MyNetWork easeLoginWithUsername:S(@"%d",userInfo.user_id) spw:spw];
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kAppUserLogin object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kAppSigin object:nil];
            
            [block_self back];
            
            showIndicator(NO, @"登录中", ^{
                [MBProgressHUD showMessage:[responseObject objectForKey:@"resperr"]];
            });
            
        }else{
            showIndicator(NO, @"登录中", ^{
                [MBProgressHUD showMessage:[responseObject objectForKey:@"resperr"]];
                
            });
        }
        showFullView(NO, block_self);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        showIndicator(NO, nil, nil);
        showFullView(NO, block_self);
    }];
    
}


- (UIView *)containerView {
    if(_containerView == nil) {
        _containerView = [[UIView alloc]init];
        _containerView.backgroundColor = [UIColor whiteColor];

    }
    return _containerView;
}
- (UILabel *)titleLabel {
    if(_titleLabel == nil) {
        _titleLabel = [[UILabel alloc]initWithText:@"注册骑手账号" textColor:F_3D3B4F_COLOR textAlignment:NSTextAlignmentLeft fontSize:24];
    }
    return _titleLabel;
}
- (UIButton *)accountButton {
    if(_accountButton == nil) {
        _accountButton = [[UIButton alloc]initWithTitle:@"我有账号" fontSize:14 titleColor:BLUE_COLOR normalImageName:@"right" selectedImgName:@"right" backgroundColor:[UIColor whiteColor]];
        [_accountButton setForceRightToLeft:0 forState:UIControlStateNormal];
        WS(weakSelf);
        [_accountButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(UIButton *sender) {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }];
    }
    return _accountButton;
}
//
- (XVInputFieldView *)phoneView {
    if(_phoneView == nil) {
        _phoneView = [[XVInputFieldView alloc]initWithType:InputTypeNumber placeholder:@"请输入手机号"];
        IMP_BLOCK_SELF(XVRegisterViewController)
        _phoneView.textEditingChanged = ^(NSString * _Nonnull obj) {
            block_self.phone = obj;
            if (StringIsNullOrEmpty(obj) || StringIsNullOrEmpty(block_self.imgCode)) {
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:BB_3_COLOR];
                
            }else{
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:COLOR_THEMEGRENN];
            }
        };
    }
    return _phoneView;
}
- (XVInputFieldView *)smsCodeView {
    if(_smsCodeView == nil) {
        _smsCodeView = [[XVInputFieldView alloc]initWithType:InputTypeSmsCode placeholder:@"请输入验证码"];
        IMP_BLOCK_SELF(XVRegisterViewController)
        [_smsCodeView.smsCodeButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            [block_self loadVerifycode:0];
        }];
    }
    return _smsCodeView;
}

- (XVInputFieldView *)imgCodeView {
    if(_imgCodeView == nil) {
        _imgCodeView = [[XVInputFieldView alloc]initWithType:InputTypePicCode placeholder:@"请输入图片验证码"];
        IMP_BLOCK_SELF(XVRegisterViewController)
        [_imgCodeView.picCodeButton addBlockForControlEvents:(UIControlEventTouchUpInside) block:^(id  _Nonnull sender) {
            [block_self loadPicVerfData];
        }];
        
        _imgCodeView.textEditingChanged = ^(NSString * _Nonnull obj) {
            block_self.imgCode = obj;
            if (StringIsNullOrEmpty(obj) || StringIsNullOrEmpty(block_self.phone)) {
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:BB_3_COLOR];
            }else{
                [block_self.smsCodeView.smsCodeButton setBackgroundColor:COLOR_THEMEGRENN];
            }
        };

    }
    return _imgCodeView;
}


- (XVInputFieldView *)passwordView {
    if(_passwordView == nil) {
        _passwordView = [[XVInputFieldView alloc]initWithType:InputTypePassword placeholder:@"请设置登录密码"];
    }
    return _passwordView;
}


- (UIButton *)registerButton {
    if(_registerButton == nil) {
        _registerButton = [[UIButton alloc]initWithTitle:@"注册" fontSize:16 titleColor:[UIColor whiteColor] bgColor:COLOR_THEMEGRENN];
        
        [_registerButton addTarget:self action:@selector(registerButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}


- (YYLabel *)protocolLabel {
    if(_protocolLabel == nil) {
        
        _protocolLabel = [[YYLabel alloc]init];
        
        NSMutableAttributedString *text = [NSMutableAttributedString new];
        UIFont *font = [UIFont systemFontOfSize:12];
        UIColor *color = [UIColor colorWithHexString:@"#737272"];

        // UIView attachment
        UIButton *selectButton = [[UIButton alloc]init];
        
        [selectButton setImage:IMG(@"order_check box") forState:UIControlStateNormal];
        [selectButton setImage:IMG(@"order_checkSelect") forState:UIControlStateSelected];
        [selectButton addTarget:self action:@selector(agreeClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [selectButton sizeToFit];
        selectButton.hitEdgeInsets = UIEdgeInsetsMake(-40, -40, -40, -40);
        NSMutableAttributedString *attachment = [NSMutableAttributedString attachmentStringWithContent:selectButton contentMode:UIViewContentModeBottom attachmentSize:selectButton.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
    
        [text appendAttributedString: attachment];
        
        IMP_BLOCK_SELF(XVRegisterViewController)
        NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:@" 我已阅读并同意"];
        str1.font = font;
        str1.color = color;
        
        [text appendAttributedString:str1];
        
        NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:@"《快服务服务者合作协议》"];
        str2.font = font;
        str2.color = BLUE_COLOR;

        YYTextHighlight *highlight = [YYTextHighlight new];
        
        highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            [block_self toWebView:SS_SERVICE_AGREEMENT name:@"骑士协议"];
        };
        [str2 setTextHighlight:highlight range:str2.rangeOfAll];
        
        
        [text appendAttributedString:str2];
        
        
        NSMutableAttributedString *str3 = [[NSMutableAttributedString alloc] initWithString:@"及"];
        str3.font = font;
        str3.color = color;
        
        [text appendAttributedString:str3];
        
        NSMutableAttributedString *str4 = [[NSMutableAttributedString alloc] initWithString:@"隐私协议"];
        str4.font = font;
        str4.color = BLUE_COLOR;

        YYTextHighlight *highlight1 = [YYTextHighlight new];
        
        highlight1.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            [block_self toWebView:SS_PRIVACY_COURIER name:@"隐私协议"];
        };
        [str4 setTextHighlight:highlight1 range:str4.rangeOfAll];
        
        
        [text appendAttributedString:str4];
        
        _protocolLabel.attributedText = text;
        _protocolLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    return _protocolLabel;
}

- (void)toWebView:(NSString *)url name:(NSString *)name {
    NSString * path = S(@"%@%@",[AFNetworkingClient baseURLString],url);
    XVWebViewController *web = [[XVWebViewController alloc]init];
    
    [web loadWebURLSring:path];
    
    [self.navigationController pushViewController:web animated:YES];
}


@end
