//
//  ScanViewController.m
//  Car
//
//  Created by Javen on 2016/12/27.
//  Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//

#import "ScanViewController.h"
#import "CardViewController.h"
#import "WatchLoginViewController.h"
@interface ScanViewController ()
@property (strong, nonatomic) UIButton *btnGoInput;
@property (strong, nonatomic) UILabel *labelInfo;
@end

@implementation ScanViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.title = @"扫码";
  
  // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  [self labelInfo];
  
  switch (self.type) {
    case scanTypeCard:
    {
      [self btnGoInput];
    }
      break;
    case scanTypeLogin:
    {
      
    }
      break;
      
    default:
      break;
  }
}

- (UILabel *)labelInfo {
  CGFloat y = kHeight/2 - 44 - (kWidth - 120)/2 - 60;
  if (!_labelInfo) {
    _labelInfo = [[UILabel alloc] initWithFrame:CGRectMake(0, y, kWidth, 30)];
    _labelInfo.text = @"将二维码放入框中，即可自动扫描";
    _labelInfo.font = [UIFont systemFontOfSize:13];
    _labelInfo.textAlignment = NSTextAlignmentCenter;
    _labelInfo.textColor = [UIColor whiteColor];
//    _labelInfo.backgroundColor = [UIColor redColor];
    [self.view addSubview:_labelInfo];
  }
  
  return _labelInfo;
}

- (UIButton *)btnGoInput {
  if (!_btnGoInput) {
    _btnGoInput = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnGoInput.frame = CGRectMake(0, kHeight - 200, 120, 48);
    _btnGoInput.backgroundColor = [UIColor grayColor];
    [_btnGoInput setTitle:@"手工输入" forState:UIControlStateNormal];
    [_btnGoInput setTitleColor:[UIColor colorWithRed:0.89 green:0.44 blue:0.23 alpha:1.00] forState:UIControlStateNormal];
    _btnGoInput.layer.cornerRadius = 24;
    _btnGoInput.centerX = self.view.centerX;
    [_btnGoInput addTarget:self action:@selector(actionGoInput) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnGoInput];
  }
  return _btnGoInput;
}


/**
 跳转到手工输入界面
 */
- (void)actionGoInput {
  [self goCardVCWithNumber:nil];
}


/**
 跳转核销卡券页面
 */
- (void)goCardVCWithNumber:(NSString *)number {
  CardViewController *cardVC = [CardViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
  cardVC.cardNumber = number;
  [kGlobal.mainNaVC pushViewController:cardVC animated:YES];
}

- (void)goWatchLoginWithUrl:(NSString *)url {
  NSString *device = [self getStringAfter:@"deviceId=" string:url];
  NSString *token = [self getStringAfter:@"token=" string:url];
  WS(weakSelf);
  if (device == nil || token == nil) {
    [MBProgressHUD j_error:@"设备信息异常！" complete:^{
      [weakSelf reStartDevice];
    }];
    return;
  }
  WatchLoginViewController *loginVC = [WatchLoginViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
  loginVC.device = device;
  loginVC.token = token;
  [kGlobal.mainNaVC pushViewController:loginVC animated:YES];
}
#pragma mark -实现类继承该方法，作出对应处理
- (void)scanResultWithArray:(NSArray<LBXScanResult *> *)array {

  if (array.count < 1) {
   

    return;
  }

  //经测试，可以同时识别2个二维码，不能同时识别二维码和条形码
  for (LBXScanResult *result in array) {

    NSLog(@"scanResult:%@", result.strScanned);
  }

  LBXScanResult *scanResult = array[0];

  NSString *strResult = scanResult.strScanned;

  self.scanImage = scanResult.imgScanned;

  if (!strResult) {


    return;
  }

  //震动提醒
  [LBXScanWrapper systemVibrate];
  //声音提醒
  [LBXScanWrapper systemSound];
  
  if (self.type == scanTypeCard) {
    
    [self goCardVCWithNumber:strResult];
    
  }else if (self.type == scanTypeLogin){
    [self goWatchLoginWithUrl:strResult];
  }

}

/**
 从prefix后开始截取连续字符串（字符串中可包涵数字字母）
 
 @param prefix 从哪里开始截取
 @param string 需要截取的字符串
 @return 截取后的字符串
 */
- (NSString *)getStringAfter:(NSString *)prefix string:(NSString *)string {
  NSString *grex = [NSString stringWithFormat:@"%@[a-z0-9A-Z]*",prefix];
  
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:grex options:NSRegularExpressionCaseInsensitive error:nil];
  
  NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
  if (matches.count == 1) {
    NSTextCheckingResult *result = matches[0];
    NSString *tempString = [string substringWithRange:result.range];
    NSString *matchedString = [tempString componentsSeparatedByString:@"="][1];
    return matchedString;
  }
  CLog(@"无法匹配到prefix：%@ \n string = %@",prefix, string);
  return nil;
}

//- (void)goWatchLoginViewWith

- (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
