//
//  CameraView.m
//  Lighting
//
//  Created by mac on 16/5/24.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "CameraView.h"
#import "NSObject+UIImagePickerController.h"
#import "CustomUIImagePickerController.h"

@interface CameraView ()
{
    UIImagePickerController *_imagePickerController;
}

@end

@implementation CameraView

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _imagePickerController = [[CustomUIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
//    [_imagePickerController supportedInterfaceOrientations];
    [self initView];
    // Do any additional setup after loading the view.
}
-(void)initView
{
    self.subView=[[UIView alloc]init];
    self.subView.bounds=CGRectMake(0, 0, 300, 150);
    self.subView.center=self.view.center;
    self.subView.layer.masksToBounds = YES;
    self.subView.layer.cornerRadius = 10;
    self.subView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.subView];
    
    UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 300, 50)];
    [btn1 setTitle:@"拍照" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    btn1.titleLabel.textAlignment=NSTextAlignmentCenter;
    btn1.tag=101;
    [btn1 addTarget:self action:@selector(selectedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.subView addSubview:btn1];
    
    UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 50, 300, 50)];
    [btn2 setTitle:@"从相册中选取" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    btn2.titleLabel.textAlignment=NSTextAlignmentCenter;
    btn2.tag=102;
    [btn2 addTarget:self action:@selector(selectedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.subView addSubview:btn2];
    UIButton *btn3=[[UIButton alloc]initWithFrame:CGRectMake(0, 100, 300, 50)];
    [btn3 setTitle:@"取消" forState:UIControlStateNormal];
    [btn3 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    btn3.titleLabel.textAlignment=NSTextAlignmentCenter;
    btn3.tag=103;
    [btn3 addTarget:self action:@selector(selectedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.subView addSubview:btn3];

      //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(DismissScreenView:)];
    tap.delegate = self;
    tap.cancelsTouchesInView = NO;
    [[UIApplication sharedApplication].keyWindow addGestureRecognizer:tap];
}
-(void)selectedBtn:(UIButton*)sender
{
    switch (sender.tag) {
        case 101://拍照
        {
//            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//            if ([UIImagePickerController isSourceTypeAvailable:
//                              UIImagePickerControllerSourceTypePhotoLibrary]) {
//                      imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//                     imagePicker.delegate = self;
//                     [imagePicker setAllowsEditing:YES];
//                     UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
//                      self.popoverController = popover;
//                [self presentViewController:imagePicker animated:YES completion:nil];
////                    [self.popoverController presentPopoverFromRect:CGRectMake(0, 0, 800, 500) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
//                
//                 }
//            [self selectImageFromAlbum];
        }
            break;
        case 102://从相册中选取
        {
        
        }
            break;
        case 103://取消
        {
            [self DismissScreenView];
        }
            break;


            
        default:
            break;
    }
}
#pragma mark 从摄像头获取图片或视频
- (void)selectImageFromCamera
{
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    //录制视频时长，默认10s
    _imagePickerController.videoMaximumDuration = 15;
    
    //相机类型（拍照、录像...）字符串需要做相应的类型转换
    _imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
    
    //视频上传质量
    //UIImagePickerControllerQualityTypeHigh高清
    //UIImagePickerControllerQualityTypeMedium中等质量
    //UIImagePickerControllerQualityTypeLow低质量
    //UIImagePickerControllerQualityType640x480
    _imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    
    //设置摄像头模式（拍照，录制视频）为录像模式
    _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    [self presentViewController:_imagePickerController animated:YES completion:nil];
}
#pragma mark 从相册获取图片或视频
- (void)selectImageFromAlbum
{
    //NSLog(@"相册");
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:_imagePickerController animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    NSLog(@"选择完毕----image:%@-----info:%@",image,editingInfo);
}

//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    //判断资源类型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        //如果是图片
//        self.imageView.image = info[UIImagePickerControllerEditedImage];
//        //压缩图片
//        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
//        //保存图片至相册
//        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//        //上传图片
//        [self uploadImageWithData:fileData];
        
    }else{
        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];
        //播放视频
//        _moviePlayer.contentURL = url;
//        [_moviePlayer play];
        //保存视频至相册（异步线程）
        NSString *urlStr = [url path];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
                
                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
        });
        NSData *videoData = [NSData dataWithContentsOfURL:url];
        //视频上传
//        [self uploadVideoWithData:videoData];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    
}

#pragma mark 视频保存完毕的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}
//支持横屏
-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
//取消按钮
-(void)DismissScreenView
{
    if (self) {
        [self.view removeFromSuperview];
    }
}
//取消当前页面点击手势
-(void)DismissScreenView:(UITapGestureRecognizer*)sender{
    CGPoint point = [sender locationInView:self.view];
    if (point.x<self.subView.frame.origin.x || point.x >self.subView.frame.origin.x+self.subView.frame.size.width||point.y<self.subView.frame.origin.y||point.y>self.subView.frame.origin.y+self.subView.frame.size.height) {
        
        if (self) {
            [self.view removeFromSuperview];
        }
    }
}

- (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.
}
*/

@end
