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

#import "ALChangeUserIconView.h"
#import "GMPhotoPickController.h"

@interface ALChangeUserIconView()<GMPhotoPickDismissDelegate>
@property (nonatomic, strong) GMImageView *imageView;
@end

@implementation ALChangeUserIconView

- (void)setup {
    
    [super setup];
    
    GMImageView *imageView = [[GMImageView alloc] initWithImage:[UIImage
                                                                 imageNamed:@"user_setter_default_icon_new"]];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 150/2;
    imageView.userInteractionEnabled = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [imageView setImageWithUrlString:[GMLoginManager shareInstance].user.portrait placeHolder:@"user_setter_default_icon_new"];
    [self addSubview:imageView];
    
    GMButton *changeButton = [GMButton buttonWithTitle:@"更换"
                                       backgroundColor:RGBCOLOR_HEX(0xE9F6FF)
                                         titleFontSize:12 titleColor:RGBCOLOR_HEX(0x0093FF)];
    [changeButton addTarget:self action:@selector(changeUserImageClick) forControlEvents:(UIControlEventTouchUpInside)];
    changeButton.layer.masksToBounds = YES;
    changeButton.layer.cornerRadius = 14.0f;
    [self addSubview:changeButton];
    
    __weak __typeof(self)weakSelf = self;
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(150, 150));
        make.centerX.mas_equalTo(weakSelf.mas_centerX);
        make.top.mas_equalTo(0);
    }];
    
    [changeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 28));
        make.right.bottom.equalTo(imageView);
    }];
    self.imageView = imageView;
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserImageClick)];
    [self addGestureRecognizer:gesture];
}


// 更改用户头像
- (void)changeUserImageClick {
    GMPhotoPickController *controller = [[GMPhotoPickController alloc] initWithMaxPhotoCount:1];
    controller.dismissDelegate = self;
    controller.root.singleSelection = YES;
    [[AppDelegate shareInstance].window.rootViewController presentViewController:controller animated:YES completion:NULL];
}

#pragma mark - GMPhotoPickDismissDelegate
- (void)dismissPhotoPick:(NSArray<UIImage *> *)images {
    
    if (images.count > 0) {
        UIImage *image = images[0];
        self.imageView.image = image;
        if (self.iconChangeBlock) {
            self.iconChangeBlock(image);
        }
    }
}

@end
