//
//  ScanVc.m
//  YF-Store-iphone
//
//  Created by I Mac on 16/3/28.
//  Copyright © 2016年 yfdyf. All rights reserved.
//

#import "ScanVc.h"
#import <AVFoundation/AVFoundation.h>
#import <ZXingObjC/ZXingObjC.h>
#import "MBProgressHUD.h"

#define YF_IS_IPHON4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ?            CGSizeEqualToSize(CGSizeMake(640,960), [[UIScreen mainScreen] currentMode].size) : NO)
#define YF_IS_IPHON5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640,1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define YF_IS_IPHONX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125,2436), [[UIScreen mainScreen] currentMode].size) : NO)
#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#define Height [UIScreen mainScreen].bounds.size.height
#define Width [UIScreen mainScreen].bounds.size.width
#define XCenter self.view.center.x
#define YCenter self.view.center.y

#define SHeight YF_IS_IPHONX ? 44 : 20

#define SWidth (XCenter+30)
@interface ScanVc ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate> {
    int num;
    BOOL upOrdown;
    NSTimer * timer;
    NSString *scanCodeString;
    
}

@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UIImageView *lineimageView;
@property (nonatomic,strong) UILabel *tipsLabel;
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (nonatomic,strong) UIView *backgoundView;
@property (nonatomic,strong) UIView *navigationView;
@property (nonatomic,strong) UIButton *backBtn;
@property (nonatomic,strong) UIButton *rightBtn;
@property (strong, nonatomic) UILabel *titleLabel;

@end

@implementation ScanVc

- (void)viewDidLoad {
    [super viewDidLoad];
    upOrdown = NO;
    num =0;
    
    self.title =@"二维码";
    [self.view addSubview:self.navigationView];
    [self.navigationView addSubview:self.titleLabel];
    [self.navigationView addSubview:self.backBtn];
    [self.navigationView addSubview:self.rightBtn];
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.lineimageView];
    [self.view addSubview:self.tipsLabel];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
#if !TARGET_OS_SIMULATOR    //真机
    [self checkAVAuthorizationStatus];
#endif
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [timer invalidate];
}
- (void)dealloc{
    timer = nil;
    self.session = nil;
    self.preview = nil;
    self.lineimageView = nil;
    self.output = nil;
    self.input = nil;
    self.imageView = nil;
    self.backgoundView = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)backAction{
    NSLog(@"backActionbackActionbackActionbackActionbackAction");
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)animation1{
    if (upOrdown == NO) {
        num ++;
        self.lineimageView.frame = CGRectMake(CGRectGetMinX(self.imageView.frame)+5, CGRectGetMinY(self.imageView.frame)+5+2*num, Width-144,5);
        
        if (num ==(int)(( Width-144)/2)){
            upOrdown = YES;
        }
    } else {
        num --;
        self.lineimageView.frame =CGRectMake(CGRectGetMinX(self.imageView.frame)+5, CGRectGetMinY(self.imageView.frame)+5+2*num, Width-144,5);
        if (num == 0) {
            upOrdown = NO;
        }
    }
}
- (void)setupCamera{
    [self.view.layer insertSublayer:self.preview atIndex:0];
    [self.view bringSubviewToFront:self.imageView];
    if (!self.backgoundView) {
        [self setOverView];
    }
    [self.session startRunning];
}

- (void)checkAVAuthorizationStatus {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(status == AVAuthorizationStatusAuthorized ||status == AVAuthorizationStatusNotDetermined){
        [self setupCamera];
    } else if(status == AVAuthorizationStatusRestricted ||
              status == AVAuthorizationStatusDenied){
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_8_0
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您已经关闭了“益助手”相机权限" message:@"打开相机使用权限才能正常使用扫描功能哦！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"去设置", nil];
        [alertView show];
#else
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您已经关闭了“益助手”相机权限" message:@"打开相机使用权限才能正常使用扫描功能哦！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
#endif
        
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(1 == buttonIndex){
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];[[UIApplication sharedApplication] openURL:url];
        }
    }else{
        [self backAction];
    }
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if ([metadataObjects count] >0){
        AVMetadataMachineReadableCodeObject *object = [metadataObjects  firstObject];
        scanCodeString = object.stringValue;
        NSLog(@"scanCodeString----%@",scanCodeString);
        NSNotification * notice = [NSNotification notificationWithName:@"scan" object:nil userInfo:@{@"content":scanCodeString}];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [self.preview removeFromSuperlayer];
        [self backAction];
    }
    [self.session stopRunning];
}
- (void)setOverView {
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    CGFloat x = CGRectGetMinX(self.imageView.frame);
    CGFloat y = CGRectGetMinY(self.imageView.frame);
    CGFloat w = CGRectGetWidth(self.imageView.frame);
    CGFloat h = CGRectGetHeight(self.imageView.frame);
    CGFloat top = SHeight;
    
    [self creatView:CGRectMake(0, 44 + top, width, y - 44 - top)];
    [self creatView:CGRectMake(0, y, x, h)];
    [self creatView:CGRectMake(0, y + h, width, height - y - h)];
    [self creatView:CGRectMake(x + w, y, width - x - w, h)];
}
- (void)creatView:(CGRect)rect {
    self.backgoundView = [[UIView alloc] initWithFrame:rect];
    self.backgoundView.backgroundColor = [UIColor blackColor];
    self.backgoundView.alpha = 0.48;
    [self.view addSubview:self.backgoundView];
}
- (CGRect)rectOfInterestByScanViewRect:(CGRect)rect {
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    CGFloat x = (height - CGRectGetHeight(rect)) / 2 / height;
    CGFloat y = (width - CGRectGetWidth(rect)) / 2 / width;
    
    CGFloat w = CGRectGetHeight(rect) / height;
    CGFloat h = CGRectGetWidth(rect) / width;
    
    return CGRectMake(x, y, w, h);
}

