ScannerViewController.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. }
  253. //#pragma mark - ScannerControllerDelegate
  254. //-(void)BeginScan:(bool)begin
  255. //{
  256. // self.handelOutput = begin;
  257. //}
  258. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  259. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  260. {
  261. if(!self.handelOutput)
  262. return;
  263. AVMetadataObject * cadedate = nil;
  264. CGPoint centerzone =CGPointMake(CGRectGetMidX(self.focusZone.frame), CGRectGetMidY(self.focusZone.frame));
  265. float distance = MAXFLOAT;
  266. for (AVMetadataObject *metadata in metadataObjects) {
  267. DebugLog(@"%@",metadata);
  268. // if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode])
  269. {
  270. // Transform the meta-data coordinates to screen coords
  271. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:metadata];
  272. // Update the frame on the _boundingBox view, and show it
  273. CGRect rt = transformed.bounds;
  274. CGRectGetMidX(rt);
  275. CGPoint centermeta =CGPointMake(CGRectGetMidX(rt), CGRectGetMidY(rt));
  276. if(CGRectContainsPoint(self.focusZone.frame, centermeta))
  277. {
  278. if(cadedate == nil)
  279. cadedate = metadata;
  280. float distancemeta = (centermeta.x-centerzone.x)*(centermeta.x-centerzone.x)+(centermeta.y-centerzone.y)*(centermeta.y-centerzone.y);
  281. if(distancemeta<distance)
  282. {
  283. distance = distancemeta;
  284. cadedate = metadata;
  285. }
  286. }
  287. }
  288. }
  289. if(cadedate==nil)
  290. return;
  291. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:cadedate];
  292. // Update the frame on the _boundingBox view, and show it
  293. // CGRect rt = transformed.bounds;
  294. _boundingBox.frame = transformed.bounds;
  295. _boundingBox.hidden = NO;
  296. // Now convert the corners array into CGPoints in the coordinate system
  297. // of the bounding box itself
  298. // NSArray * corners = transformed.corners;
  299. NSArray *translatedCorners = [self translatePoints:transformed.corners
  300. fromView:self.view
  301. toView:_boundingBox];
  302. // Set the corners array
  303. _boundingBox.corners = translatedCorners;
  304. // Update the view with the decoded text
  305. _decodedMessage.text = [transformed stringValue];
  306. // Start the timer which will hide the overlay
  307. [self startOverlayHideTimer];
  308. [self playSound];
  309. self.handelOutput = false;
  310. [self StopScan];
  311. self.scan_val = [transformed stringValue];
  312. NSString *action = nil;
  313. switch (self.target) {
  314. case SCANNER_TARGET_DETAIL:
  315. {
  316. DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
  317. // dvc
  318. action = @"Open A Model";
  319. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeCamScan Action:action Extra:nil];
  320. dvc.use_model_name = true;
  321. dvc.model_name=[transformed stringValue];
  322. dvc.category_id=nil;
  323. dvc.ispush = true;
  324. [dvc reload];
  325. [self.navigationController pushViewController:dvc animated:true];
  326. }
  327. break;
  328. case SCANNER_TARGET_CART:
  329. {
  330. [CartUtils add_to_cart:self selectorholder:self selector:@selector(addtocart)];
  331. // return;
  332. // [self add_toCart];
  333. // DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
  334. // // dvc
  335. //
  336. //
  337. // dvc.use_model_name = true;
  338. // dvc.model_name=[transformed stringValue];
  339. // dvc.category_id=nil;
  340. // dvc.ispush = true;
  341. //
  342. // [dvc reload];
  343. // [self.navigationController pushViewController:dvc animated:true];
  344. }
  345. break;
  346. default:
  347. break;
  348. }
  349. }
  350. -(void)add_toCart
  351. {
  352. UIApplication * app = [UIApplication sharedApplication];
  353. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  354. MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  355. if(appDelegate.bLogin==false)
  356. {
  357. LoginViewController * loginvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
  358. loginvc.returnValue = ^(bool blogin){
  359. if(blogin)
  360. {
  361. if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE*/ true)
  362. {
  363. #ifdef RA_NOTIFICATION
  364. [ActiveViewController Notify:@"CategoryViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  365. #else
  366. [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
  367. #endif
  368. [main_vc checklogin:false];
  369. 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];
  370. // alert.
  371. [alert show];
  372. }
  373. else
  374. {
  375. [main_vc checklogin:true];
  376. }
  377. }
  378. };
  379. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
  380. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  381. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  382. [self presentViewController:navi animated:YES completion:^{
  383. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  384. DebugLog(@"LoginViewController present.........");
  385. // self.btop = false;
  386. // <#code#>
  387. }];
  388. }
  389. else
  390. {
  391. if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE&&/*appDelegate.contact_id==nil&&*/appDelegate.order_code==nil)
  392. {
  393. [main_vc checklogin:false];
  394. if(appDelegate.can_create_order)
  395. {
  396. NSString* msg =@"";
  397. if(appDelegate.contact_id.length>0)
  398. {
  399. msg = [msg stringByAppendingString:@"\n\nCustomer:"];
  400. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  401. }
  402. 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];
  403. // alert.
  404. [alert show];
  405. }
  406. else
  407. {
  408. 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];
  409. // alert.
  410. [alert show];
  411. }
  412. }
  413. else
  414. {
  415. if(appDelegate.order_code==nil)
  416. [ self neworder];
  417. else
  418. [self addtocart];
  419. }
  420. }
  421. }
  422. -(void) neworder
  423. {
  424. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Create Order"];
  425. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  426. NSDictionary* return_json = [RANetwork new_Order];
  427. dispatch_async(dispatch_get_main_queue(), ^{
  428. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  429. if([[return_json valueForKey:@"result"] intValue]==2)
  430. {
  431. int result=[[return_json valueForKey:@"result"] intValue];
  432. if(result==2)
  433. {
  434. //successed.
  435. NSString* order_code = [return_json valueForKey:@"orderCode"];
  436. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  437. appDelegate.order_code = order_code;
  438. appDelegate.order_status = [[return_json valueForKey:@"orderStatus"] intValue];
  439. [self addtocart];
  440. }
  441. }
  442. else
  443. {
  444. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:self] ;
  445. }
  446. });
  447. });
  448. }
  449. -(void) addtocart
  450. {
  451. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  452. NSDictionary* return_json = [RANetwork add_toCart_byName: self.scan_val withScreen:ScreenCodeCamScan];
  453. dispatch_async(dispatch_get_main_queue(), ^{
  454. if([[return_json valueForKey:@"result"] intValue]==2)
  455. {
  456. #ifdef RA_NOTIFICATION
  457. [ActiveViewController Notify:@"CartViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  458. #else
  459. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  460. [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
  461. #endif
  462. }
  463. else
  464. {
  465. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:self] ;
  466. }
  467. });
  468. });
  469. }
  470. - (IBAction)TargetButtonClick:(id)sender {
  471. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Change scanner target to" message:nil preferredStyle:UIAlertControllerStyleAlert];
  472. //block代码块取代了delegate
  473. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Model Detail" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  474. [self.targetButton setTitle:@"Target: Model Detail" forState:UIControlStateNormal];
  475. self.target = SCANNER_TARGET_DETAIL;
  476. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Remove Models From Cart"];
  477. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  478. //
  479. // NSDictionary* cart_json = [iSalesNetwork cart_remove:ids];
  480. //
  481. // dispatch_async(dispatch_get_main_queue(), ^{
  482. //
  483. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  484. //
  485. // if([[cart_json valueForKey:@"result"] intValue]==2)
  486. // {
  487. //
  488. // [self end_edit];
  489. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  490. // [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:true];
  491. // [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:true];
  492. // }
  493. // else
  494. // {
  495. // [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Delete Model" controller:self] ;
  496. // }
  497. //
  498. //
  499. //
  500. // });
  501. // });
  502. }];
  503. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cart" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  504. [self.targetButton setTitle:@"Target: Cart" forState:UIControlStateNormal];
  505. self.target = SCANNER_TARGET_CART;
  506. DebugLog(@"No");
  507. }];
  508. [alertControl addAction:actionOne];
  509. [alertControl addAction:alertthree];
  510. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  511. [self presentViewController:alertControl animated:YES completion:nil];
  512. }
  513. - (IBAction)ScanButtonClick:(id)sender {
  514. self.scanButton.backgroundColor = [UIColor greenColor];
  515. [self.scanButton setTitle:@"Scanning" forState:UIControlStateNormal];
  516. // self.scanButton.layer.borderWidth = 1;
  517. self.handelOutput = true;
  518. // if (self.Scannerdelegate && [self.Scannerdelegate respondsToSelector:@selector(BeginScan:)]) {
  519. // [self.Scannerdelegate BeginScan:true];
  520. // }
  521. }
  522. -(void) StopScan
  523. {
  524. self.scanButton.backgroundColor = [UIColor redColor];
  525. [self.scanButton setTitle:@"Tap" forState:UIControlStateNormal];
  526. }
  527. #pragma mark - Utility Methods
  528. - (void)startOverlayHideTimer
  529. {
  530. // Cancel it if we're already running
  531. if(_boxHideTimer) {
  532. [_boxHideTimer invalidate];
  533. }
  534. // Restart it to hide the overlay when it fires
  535. _boxHideTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
  536. target:self
  537. selector:@selector(removeBoundingBox:)
  538. userInfo:nil
  539. repeats:NO];
  540. }
  541. - (void)removeBoundingBox:(id)sender
  542. {
  543. // Hide the box and remove the decoded text
  544. _boundingBox.hidden = YES;
  545. // _decodedMessage.text = @"";
  546. }
  547. - (NSArray *)translatePoints:(NSArray *)points fromView:(UIView *)fromView toView:(UIView *)toView
  548. {
  549. NSMutableArray *translatedPoints = [NSMutableArray new];
  550. // The points are provided in a dictionary with keys X and Y
  551. for (NSDictionary *point in points) {
  552. // Let's turn them into CGPoints
  553. CGPoint pointValue = CGPointMake([point[@"X"] floatValue], [point[@"Y"] floatValue]);
  554. // Now translate from one view to the other
  555. CGPoint translatedPoint = [fromView convertPoint:pointValue toView:toView];
  556. // Box them up and add to the array
  557. [translatedPoints addObject:[NSValue valueWithCGPoint:translatedPoint]];
  558. }
  559. return [translatedPoints copy];
  560. }
  561. #pragma mark - UIAlertViewDelegate
  562. // Called when a button is clicked. The view will be automatically dismissed after this call returns
  563. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  564. {
  565. UIApplication * app = [UIApplication sharedApplication];
  566. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  567. // int count=[self.quantity_text.text intValue];
  568. MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  569. if(buttonIndex==alertView.cancelButtonIndex)
  570. {
  571. }
  572. else if(buttonIndex==1)
  573. {
  574. //open exist
  575. OrderListViewController* ovc =[ self.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  576. ovc.showNavibar = true;
  577. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  578. if(appDelegate.order_code==nil)
  579. {
  580. [self neworder];
  581. }
  582. else
  583. {
  584. #ifdef RA_NOTIFICATION
  585. [ActiveViewController Notify:@"CartViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  586. #else
  587. [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
  588. #endif
  589. [self addtocart];
  590. [main_vc checklogin:true];
  591. }
  592. };
  593. ovc.init_style = OL_OPEN;
  594. ovc.onCancel = ^(){
  595. [main_vc checklogin:true];
  596. };
  597. [self.navigationController pushViewController:ovc animated:true];
  598. }
  599. else
  600. {
  601. //create new;
  602. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  603. {
  604. ContactListViewController* cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  605. cvc.showNavibar = true;
  606. cvc.contact_type = @"Sales_Order_Customer";
  607. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  608. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  609. appDelegate.customerInfo = value;
  610. if(appDelegate.order_code==nil)
  611. [self neworder];
  612. [main_vc checklogin:true];
  613. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  614. //
  615. // if(self.returnValue)
  616. // self.returnValue(value);
  617. };
  618. cvc.onCancel = ^(){
  619. UIViewController *vc= [RAUtils getViewController:self];
  620. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order" controller:vc];
  621. };
  622. cvc.onReset = ^(){
  623. [main_vc checklogin:true];
  624. };
  625. [self.navigationController pushViewController:cvc animated:true];
  626. }
  627. else
  628. {
  629. [self neworder];
  630. }
  631. }
  632. }
  633. @end