//
//  SelectHeadPortraitViewController.m
//  HWMSDKDemo
//
//

#import "SelectHeadPortraitViewController.h"
#import "GlobalHandlerImpl.h"
#import "SDKEnvConfig.h"

@interface SelectHeadPortraitViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UIImageView *headImgView;     /**< 头像视图 */
@property (nonatomic, copy) NSString *headImgPath;          /**< 头像路径 */
@end

@implementation SelectHeadPortraitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择头像";
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)setupViews {
    [super setupViews];
    UILabel *contentLabel = [[UILabel alloc] init];
    contentLabel.numberOfLines = 0;
    contentLabel.font = [UIFont systemFontOfSize:14];
    contentLabel.text = @"选择头像：选择相册头像\n下载头像：使用网络头像（\n上传头像：上传图片为个人头像\n拦截头像：使用图片拦截图片显示\n选择图片会重置图片路径";
    [self.view addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
    }];
    UIButton *selectImageBtn = [UIButton newButtonWithTitle:@"选择头像" fontSize:14];
    [selectImageBtn addTarget:self action:@selector(handelSelectHeadImage) forControlEvents:UIControlEventTouchUpInside];
    UIButton *downImageBtn = [UIButton newButtonWithTitle:@"下载头像" fontSize:14];
    [downImageBtn addTarget:self action:@selector(handelDownHeadImage) forControlEvents:UIControlEventTouchUpInside];
    UIButton *updateBtn = [UIButton newButtonWithTitle:@"上传头像" fontSize:14];
    [updateBtn addTarget:self action:@selector(handelUpdateHeadImage) forControlEvents:UIControlEventTouchUpInside];
    UIButton *setHeadImagebtn = [UIButton newButtonWithTitle:@"拦截头像" fontSize:14];
    [setHeadImagebtn addTarget:self action:@selector(handelSetHeadImage) forControlEvents:UIControlEventTouchUpInside];
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.spacing = 10.0;
    stackView.distribution = UIStackViewDistributionFillEqually;

    [stackView addArrangedSubview:selectImageBtn];
    [stackView addArrangedSubview:downImageBtn];
    [stackView addArrangedSubview:updateBtn];
    [stackView addArrangedSubview:setHeadImagebtn];

    [self.view addSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(contentLabel.mas_bottom).mas_offset(15);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(50);
    }];

    self.headImgView = [[UIImageView alloc] init];
    [self.view addSubview:self.headImgView];
    self.headImgView.backgroundColor = HexColor(0xE6E6FA);
    self.headImgView.image = [GlobalHandlerImpl sharedInstance].headImage;
    [self.headImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(stackView.mas_bottom).mas_offset(10);
        make.left.right.mas_equalTo(stackView);
        make.height.mas_equalTo(Screen_Width - 20);
    }];
}

#pragma mark - Event
/// 选择头像图片
- (void)handelSelectHeadImage {
    // 置空headImgPath
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}

/// 下载头像
- (void)handelDownHeadImage {
    NSString *imgUrl = @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605186516454&di=da6b9d3ce82a3d2d488e4dec4ec67d80&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F30%2F29%2F01300000201438121627296084016.jpg";
    NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
    UIImage *headImg = [UIImage imageWithData:imgData];
    self.headImgView.image = headImg;
    [self cacheImage:imgData];
}

/// 缓存头像
/// @param data 头像data
- (void)cacheImage:(NSData *)data {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [NSString stringWithFormat:@"%@/headImg", cachePath];
    NSFileManager *fileManger = [NSFileManager defaultManager];
    [fileManger createFileAtPath:filePath contents:data attributes:nil];
    self.headImgPath = filePath;
}

/// 上传头像图片
- (void)handelUpdateHeadImage {
    [[HWMBizSdk getBizOpenApi] uploadSelfAvatarWithFilePath:self.headImgPath callback:^(NSError * _Nullable error, id  _Nullable result) {
        if (error) {
            [UIUtil showMessage:[NSString stringWithFormat:@"上传失败 %zd %@", error.code, error.localizedDescription]];
        } else {
            [UIUtil showMessage:@"上传成功"];
        }
    }];
}

/// 设置自定义头像图片
- (void)handelSetHeadImage {
    if (![SDKEnvConfig sharedInstance].contactHeadPortrait) {
        [UIUtil showMessage:@"请在全局设置中打开定制联系人头像开关"];
        return;
    }
    [GlobalHandlerImpl sharedInstance].headImage = self.headImgView.image;
    [UIUtil showMessage:@"已设置拦截图片"];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info;
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *img = info[UIImagePickerControllerEditedImage];
        self.headImgView.image = img;
        NSData *imgData = UIImageJPEGRepresentation(img, 1);
        [self cacheImage:imgData];
    }];
}

@end
