ScannerViewController.m 31 KB

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