//
//  ALSetterUserInfoViewController.m
//  GMAlpha
//
//  Created by Mikasa on 2018/11/23.
//  Copyright © 2018 Gengmei. All rights reserved.
//
#import "ALSetterUserInfoViewController.h"
#import "ALSetterUserTitleView.h"
#import "ALChangeUserIconView.h"
#import "ALTextFieldEnterView.h"
#import "GMSignInManager.h"
#import "GMLoginManager.h"
#import "QNUploadManager.h"
#import "AppDelegate+ViewControl.h"
#import "ALUpLoadManager.h"
#import "ALFaceFittingManager.h"
#import "ALAgeSelectPickView.h"

@interface ALSetterUserInfoViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) ALTextFieldEnterView *nickNameField;
@property (nonatomic, strong) ALTextFieldEnterView *ageField;
@property (nonatomic, strong) GMButton *completeButton;
@property (nonatomic, copy) NSString *profile_pic;// 图片地址
@property (nonatomic, strong) UIImage *iconImage;//图片
@property (nonatomic, assign) BOOL uploadingImage;// 是否正在上传图片
@property (nonatomic, assign) BOOL needUploadUserInfo;// 是否需要上传用户信息
@property (nonatomic, copy) NSString *ageCode;
@property (nonatomic, copy) NSString *age;
@end


@implementation ALSetterUserInfoViewController

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

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

- (void)initController {
    
    [super initController];
    self.pageName = @"upload_avatar";
    // 多属性选择时需要隐藏导航栏，需要用到此属性
    self.controlNavigationByYou = NO;
    
    self.navigationBar.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    self.navigationBar.titleLabel.textColor = [UIColor colorWithWhite:0 alpha:0];
    self.navigationBar.isShowShadow = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupSubView];
}

- (void)setupSubView {
    ALSetterUserTitleView *titleView = [ALSetterUserTitleView new];
    [self.view addSubview:titleView];
    
    __weak __typeof(self)weakSelf = self;
    ALChangeUserIconView *changeIconView = [ALChangeUserIconView new];
    changeIconView.iconChangeBlock = ^(UIImage *image) {
        
        // 图片发生变化后需要重新上传
        if (weakSelf.iconImage != image) {
            
            weakSelf.profile_pic = @"";
            weakSelf.iconImage = image;
            [weakSelf uplodaImageToServer];
        }
    };
    [self.view addSubview:changeIconView];
    
    ALTextFieldEnterView *nickNameField = [[ALTextFieldEnterView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, 33) title:@"昵称"];
    nickNameField.placeholder = @"输入你的昵称";
    nickNameField.text = [GMLoginManager shareInstance].user.nickName;
    nickNameField.returnKeyType = UIReturnKeyNext;
    nickNameField.delegate = self;
    [self.view addSubview:nickNameField];
    
    ALTextFieldEnterView *ageField = [[ALTextFieldEnterView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, 33) title:@"年龄"];
    ageField.placeholder = @"输入你的年龄";
    ageField.userInteractionEnabled = NO;
    ageField.text = [GMLoginManager shareInstance].user.age;

    
    ageField.returnKeyType = UIReturnKeyDone;
    ageField.keyboardType = UIKeyboardTypeNumberPad;
    ageField.delegate = self;
    [self.view addSubview:ageField];
    self.ageField = ageField;
    
    UIView *clickView = [[UIView alloc] init];
    clickView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:clickView];
    UITapGestureRecognizer *tapgest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ageFieldClickMethod)];
    [clickView addGestureRecognizer:tapgest];
    clickView.frame = ageField.frame;

    // 完成
    GMButton *completeButton = [GMButton buttonWithTitle:@"完成" backgroundColor:RGBCOLOR_HEX(0x0093FF) titleFontSize:16 titleColor:UIColor.whiteColor];
    [completeButton setBackgroundColor:RGBCOLOR_HEX(0x99D4FF)  forState:UIControlStateDisabled];
    [completeButton addTarget:self action:@selector(completeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    completeButton.layer.masksToBounds = YES;
    completeButton.layer.cornerRadius = 21.0f;
    if ([ageField.text isNonEmpty] && [nickNameField.text isNonEmpty]) {
        completeButton.enabled = YES;
    } else {
        completeButton.enabled = NO;
    }
    [self.view addSubview:completeButton];
    [completeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_safeBottom).offset(-20);
        make.height.mas_equalTo(42);
        make.left.equalTo(self.view.mas_left).offset(30);
        make.right.equalTo(self.view.mas_right).offset(-30);
    }];
    
    
    CGFloat top = [AppDelegate navigation].navigationBar.height + UIView.safeAreaInsetsTop;
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(top);
        make.height.mas_equalTo(kUserTitleViewH);
    }];
    
    [changeIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleView.mas_bottom).offset(30);
        make.size.mas_equalTo(CGSizeMake(150, 150));
        make.centerX.mas_equalTo(weakSelf.view.mas_centerX);
    }];
    
    [nickNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.top.mas_equalTo(changeIconView.mas_bottom).offset(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(33);
    }];
    
    [ageField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.top.mas_equalTo(nickNameField.mas_bottom).offset(15);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(33);
    }];
    
    [completeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(40);
        make.bottom.mas_equalTo(-(UIView.safeAreaInsetsBottom + 30));
    }];
    [clickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.top.mas_equalTo(nickNameField.mas_bottom).offset(15);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(33);
    }];
    self.nickNameField = nickNameField;
    self.ageField = ageField;
    self.completeButton = completeButton;
    
}

