//
//  MyHeaderVC.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/4/7.
//  Copyright © 2016年 Mac Book DQ02. All rights reserved.
//  

#import "MyHeaderVC.h"
#import "Singleton.h"
#import "AFNetworking.h"


#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define KMargin 40
#define kHeight 40
#define HeightWidth kScreenWidth*0.5

@interface MyHeaderVC () <UINavigationControllerDelegate,UIImagePickerControllerDelegate> {
    Singleton *singleton;
    NSData *data;
}

//背景图片
@property (nonatomic, strong) UIImageView *bgImageView;
//获取图库图片
@property (nonatomic, strong) UIButton *mapStorageBtn;
//拍照获取图片
@property (nonatomic, strong) UIButton *photographBtn;

@property (nonatomic, strong) UIImageView *imageView;
//打开相册提示框
@property (nonatomic, strong) UIAlertController *alertVC;
//图片二进制保存路径
@property (nonatomic ,strong) NSString *filePath;
//用于保存图片
@property (nonatomic, strong) UIImage *image;

@end

@implementation MyHeaderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建单例
    singleton = [Singleton defaultSingleton];
    self.navigationItem.title = @"我的头像";
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
//    //改变字体颜色.
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
    
    [Manager setNavi:self.navigationController.navigationBar];
    
    
#pragma - 设置导航栏左边的按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBarBtnItemIsClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
#pragma UI布局背景图片
    //设置背景图片
    _bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"headback.jpg"]];
    _bgImageView.frame = [UIScreen mainScreen].bounds;
    _bgImageView.userInteractionEnabled = YES;
    [self.view addSubview:_bgImageView];
    
    //获取图库图片Btn
    _mapStorageBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _mapStorageBtn.frame = CGRectMake(KMargin, KMargin + 64, kScreenWidth - 2*KMargin, kHeight);
     [_mapStorageBtn setImage:[UIImage imageNamed:@"fromimage"] forState:UIControlStateNormal];
    [_mapStorageBtn.layer setMasksToBounds:YES];
    [_mapStorageBtn.layer setCornerRadius:5];
    [_mapStorageBtn addTarget:self action:@selector(mapStorageBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [_bgImageView addSubview:_mapStorageBtn];
    
    //拍照获取图片Btn
    _photographBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _photographBtn.frame = CGRectMake(KMargin, CGRectGetMaxY(_mapStorageBtn.frame) + KMargin/2, kScreenWidth - 2*KMargin, kHeight);
    [_photographBtn setImage:[UIImage imageNamed:@"fromcamera"] forState:(UIControlStateNormal)];
    [_photographBtn.layer setMasksToBounds:YES];
    [_photographBtn.layer setCornerRadius:5];
    [_photographBtn addTarget:self action:@selector(photographBtnBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [_bgImageView addSubview:_photographBtn];
    
    //imageView用于存放从手机相册或拍照中获取的相片
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - HeightWidth)/2.0, CGRectGetMaxY(_photographBtn.frame) + KMargin, HeightWidth, HeightWidth)];
    NSLog(@"sington.head =%@", singleton.headImgUrl);
    //从文件中读取内容（读取二进制数据）
    if (singleton.headImgUrl == nil) {
        
        [self.imageView setImage:[UIImage imageNamed:@"head.png"]];
        
    } else {
         __block NSData *headData;
        dispatch_async(dispatch_queue_create("login", NULL), ^{
            headData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", localRequestUrl,singleton.headImgUrl]]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.imageView setImage:[UIImage imageWithData:headData]];
            });
        });

        
    }
    
//    NSData *contentData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://gwms.517gts.com%@", singleton.headImgUrl]]];
//    [self.imageView setImage:savedImage];

    //设置中点值
//    _imageView.center = CGPointMake(kScreenWidth/2.0, 0);
    //注: 图片圆角,需要开启切除模式.
    _imageView.layer.cornerRadius = HeightWidth / 2.0;
    _imageView.clipsToBounds = YES;
    [_bgImageView addSubview:_imageView];
    
}

