ScannerViewController.m 33 KB

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