#pragma mark ------Property------

- (UIImageView *)imageView{
    if (!_imageView) {
        CGFloat top = SHeight;
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = CGRectMake(67, (Height- 44 - top - (Width - 134))/2, Width - 134, Width - 134);
        _imageView.image = [UIImage imageNamed:@"scan-frame"];
    }
    return _imageView;
}
- (UIImageView *)lineimageView{
    if (!_lineimageView) {
        _lineimageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.imageView.frame)+5, CGRectGetMinY(self.imageView.frame)+5, Width - 144,5)];
        _lineimageView.image = [UIImage imageNamed:@"search_scanning"];
    }
    return _lineimageView;
}
- (UILabel *)tipsLabel {
    if(!_tipsLabel) {
        CGFloat top = SHeight;
        _tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, (Height- 44 - top - (Width - 134))/2 + 20 + (Width - 134) , Width - 80 , 30)];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.text = @"请将条形码/二维码放入框内，即可自动扫描";
        _tipsLabel.font = [UIFont systemFontOfSize:13.0f];
        _tipsLabel.textColor = [UIColor whiteColor];
    }
    return _tipsLabel;
}

- (AVCaptureDevice *)device{
    if (!_device) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}

- (AVCaptureDeviceInput *)input{
    if (!_input) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}
//
- (AVCaptureMetadataOutput *)output{
    if (!_output) {
        _output = [[AVCaptureMetadataOutput alloc]init];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        if (YF_IS_IPHON4) {
            //      [_output setRectOfInterest:CGRectMake((Width-SWidth)/2/Height+0.03,((Height-SWidth)/2-90)/Width,SWidth/Height,SWidth/Width)];
        }else{
            //      [_output setRectOfInterest:CGRectMake((Width-SWidth)/2/Height+0.06,((Height-SWidth)/2-150)/Width,SWidth/Height,SWidth/Width)];
        }
    }
    return _output;
}

- (AVCaptureSession *)session{
    if (!_session) {
        _session = [[AVCaptureSession alloc]init];
        [_session setSessionPreset:AVCaptureSessionPresetHigh];
        if ([_session canAddInput:self.input]){
            [_session addInput:self.input];
        }
        if ([_session canAddOutput:self.output]){
            [_session addOutput:self.output];
        }
        self.output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeQRCode];
    }
    return _session;
}

- (AVCaptureVideoPreviewLayer *)preview{
    if (!_preview) {
        _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _preview.videoGravity = AVLayerVideoGravityResize;
        _preview.frame =self.view.bounds;
    }
    return _preview;
}
#pragma mark 从相册获取图片或视频
- (void)selectImageFromAlbum{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info valueForKey:UIImagePickerControllerOriginalImage];
    [self decode:image];
}


- (void)decode:(UIImage *)srcImage{
    if (nil==srcImage){
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"未找到二维码或条形码";
        [hud hideAnimated:YES afterDelay:2.f];
        return;
    }
    CGImageRef imageToDecode = srcImage.CGImage;  // Given a CGImage in which we are looking for barcodes
    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
    ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
    NSError *error = nil;
    ZXDecodeHints *hints = [ZXDecodeHints hints];
    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
    ZXResult *result = [reader decode:bitmap hints:hints error:&error];
    if (result) {
        NSString *contents = result.text;
        NSNotification * notice = [NSNotification notificationWithName:@"scan" object:nil userInfo:@{@"content":contents}];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [self backAction];
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"未找到二维码或条形码";
        [hud hideAnimated:YES afterDelay:2.f];
    }
}

- (UIView *)navigationView{
    if (!_navigationView) {
        _navigationView = [[UIView alloc] init];
        _navigationView.backgroundColor = [UIColor whiteColor];
        _navigationView.frame = CGRectMake(0, 0, Width, 44+(YF_IS_IPHONX ? 44:20));
    }
    return _navigationView;
}
-(UILabel *)titleLabel {
    if(!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 12+(YF_IS_IPHONX ? 44:20),Width - 120 , 20)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text = @"扫一扫";
        _titleLabel.font = [UIFont systemFontOfSize:18.0f];
        _titleLabel.textColor = RGBColor(49, 49, 51);
    }
    return _titleLabel;
}
- (UIButton *)backBtn{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(5, 5+(YF_IS_IPHONX ? 44:20), 34, 34);
        _backBtn.backgroundColor = [UIColor clearColor];
        [_backBtn setImage:[UIImage imageNamed:@"close_btn"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake(self.view.frame.size.width-60, 5+(YF_IS_IPHONX ? 44:20), 60, 34);
        _rightBtn.backgroundColor = [UIColor clearColor];
        [_rightBtn setTitle:@"相册" forState:0];
        [_rightBtn setTitleColor:RGBColor(49, 49, 51) forState:0];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_rightBtn addTarget:self action:@selector(selectImageFromAlbum) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}

@end

