//
//  QRCodeScanVC.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/4/28.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "QRCodeScanVC.h"
#import <AVFoundation/AVFoundation.h>

@interface QRCodeScanVC () <AVCaptureMetadataOutputObjectsDelegate>

//接收扫描后输出值
@property (nonatomic, strong) NSString *str;
//设置扫描框
@property (strong, nonatomic) UIView *boxView;
//设置扫描线
@property (strong, nonatomic) CALayer *scanLayer;

-(void)stopReading;

//捕捉会话
@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;


@end

@implementation QRCodeScanVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
#pragma - 设置导航栏左边的按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBackBtnIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //2.用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
    //4.实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
    //4.1.将输入流添加到会话
    [_captureSession addInput:input];
    
    //4.2.将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    
    //5.创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    //5.2.设置输出媒体数据类型为QRCode
    //    [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,nil]];
    
    
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //8.设置图层的frame
    [_videoPreviewLayer setFrame:self.view.bounds];
    
    //9.将图层添加到预览view的图层上
    //    [self.view addSublayer:_videoPreviewLayer];
    [self.view.layer insertSublayer:_videoPreviewLayer atIndex:100];
    
    //10.设置扫描范围
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    
    //10.1.扫描框
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 0.1f, self.view.frame.size.height * 0.3f, self.view.frame.size.width - self.view.frame.size.width * 0.2f, self.view.frame.size.height - self.view.frame.size.height * 0.5f)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    [self.view addSubview:_boxView];
    
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
    
    [_boxView.layer addSublayer:_scanLayer];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    
    [timer fire];
    
    //10.开始扫描
    [_captureSession startRunning];
    
}


-(void)stopReading{
    
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
    [_boxView removeFromSuperview];
    
    if ([self.delegate respondsToSelector:@selector(passValueToWatch:)]) {
        [self.delegate passValueToWatch:self.str];
    }
    
    if ([self.delegate respondsToSelector:@selector(passValueToDevice:)]) {
        [self.delegate passValueToDevice:self.str];
    }
    
    if ([self.delegate respondsToSelector:@selector(passValueToCultureGame:)]) {
        [self.delegate passValueToCultureGame:self.str];
    }
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            
             [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            NSLog(@"erweima:%@", metadataObj.stringValue);
            
            self.str = metadataObj.stringValue;
            
//            if ([self.delegate respondsToSelector:@selector(passValueToWatch:)]) {
//                [self.delegate passValueToWatch:self.str];
//            }
//            
//            if ([self.delegate respondsToSelector:@selector(passValueToDevice:)]) {
//                [self.delegate passValueToDevice:self.str];
//            }
           
            
        } else {
            
            NSLog(@"feierweima:%@", metadataObj.stringValue);
            
            self.str = metadataObj.stringValue;
            
//            if ([self.delegate respondsToSelector:@selector(passValueToWatch:)]) {
//                [self.delegate passValueToWatch:self.str];
//            }
//            
//            if ([self.delegate respondsToSelector:@selector(passValueToDevice:)]) {
//                [self.delegate passValueToDevice:self.str];
//            }
//
            
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            
        }
    }
}

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        
        frame.origin.y += 5;
        
        [UIView animateWithDuration:0.01 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (void)leftBackBtnIsClicked {
    //返回按钮的逻辑还有什么？？
    
    [self dismissViewControllerAnimated: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.
}
*/

@end