- (void)completeButtonClick {
    
    [Phobos track:@"upload_avatar_click_done" attributes:@{@"page_name":@"upload_avatar"}];
    
    if (![self validateAge]) return;
    
    [GMHudModule showLoading:nil];
    
    self.needUploadUserInfo = YES;
    // 判断是否已经获取到图片地址，如没有优先进行图片上传
    if (self.iconImage && ![self.profile_pic isNonEmpty]) {
        [self uplodaImageToServer];
        return;
    } else {
        [self uploadUserInfoToServer];
    }
    
}

// 校验文本输入
- (BOOL)validateAge {
    NSString *age = self.ageField.text;
    if (age.length == 0) {
        [GMHudModule toast:@"年龄不能为空"];
        [self.ageField becomeFirstResponder];
        return NO;
    }
//    if (![self isValidateAge:age]) {
//        [GMHudModule toast: @"请输入正确的年龄"];
//        [self.ageField becomeFirstResponder];
//        return NO;
//    }
    return YES;
}

- (BOOL)isValidateAge:(NSString *)age {
    
    NSString *ageRegex = @"^(\\d|[1-9]\\d|200)$";
    NSPredicate *ageTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ageRegex];
    return [ageTest evaluateWithObject:age];
}

// 上传用户信息到服务端
- (void)uploadUserInfoToServer {
    
    __weak __typeof(self)weakSelf = self;
    WMUser *user = [GMLoginManager shareInstance].user;
    [GMSignInManager setUserProfileUserId:user.userId country_id:@"" nick_name:self.nickNameField.text profile_pic:self.profile_pic age:self.ageCode finishBlock:^(NSString *message, BOOL success, id data) {
        [GMHudModule hideLoading];
        if (success) {
            [GMLoginManager shareInstance].user.detail_setted = YES;
            [GMLoginManager shareInstance].user.ageCode = weakSelf.ageCode;
            [GMLoginManager shareInstance].user.age = weakSelf.age;
            [[GMLoginManager shareInstance] saveUser];
            [[AppDelegate shareInstance] enableShowNextRootView:[ALSetterUserInfoViewController class]];
            [ALFaceFittingManager shareInstance].isNeedRequest = YES;
        }
        weakSelf.needUploadUserInfo = NO;
    }];
    
}

// 上传图片到服务器
- (void)uplodaImageToServer {

    if (self.uploadingImage) return;
    
    self.uploadingImage = YES;
    __weak __typeof(self)weakSelf = self;
    ALUpLoadManager *uploadImage = [ALUpLoadManager new];
    [uploadImage setImage:self.iconImage getTokenType:GetTokenTypeImage fileSuffix:nil block:^(NSString *url) {
        weakSelf.profile_pic = url;
        weakSelf.uploadingImage = NO;
        // 图片上传完成后执行
        if (weakSelf.needUploadUserInfo) {
            [weakSelf uploadUserInfoToServer];
        }
    } failBlock:^(NSString *message) {
        weakSelf.uploadingImage = NO;
        // 图片上传完成后执行
        if (weakSelf.needUploadUserInfo) {
            [weakSelf uploadUserInfoToServer];
        }
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSString *text = textField.text;
    if (![text isNonEmpty]) {
        return NO;
    }
    [textField resignFirstResponder];
    if (textField == self.nickNameField) {
        [self ageFieldClickMethod];
    } else {
        [self completeButtonClick];
    }
    
    return YES;
}

- (void)ageFieldClickMethod {
    
    ALAgeSelectPickView *pickView =[[ALAgeSelectPickView alloc] init];
    __weak __typeof(self)weakSelf = self;
    pickView.ageBlock = ^(BOOL isChange, NSString *ageStr, NSString *ageCode) {
        if (isChange) {
            weakSelf.ageField.text = ageStr;
            weakSelf.age = ageStr;
            weakSelf.ageCode = ageCode;
            [self eventButtonEnable];
        }
    };    
    [AppDelegate.shareInstance.window addSubview:pickView];
}

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

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

- (void)eventButtonEnable {
    
    if ([self.nickNameField.text isNonEmpty] && [self.ageField.text isNonEmpty]) {
        self.completeButton.enabled = YES;
    } else {
        self.completeButton.enabled = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
