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

#import "ALMeSettingsController.h"
#import "ALSelectCountryController.h"
#import "GMPhotoPickController.h"
#import "ALSelectCountryObject.h"
#import "ALMyCenterObject.h"
#import "ALUpLoadManager.h"

@interface ALMeSettingsController ()<GMPhotoPickDismissDelegate>
    
/** 头像 */
@property (nonatomic, strong) GMImageView *headIcon;
/** 装载昵称的view */
@property (nonatomic, strong) GMView *userNameView;
/** 昵称的label */
@property (nonatomic, strong) GMLabel *userNameLabel;
/** 昵称 */
@property (nonatomic, strong) GMTextField *nameTextField;
/** 选择国家的View */
@property (nonatomic, strong) GMView *countryView;
/** 选择国家额占位符 */
@property (nonatomic, strong) GMLabel *nameLabel;
/** 选择国家的右边箭头 */
@property (nonatomic, strong) GMButton *rightButton;
/** 退出登录按钮 */
@property (nonatomic, strong) GMButton *logoutButton;
/** ALSelectCountryObject */
@property (nonatomic, strong) ALSelectCountryArrayObject *countryObject;
/** 上传的头像的key */
@property (nonatomic, copy) NSString *iconKey;
/** 上传头像的image */
@property (nonatomic, strong) UIImage *iconImage;

@end

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

#pragma mark--setter
-(void)setCenterModel:(ALMyCenterObject *)centerModel
{
    _centerModel = centerModel;
    
    [self.headIcon sd_setImageWithURL:[NSURL URLWithString:centerModel.userInfo.icon] placeholderImage:[UIImage imageNamed:@"user_setter_default_icon_new"]];
    
    self.nameTextField.text = centerModel.userInfo.name;
}

- (void)setNav
{
    self.title = @"设置";
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationBar.rightTitle = @"保存";
    [self.navigationBar.rightButton setTitleColor:RGBCOLOR_HEX(0x2D9AFF) forState:(UIControlStateNormal)];

}
    
- (void)setUI
{
    [self.view addSubview:self.headIcon];
    [self.view addSubview:self.userNameView];
    [self.userNameView addSubview:self.nameTextField];
    [self.userNameView addSubview:self.userNameLabel];
    [self.view addSubview:self.countryView];
    [self.countryView addSubview:self.nameLabel];
    [self.countryView addSubview:self.rightButton];
    [self.view addSubview:self.logoutButton];
}
    
- (void)setLayout
{
    [self.headIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navigationBar.mas_bottom).offset(40);
        make.centerX.mas_equalTo(0);
        make.width.height.mas_equalTo(110);
    }];
    
    [self.userNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headIcon.mas_bottom).offset(47);
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(32);
    }];
    
    [self.userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(35);
    }];
        
    [self.nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.mas_equalTo(0);
        make.left.equalTo(self.userNameLabel.mas_right).offset(10);
    }];
        
    [self.countryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameTextField.mas_bottom).offset(17);
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(32);
    }];
        
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
    }];
        
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.centerY.equalTo(self.nameLabel.mas_centerY);
    }];
        
    [self.logoutButton 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);
    }];
    
    //先给model进行赋值，防止没有选择的时候直接点击保存block回调中model为空的情况
    if ([GMLoginManager shareInstance].user.countryId) {
        self.countryObject.id = [GMLoginManager shareInstance].user.countryId;
        self.countryObject.name = [GMLoginManager shareInstance].user.countryName;
        self.countryObject.language = [GMLoginManager shareInstance].user.language;
    }
}
    
#pragma mark--delegate
    
#pragma mark - GMPhotoPickDismissDelegate
- (void)dismissPhotoPick:(NSArray *)images
{
    if (images.count == 1)
    {
        self.headIcon.image = images.firstObject;
        self.iconImage = images.firstObject;
    }
}
#pragma mark--click Method
    
#pragma mark--上传头像
- (void)editPortrait
{
    GMPhotoPickController *controller = [[GMPhotoPickController alloc] initWithMaxPhotoCount:1];
    controller.dismissDelegate = self;
    controller.root.singleSelection = YES;
    [self presentViewController:controller animated:YES completion:NULL];
}
    
#pragma mark--退出登录
- (void)logoutButtonClick: (GMButton *)button
{
    [[GMLoginManager shareInstance] shouldLogout];
}
    
#pragma mark--选择国家
- (void)clickCountry
{
    ALSelectCountryController *countryCodeVC = [[ALSelectCountryController alloc] init];
    
    __weak __typeof(self)weakSelf = self;
    countryCodeVC.returnCountryCodeBlock = ^(ALSelectCountryArrayObject *model) {
        weakSelf.nameLabel.text = model.name;
        weakSelf.nameLabel.textColor = UIColor.headlineText;
        weakSelf.countryObject = model;
    };
    [self pushViewController:countryCodeVC];
}

#pragma mark--保存Method