#pragma mark - 导航栏左边按钮被点击
- (void)leftBarBtnItemIsClicked:(UIBarButtonItem *)sender {
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

#pragma mark - 获取图库图片Btn被点击
- (void)mapStorageBtnIsClicked:(UIButton *)sender {
    //从手机相册中选择头像
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - 拍照获取图片Btn被点击
- (void)photographBtnBtnIsClicked:(UIButton *)sender {
//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//        self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
}


//-(UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
//    UIImage *newImage = nil;
//    CGSize imageSize = sourceImage.size;
//    CGFloat width = imageSize.width;
//    CGFloat height = imageSize.height;
//    CGFloat targetWidth = size.width;
//    CGFloat targetHeight = size.height;
//    CGFloat scaleFactor = 0.0;
//    CGFloat scaledWidth = targetWidth;
//    CGFloat scaledHeight = targetHeight;
//    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
//    
//    if(CGSizeEqualToSize(imageSize, size) == NO){
//        
//        CGFloat widthFactor = targetWidth / width;
//        CGFloat heightFactor = targetHeight / height;
//        
//        if(widthFactor > heightFactor){
//            scaleFactor = widthFactor;
//            
//        }
//        else{
//            
//            scaleFactor = heightFactor;
//        }
//        scaledWidth = width * scaleFactor;
//        scaledHeight = height * scaleFactor;
//        
//        if(widthFactor > heightFactor){
//            
//            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
//        }else if(widthFactor < heightFactor){
//            
//            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
//        }
//    }
//    
//    UIGraphicsBeginImageContext(size);
//    
//    CGRect thumbnailRect = CGRectZero;
//    thumbnailRect.origin = thumbnailPoint;
//    thumbnailRect.size.width = scaledWidth;
//    thumbnailRect.size.height = scaledHeight;
//    
//    [sourceImage drawInRect:thumbnailRect];
//    
//    newImage = UIGraphicsGetImageFromCurrentImageContext();
//    if(newImage == nil){
//        NSLog(@"scale image fail");
//    }
//    
//    UIGraphicsEndImageContext();
//    return newImage;
//}



#pragma mark - UIImagePickerControllerDelegate 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]) {
        //先把图片转成NSData
        self.image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
//        if (UIImagePNGRepresentation(self.image) == nil) {
//            data = UIImageJPEGRepresentation(self.image, 0.3);
//            NSLog(@"12344%@", data);
//        }
//        else {
//            data = UIImageJPEGRepresentation(self.image, 0.3);
//            data = UIImagePNGRepresentation(self.image);
//            NSLog(@"%@", data);
//        }
        
//        [self imageCompressForSize:self.image targetSize:CGSizeMake(300, 300)];
        
        data = UIImageJPEGRepresentation(self.image, 0.2);

        NSLog(@"12344%@", data);
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        NSLog(@"filepath = %@",DocumentsPath);
        //得到选择图片后，沙盒中图片的完整路径
        self.filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        //单例保存头像存储路径
        singleton.headImgUrl = self.filePath;
        NSLog(@"headPath:%@", self.filePath);
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        //拍照 或 从手机相册中获取相片后，给imageView赋值
        self.imageView.image = self.image;
    }
    
    //发送通知给LeftVC和MyVC, 更换头像
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeHeaderImage" object:nil];

    
    //NSData *base_data = [[NSData alloc] initWithBase64EncodedData:data options:NSDataBase64DecodingIgnoreUnknownCharacters];
//    NSLog(@"")
    
    NSString *base_data = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    //像服务器发送数据
    NSDictionary *dicx;
    dicx = @{@"photo" : base_data, @"userId" : singleton.userid, @"sesskey" : singleton.sesskey};
    //    [MBProgressHUD showMessage:@"正在加载"];
    // 1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/user/file/base64_upload_image",localRequestUrl];
    // 2.发送POST请求
    [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:%@", responseObject);
        NSString *str_responseObject = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        singleton.headImgUrl = str_responseObject;
        NSLog(@"headImgUrl = %@",singleton.headImgUrl);
        //发送通知给LeftVC, 更换头像
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeMyVCHeaderImage" object:nil];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //弹出提示框 “上传头像失败”
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"上传头像失败！" message:@"请重新上传" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertVc addAction:action];
        [self presentViewController:alertVc animated:YES completion:nil];
        
    }];
    
    
}





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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//self.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//if (picker.sourceType == UIImagePickerControllerSourceTypeCamera || picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
//    NSData *data = [NSData data];
//    if (UIImagePNGRepresentation(self.image) == nil) {
//        data = UIImageJPEGRepresentation(self.image, 1.0);
//    }
//    else {
//        data = UIImagePNGRepresentation(self.image);
//    }
//    
//    //图片保存的路径
//    //这里将图片放在沙盒的documents文件夹中
//    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    
//    //文件管理器
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    
//    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
//    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
//    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
//    
//    //得到选择图片后，沙盒中图片的完整路径
//    self.filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
//    //单例保存头像存储路径
//    singleton.headPath = self.filePath;
//    //关闭相册界面
//    [picker dismissViewControllerAnimated:YES completion:nil];
//    
//    //拍照 或 从手机相册中获取相片后，给imageView赋值
//    self.imageView.image = self.image;
//}


//清除缓存
//dispatch_async(
//               dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//               , ^{
//                   NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
//                   
//                   NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//                   NSLog(@"files :%d",[files count]);
//                   for (NSString *p in files) {
//                       NSError *error;
//                       NSString *path = [cachPath stringByAppendingPathComponent:p];
//                       if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
//                           [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
//                       }
//                   }
//                   [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nilwaitUntilDone:YES];});
//
//-(void)clearCacheSuccess
//{
//    NSLog(@"清理成功");
//}


@end
