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