- (void)rightButtonClicked:(OCNavigationBarButton *)button;
{
    __weak typeof(self)weakSelf = self;
    [self showLoading:nil];
    //用户是否选择头像
    if(self.iconImage)
    {
        [[ALUpLoadManager shareInstance] setImage:self.iconImage  getTokenType:GetTokenTypeImage fileSuffix:nil block:^(NSString *url) {
            weakSelf.iconKey = url;
            [weakSelf pushMethod];
        } failBlock:^(NSString *message) {
            [weakSelf pushMethod];
        }];
    }
    else
    {
        [self pushMethod];
    }
}
/** 上传操作 */
- (void)pushMethod
{
    __weak __typeof(self)weakSelf = self;

    if (self.nameTextField.text.length>0 && self.countryObject.id.length>0)
    {
        NSDictionary *params = @{
                                 @"country_id":self.countryObject.id,
                                 @"nick_name":SafeString(self.nameTextField.text),
                                 @"profile_pic": SafeString(self.iconKey),
                                 @"user_id":@([GMLoginManager shareInstance].user.userId)
                                 };
        [GMNetworking requestOCWithApi:API_USER_SETINFO method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
            [weakSelf hideLoading];
            [weakSelf toast:response.message];
            
            if (response.isSuccess)
            {
                NSDictionary *dic = (NSDictionary *)response.data;
                WMUser *user = [GMLoginManager shareInstance].user;
                user.language = weakSelf.countryObject.language;
                user.countryName = weakSelf.countryObject.name;
                user.countryId = weakSelf.countryObject.id;
                user.nickName = SafeString(dic[@"nick_name"]);
                user.portrait = SafeString(dic[@"profile_pic"]);
                [weakSelf saveUser:user];
                //刷新个人中心页面
                if ([self.delegate respondsToSelector:@selector(refreshUserInfoMethod)]) {
                    [self.delegate refreshUserInfoMethod];
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            else
            {
            }
        }];
    }
    else
    {
        [self toast:@"请您填写完整信息"];
    }
}

- (void)saveUser:(WMUser *)user {
    
    //user属于用户重要数据，如果存储在沙河cache目录下，当系统内存紧张时候，系统可能会删除user数据，所以必须存储在Document目录下
    [GMCache storeObjectAtDocumentPathWithkey:@"userKey" object:user block:nil];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //收起键盘
    [self.view endEditing:YES];
}
    
#pragma mark--Getter and Setter Method
    
- (GMImageView *)headIcon
{
    if (!_headIcon)
    {
        _headIcon = [[GMImageView alloc] init];
        UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(editPortrait)];
        [_headIcon addGestureRecognizer:tapGest];
        _headIcon.userInteractionEnabled = YES;
        _headIcon.layer.cornerRadius = 55.0f;
        _headIcon.layer.masksToBounds = YES;
        _headIcon.contentMode = UIViewContentModeScaleAspectFit;
        _headIcon.image = [UIImage imageNamed:@"user_setter_default_icon_new"];
    }
    return _headIcon;
}
    
- (GMTextField *)nameTextField
{
    if (!_nameTextField)
    {
        _nameTextField = [[GMTextField alloc] init];
        _nameTextField.font = [UIFont systemFontOfSize:16];
//        [_nameTextField addBottomLine];
        _nameTextField.placeholder = @"请输入昵称";
        _nameTextField.textAlignment = NSTextAlignmentRight;
    }
    return _nameTextField;
}
- (ALSelectCountryArrayObject *)countryObject
{
    if (!_countryObject) {
        _countryObject = [[ALSelectCountryArrayObject alloc]init];
    }
    return _countryObject;
}

- (GMView *)countryView
{
    if (!_countryView)
    {
        _countryView = [[GMView alloc] init];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCountry)];
        [_countryView addGestureRecognizer:tap];
        [_countryView addBottomLine];
    }
    return _countryView;
}
    
- (GMLabel *)nameLabel
{
    if (!_nameLabel)
    {
        _nameLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextExtraLight fontSize:16];
        WMUser *user = [GMLoginManager shareInstance].user;
        NSLog(@"%@",user.countryName);
        if ([GMLoginManager shareInstance].user.countryName)
        {
            _nameLabel.text = [GMLoginManager shareInstance].user.countryName;
            _nameLabel.textColor = UIColor.headlineText;
        }
        else
        {
            _nameLabel.text = @"请选择国家";
        }
        
        
    }
    return _nameLabel;
}
    
- (GMButton *)rightButton
{
    if (!_rightButton)
    {
        _rightButton = [GMButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setBackgroundImage:[UIImage imageNamed:@"right_arrow"] forState:UIControlStateNormal];
    }
    return _rightButton;
}
    
- (GMButton *)logoutButton
{
    if (!_logoutButton)
    {
        _logoutButton = [GMButton buttonWithCustomType:GMButtonTypeGraySemicircleBorder];
        [_logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        _logoutButton.titleLabel.font = [UIFont gmFont:16];
        [_logoutButton setBackgroundColor:UIColor.auxiliaryTextExtraLight forState:UIControlStateNormal];
        [_logoutButton setAlpha:0.5];
        [_logoutButton setTitleColor:UIColor.auxiliaryTextLight forState:UIControlStateNormal];
        _logoutButton.clipsToBounds = YES;
        [_logoutButton addTarget:self action:@selector(logoutButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _logoutButton;
}

- (GMLabel *)userNameLabel
{
    if (!_userNameLabel) {
        _userNameLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextExtraLight fontSize:16];
        _userNameLabel.text = @"昵称";
    }
    return _userNameLabel;
}

- (GMView *)userNameView
{
    if (!_userNameView)
    {
        _userNameView = [[GMView alloc] init];
        [_userNameView addBottomLine];
    }
    return _userNameView;
}

@end
