ScannerViewController.m 31 KB

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