ScannerViewController.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. /*
  2. Copyright 2013 Scott Logic Ltd
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #import "ScannerViewController.h"
  14. @import AVFoundation;
  15. #import <AudioToolbox/AudioToolbox.h>
  16. #import "SCShapeView.h"
  17. #import "ScannerControllerView.h"
  18. #import "DetailViewController.h"
  19. #import "const.h"
  20. #import "AppDelegate.h"
  21. #import "MainViewController.h"
  22. #import "ContactListViewController.h"
  23. #import "CartUtils.h"
  24. #import "ERPUtils.h"
  25. #import "RANetwork.h"
  26. #define SCANNER_TARGET_DETAIL 0
  27. #define SCANNER_TARGET_CART 1
  28. //#import "ScannerControlViewController.h"
  29. @interface ScannerViewController () <AVCaptureMetadataOutputObjectsDelegate> {
  30. AVCaptureVideoPreviewLayer *_previewLayer;
  31. SCShapeView *_boundingBox;
  32. NSTimer *_boxHideTimer;
  33. UILabel *_decodedMessage;
  34. }
  35. @end
  36. @implementation ScannerViewController
  37. //- (UIInterfaceOrientationMask)supportedInterfaceOrientations
  38. //{
  39. // return UIInterfaceOrientationMaskPortrait;
  40. //}
  41. //- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
  42. //{
  43. //
  44. // return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
  45. //
  46. //}
  47. - (BOOL)shouldAutorotate
  48. {
  49. return false;
  50. }
  51. -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
  52. {
  53. [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
  54. CGRect rect=self.view.bounds;
  55. DebugLog(NSStringFromCGRect(self.focusZone.frame));
  56. // rect.origin.y=rect.origin.y+40;
  57. // rect.size.height = rect.size.height-40;
  58. [CATransaction begin];
  59. [CATransaction setAnimationDuration:0.5];
  60. [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
  61. // [self updatePreviewLayerForOrientation:toInterfaceOrientation];
  62. _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  63. // self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  64. _previewLayer.bounds = rect;
  65. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  66. switch (orientation) {
  67. case UIInterfaceOrientationPortrait:
  68. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
  69. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  70. break;
  71. case UIInterfaceOrientationPortraitUpsideDown:
  72. //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
  73. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  74. break;
  75. case UIInterfaceOrientationLandscapeLeft:
  76. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
  77. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  78. break;
  79. case UIInterfaceOrientationLandscapeRight:
  80. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
  81. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  82. break;
  83. default:
  84. break;
  85. }
  86. [CATransaction commit];
  87. }
  88. //- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
  89. //{
  90. // return UIInterfaceOrientationPortrait;
  91. //}
  92. -(void) playSound
  93. {
  94. /*
  95. SystemSoundID sameViewSoundID;
  96. // NSString *filePath = [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"m4r"];
  97. // NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]; //音乐文件路径
  98. NSString *path = @"/System/Library/Audio/UISounds/begin_video_record.caf";
  99. CFURLRef thesoundURL = (__bridge CFURLRef) [NSURL fileURLWithPath:path] ;
  100. AudioServicesCreateSystemSoundID(thesoundURL, &sameViewSoundID);
  101. //变量SoundID与URL对应
  102. DebugLog(@"%u",(unsigned int)sameViewSoundID);
  103. AudioServicesPlaySystemSound(1112); //播放SoundID声音
  104. */
  105. CFBundleRef mainBundle;
  106. SystemSoundID soundFileObject;
  107. mainBundle = CFBundleGetMainBundle ();
  108. CFURLRef soundFileURLRef = CFBundleCopyResourceURL (
  109. mainBundle,
  110. CFSTR ("softScanBeep" ),
  111. CFSTR ("wav" ),
  112. NULL
  113. );
  114. AudioServicesCreateSystemSoundID (
  115. soundFileURLRef,
  116. &soundFileObject
  117. );
  118. AudioServicesPlaySystemSound(soundFileObject);
  119. }
  120. - (void)viewWillAppear:(BOOL)animated
  121. {
  122. [super viewWillAppear:animated];
  123. [[self navigationController] setNavigationBarHidden:NO animated:NO];
  124. //
  125. //[ attemptRotationToDeviceOrientation];
  126. //[UIViewController attemptRotationToDeviceOrientation];
  127. //
  128. // [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
  129. // self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
  130. // CGRect frame = [UIScreen mainScreen].applicationFrame;
  131. // self.view.bounds = CGRectMake(0, 0, 768, 1024);
  132. }
  133. - (void)onBackClick:(UIButton *)sender {
  134. [self.navigationController popViewControllerAnimated:FALSE];
  135. }
  136. - (void)viewDidLoad
  137. {
  138. [super viewDidLoad];
  139. UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  140. style:UIBarButtonItemStylePlain
  141. target:self
  142. action:@selector( onBackClick:)];
  143. // closeButton.tintColor = UIColorFromRGB(0x996633);
  144. self.navigationItem.leftBarButtonItem = closeButton;
  145. // return;
  146. [self.backgroundView removeFromSuperview];
  147. //self.back = (ScannerControllerView*)self.view;
  148. self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  149. // self.backgroundView.autoresizingMask=0xff;
  150. self.handelOutput = false;
  151. // self.ScannerControl =[self.storyboard instantiateViewControllerWithIdentifier:@"ScannerControlViewController"];
  152. // self.ScannerControl.Scannerdelegate = self;
  153. // self.view.layer.
  154. // Do any additional setup after loading the view, typically from a nib.
  155. // Create a new AVCaptureSession
  156. AVCaptureSession *session = [[AVCaptureSession alloc] init];
  157. session.sessionPreset = AVCaptureSessionPresetHigh;
  158. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  159. // float factor = device.videoZoomFactor;
  160. // float up = device.activeFormat.videoZoomFactorUpscaleThreshold;
  161. // [device lockForConfiguration:nil];
  162. // device.videoZoomFactor = device.activeFormat.videoZoomFactorUpscaleThreshold;
  163. // [device unlockForConfiguration];
  164. NSError *error = nil;
  165. // Want the normal device
  166. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  167. if(input) {
  168. // Add the input to the session
  169. [session addInput:input];
  170. } else {
  171. DebugLog(@"error: %@", error);
  172. return;
  173. }
  174. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  175. // Have to add the output before setting metadata types
  176. [session addOutput:output];
  177. // What different things can we register to recognise?
  178. DebugLog(@"%@", [output availableMetadataObjectTypes]);
  179. // We're only interested in QR Codes
  180. [output setMetadataObjectTypes:@[AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode]];
  181. DebugLog(@"%@", [output metadataObjectTypes]);
  182. // NSArray* supporttype=output.availableMetadataObjectTypes;
  183. // [output setMetadataObjectTypes:output.availableMetadataObjectTypes];
  184. // This VC is the delegate. Please call us on the main queue
  185. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  186. //
  187. // CGRect rt1 = self.ScannerControl.scannerZone.frame;
  188. // Display on screen
  189. _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
  190. _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  191. // _previewLayer.orientation= AVCaptureVideoOrientationLandscapeRight;
  192. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  193. switch (orientation) {
  194. // UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
  195. // UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
  196. // UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
  197. // UIInterfaceOrientationLandscapeRight
  198. // AVCaptureVideoOrientationPortrait = 1,
  199. // AVCaptureVideoOrientationPortraitUpsideDown = 2,
  200. // AVCaptureVideoOrientationLandscapeRight = 3,
  201. // AVCaptureVideoOrientationLandscapeLeft = 4,
  202. case UIInterfaceOrientationPortrait:
  203. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  204. break;
  205. case UIInterfaceOrientationPortraitUpsideDown:
  206. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  207. break;
  208. case UIInterfaceOrientationLandscapeLeft:
  209. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  210. break;
  211. case UIInterfaceOrientationLandscapeRight:
  212. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  213. break;
  214. default:
  215. break;
  216. }
  217. CGRect rect=self.view.bounds;
  218. // rect.origin.y=rect.origin.y+40;
  219. // rect.size.height = rect.size.height-40;
  220. _previewLayer.bounds = rect;
  221. _previewLayer.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
  222. [self.view.layer addSublayer:_previewLayer];
  223. [self.view addSubview:self.backgroundView];
  224. // [self.view addSubview:self.ScannerControl.view];
  225. // CGRect rt = self.ScannerControl.scannerZone.bounds;
  226. // CGRect rt1 =output.rectOfInterest;
  227. // output.rectOfInterest = CGRectMake(0, 0, 300, 300); //self.ScannerControl.scannerZone.frame;
  228. // ScannerControllerView* view =[[ ScannerControllerView alloc] initWithFrame:self.view.frame];
  229. // view.backgroundColor = [UIColor clearColor];
  230. // ScannerLayer * layer = [[ScannerLayer alloc] init];
  231. // [self.view.layer addSublayer:layer];
  232. // Add the view to draw the bounding box for the UIView
  233. _boundingBox = [[SCShapeView alloc] initWithFrame:self.view.bounds];
  234. _boundingBox.backgroundColor = [UIColor clearColor];
  235. _boundingBox.hidden = YES;
  236. [self.view addSubview:_boundingBox];
  237. // Add a label to display the resultant message
  238. _decodedMessage = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - 75, CGRectGetWidth(self.view.bounds), 75)];
  239. _decodedMessage.numberOfLines = 0;
  240. _decodedMessage.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.9];
  241. _decodedMessage.textColor = [UIColor darkGrayColor];
  242. _decodedMessage.textAlignment = NSTextAlignmentCenter;
  243. [self.view addSubview:_decodedMessage];
  244. self.scanButton.layer.shadowColor = [UIColor blackColor].CGColor;
  245. self.scanButton.layer.shadowOffset = CGSizeMake(0, 0);
  246. self.scanButton.layer.shadowOpacity = 0.5;
  247. self.scanButton.layer.shadowRadius = 2.0;
  248. self.scanButton.layer.borderColor = [[UIColor darkGrayColor] CGColor];
  249. self.scanButton.layer.borderWidth = 15;
  250. // Start the AVSession running
  251. [session startRunning];
  252. #ifdef BUILD_UWAVER
  253. [self.targetButton setTitle:@"Target: Model Detail" forState:UIControlStateNormal];
  254. self.target = SCANNER_TARGET_DETAIL;
  255. #endif
  256. }
  257. //#pragma mark - ScannerControllerDelegate
  258. //-(void)BeginScan:(bool)begin
  259. //{
  260. // self.handelOutput = begin;
  261. //}
  262. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  263. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  264. {
  265. if(!self.handelOutput)
  266. return;
  267. AVMetadataObject * cadedate = nil;
  268. CGPoint centerzone =CGPointMake(CGRectGetMidX(self.focusZone.frame), CGRectGetMidY(self.focusZone.frame));
  269. float distance = MAXFLOAT;
  270. for (AVMetadataObject *metadata in metadataObjects) {
  271. DebugLog(@"%@",metadata);
  272. // if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode])
  273. {
  274. // Transform the meta-data coordinates to screen coords
  275. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:metadata];
  276. // Update the frame on the _boundingBox view, and show it
  277. CGRect rt = transformed.bounds;
  278. CGRectGetMidX(rt);
  279. CGPoint centermeta =CGPointMake(CGRectGetMidX(rt), CGRectGetMidY(rt));
  280. if(CGRectContainsPoint(self.focusZone.frame, centermeta))
  281. {
  282. if(cadedate == nil)
  283. cadedate = metadata;
  284. float distancemeta = (centermeta.x-centerzone.x)*(centermeta.x-centerzone.x)+(centermeta.y-centerzone.y)*(centermeta.y-centerzone.y);
  285. if(distancemeta<distance)
  286. {
  287. distance = distancemeta;
  288. cadedate = metadata;
  289. }
  290. }
  291. }
  292. }
  293. if(cadedate==nil)
  294. return;
  295. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:cadedate];
  296. // Update the frame on the _boundingBox view, and show it
  297. // CGRect rt = transformed.bounds;
  298. _boundingBox.frame = transformed.bounds;
  299. _boundingBox.hidden = NO;
  300. // Now convert the corners array into CGPoints in the coordinate system
  301. // of the bounding box itself
  302. // NSArray * corners = transformed.corners;
  303. NSArray *translatedCorners = [self translatePoints:transformed.corners
  304. fromView:self.view
  305. toView:_boundingBox];
  306. // Set the corners array
  307. _boundingBox.corners = translatedCorners;
  308. // Update the view with the decoded text
  309. _decodedMessage.text = [transformed stringValue];
  310. // Start the timer which will hide the overlay
  311. [self startOverlayHideTimer];
  312. [self playSound];
  313. self.handelOutput = false;
  314. [self StopScan];
  315. self.scan_val = [transformed stringValue];
  316. NSString *action = nil;
  317. switch (self.target) {
  318. case SCANNER_TARGET_DETAIL:
  319. {
  320. DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
  321. // dvc
  322. action = @"Open A Model";
  323. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeCamScan Action:action Extra:nil];
  324. dvc.use_model_name = true;
  325. dvc.model_name=[transformed stringValue];
  326. dvc.category_id=nil;
  327. dvc.ispush = true;
  328. #ifdef BUILD_UWAVER
  329. if(!(transformed.type==AVMetadataObjectTypeQRCode))
  330. dvc.groupName = [transformed stringValue];
  331. #endif
  332. //
  333. [dvc reload];
  334. [self.navigationController pushViewController:dvc animated:true];
  335. }
  336. break;
  337. case SCANNER_TARGET_CART:
  338. {
  339. [CartUtils add_to_cart:self selectorholder:self selector:@selector(addtocart)];
  340. // return;
  341. // [self add_toCart];
  342. // DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
  343. // // dvc
  344. //
  345. //
  346. // dvc.use_model_name = true;
  347. // dvc.model_name=[transformed stringValue];
  348. // dvc.category_id=nil;
  349. // dvc.ispush = true;
  350. //
  351. // [dvc reload];
  352. // [self.navigationController pushViewController:dvc animated:true];
  353. }
  354. break;
  355. default:
  356. break;
  357. }
  358. }
  359. -(void)add_toCart
  360. {
  361. UIApplication * app = [UIApplication sharedApplication];
  362. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  363. MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  364. if(appDelegate.bLogin==false)
  365. {
  366. LoginViewController * loginvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
  367. loginvc.returnValue = ^(bool blogin){
  368. if(blogin)
  369. {
  370. if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE*/ true)
  371. {
  372. #ifdef RA_NOTIFICATION
  373. [ActiveViewController Notify:@"CategoryViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  374. #else
  375. [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
  376. #endif
  377. [main_vc checklogin:false];
  378. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"Do you want to add to pending a order or a new order", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil),NSLocalizedString(@"Add to new order", nil), nil];
  379. // alert.
  380. [alert show];
  381. }
  382. else
  383. {
  384. [main_vc checklogin:true];
  385. }
  386. }
  387. };
  388. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
  389. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  390. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  391. [self presentViewController:navi animated:YES completion:^{
  392. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  393. DebugLog(@"LoginViewController present.........");
  394. // self.btop = false;
  395. // <#code#>
  396. }];
  397. }
  398. else
  399. {
  400. if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE&&/*appDelegate.contact_id==nil&&*/appDelegate.order_code==nil)
  401. {
  402. [main_vc checklogin:false];
  403. if(appDelegate.can_create_order)
  404. {
  405. NSString* msg =@"";
  406. if(appDelegate.contact_id.length>0)
  407. {
  408. msg = [msg stringByAppendingString:@"\n\nCustomer:"];
  409. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  410. }
  411. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil),NSLocalizedString(@"Add to new order", nil), nil];
  412. // alert.
  413. [alert show];
  414. }
  415. else
  416. {
  417. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil), nil];
  418. // alert.
  419. [alert show];
  420. }
  421. }
  422. else
  423. {
  424. if(appDelegate.order_code==nil)
  425. [ self neworder];
  426. else
  427. [self addtocart];
  428. }
  429. }
  430. }
  431. -(void) neworder
  432. {
  433. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Create Order"];
  434. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  435. NSDictionary* return_json = [RANetwork new_Order];
  436. dispatch_async(dispatch_get_main_queue(), ^{
  437. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  438. if([[return_json valueForKey:@"result"] intValue]==2)
  439. {
  440. int result=[[return_json valueForKey:@"result"] intValue];
  441. if(result==2)
  442. {
  443. //successed.
  444. NSString* order_code = [return_json valueForKey:@"orderCode"];
  445. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  446. appDelegate.order_code = order_code;
  447. appDelegate.order_status = [[return_json valueForKey:@"orderStatus"] intValue];
  448. [self addtocart];
  449. }
  450. }
  451. else
  452. {
  453. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:self] ;
  454. }
  455. });
  456. });
  457. }
  458. -(void) addtocart
  459. {
  460. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  461. NSDictionary* return_json = [RANetwork add_toCart_byName: self.scan_val withScreen:ScreenCodeCamScan];
  462. dispatch_async(dispatch_get_main_queue(), ^{
  463. if([[return_json valueForKey:@"result"] intValue]==2)
  464. {
  465. #ifdef RA_NOTIFICATION
  466. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  467. #else
  468. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  469. [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
  470. [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
  471. #endif
  472. }
  473. else
  474. {
  475. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:self] ;
  476. }
  477. });
  478. });
  479. }
  480. - (IBAction)TargetButtonClick:(id)sender {
  481. BOOL shouldChangeTarget = YES;
  482. #ifdef BUILD_UWAVER
  483. shouldChangeTarget = NO;
  484. #endif
  485. if (!shouldChangeTarget) {
  486. return;
  487. }
  488. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Change scanner target to" message:nil preferredStyle:UIAlertControllerStyleAlert];
  489. //block代码块取代了delegate
  490. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Model Detail" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  491. [self.targetButton setTitle:@"Target: Model Detail" forState:UIControlStateNormal];
  492. self.target = SCANNER_TARGET_DETAIL;
  493. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Remove Models From Cart"];
  494. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  495. //
  496. // NSDictionary* cart_json = [iSalesNetwork cart_remove:ids];
  497. //
  498. // dispatch_async(dispatch_get_main_queue(), ^{
  499. //
  500. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  501. //
  502. // if([[cart_json valueForKey:@"result"] intValue]==2)
  503. // {
  504. //
  505. // [self end_edit];
  506. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  507. // [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:true];
  508. // [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:true];
  509. // }
  510. // else
  511. // {
  512. // [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Delete Model" controller:self] ;
  513. // }
  514. //
  515. //
  516. //
  517. // });
  518. // });
  519. }];
  520. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cart" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  521. [self.targetButton setTitle:@"Target: Cart" forState:UIControlStateNormal];
  522. self.target = SCANNER_TARGET_CART;
  523. DebugLog(@"No");
  524. }];
  525. [alertControl addAction:actionOne];
  526. [alertControl addAction:alertthree];
  527. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  528. [self presentViewController:alertControl animated:YES completion:nil];
  529. }
  530. - (IBAction)ScanButtonClick:(id)sender {
  531. self.scanButton.backgroundColor = [UIColor greenColor];
  532. [self.scanButton setTitle:@"Scanning" forState:UIControlStateNormal];
  533. // self.scanButton.layer.borderWidth = 1;
  534. self.handelOutput = true;
  535. // if (self.Scannerdelegate && [self.Scannerdelegate respondsToSelector:@selector(BeginScan:)]) {
  536. // [self.Scannerdelegate BeginScan:true];
  537. // }
  538. }
  539. -(void) StopScan
  540. {
  541. self.scanButton.backgroundColor = [UIColor redColor];
  542. [self.scanButton setTitle:@"Tap" forState:UIControlStateNormal];
  543. }
  544. #pragma mark - Utility Methods
  545. - (void)startOverlayHideTimer
  546. {
  547. // Cancel it if we're already running
  548. if(_boxHideTimer) {
  549. [_boxHideTimer invalidate];
  550. }
  551. // Restart it to hide the overlay when it fires
  552. _boxHideTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
  553. target:self
  554. selector:@selector(removeBoundingBox:)
  555. userInfo:nil
  556. repeats:NO];
  557. }
  558. - (void)removeBoundingBox:(id)sender
  559. {
  560. // Hide the box and remove the decoded text
  561. _boundingBox.hidden = YES;
  562. // _decodedMessage.text = @"";
  563. }
  564. - (NSArray *)translatePoints:(NSArray *)points fromView:(UIView *)fromView toView:(UIView *)toView
  565. {
  566. NSMutableArray *translatedPoints = [NSMutableArray new];
  567. // The points are provided in a dictionary with keys X and Y
  568. for (NSDictionary *point in points) {
  569. // Let's turn them into CGPoints
  570. CGPoint pointValue = CGPointMake([point[@"X"] floatValue], [point[@"Y"] floatValue]);
  571. // Now translate from one view to the other
  572. CGPoint translatedPoint = [fromView convertPoint:pointValue toView:toView];
  573. // Box them up and add to the array
  574. [translatedPoints addObject:[NSValue valueWithCGPoint:translatedPoint]];
  575. }
  576. return [translatedPoints copy];
  577. }
  578. #pragma mark - UIAlertViewDelegate
  579. // Called when a button is clicked. The view will be automatically dismissed after this call returns
  580. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  581. {
  582. UIApplication * app = [UIApplication sharedApplication];
  583. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  584. // int count=[self.quantity_text.text intValue];
  585. MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  586. if(buttonIndex==alertView.cancelButtonIndex)
  587. {
  588. }
  589. else if(buttonIndex==1)
  590. {
  591. //open exist
  592. OrderListViewController* ovc =[ self.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  593. ovc.showNavibar = true;
  594. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  595. if(appDelegate.order_code==nil)
  596. {
  597. [self neworder];
  598. }
  599. else
  600. {
  601. #ifdef RA_NOTIFICATION
  602. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  603. #else
  604. [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
  605. [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
  606. #endif
  607. [self addtocart];
  608. [main_vc checklogin:true];
  609. }
  610. };
  611. ovc.init_style = OL_OPEN;
  612. ovc.onCancel = ^(){
  613. [main_vc checklogin:true];
  614. };
  615. [self.navigationController pushViewController:ovc animated:true];
  616. }
  617. else
  618. {
  619. //create new;
  620. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  621. {
  622. ContactListViewController* cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  623. cvc.showNavibar = true;
  624. cvc.contact_type = @"Sales_Order_Customer";
  625. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  626. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  627. appDelegate.customerInfo = value;
  628. if(appDelegate.order_code==nil)
  629. [self neworder];
  630. [main_vc checklogin:true];
  631. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  632. //
  633. // if(self.returnValue)
  634. // self.returnValue(value);
  635. };
  636. cvc.onCancel = ^(){
  637. UIViewController *vc= [RAUtils getViewController:self];
  638. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order" controller:vc];
  639. };
  640. cvc.onReset = ^(){
  641. [main_vc checklogin:true];
  642. };
  643. [self.navigationController pushViewController:cvc animated:true];
  644. }
  645. else
  646. {
  647. [self neworder];
  648. }
  649. }
  650. }
  651. @end