RAUtils.m 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. //
  2. // RAUtils.m
  3. // RedAnt ERP Mobile
  4. //
  5. // Created by Ray on 9/17/15.
  6. // Copyright (c) 2015 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "RAUtils.h"
  9. #import "LoginViewController.h"
  10. #import "MainViewController.h"
  11. #import <sys/param.h>
  12. #import <sys/mount.h>
  13. @implementation RAUtils
  14. +(NSDictionary*) dictfromfile:(NSString*) path
  15. {
  16. NSData *filedata = [NSData dataWithContentsOfFile:path];
  17. NSError *error = nil;
  18. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: filedata
  19. options: NSJSONReadingMutableContainers
  20. error: &error];
  21. // NSLog(@"%@",string2dic);
  22. return string2dic;
  23. }
  24. + (bool)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err {
  25. NSLog(@"- mergeContentsOfPath: %@\n intoPath: %@", srcDir, dstDir);
  26. NSFileManager *fm = [NSFileManager defaultManager];
  27. NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
  28. NSString *subPath;
  29. while ((subPath = [srcDirEnum nextObject])) {
  30. NSLog(@" subPath: %@", subPath);
  31. NSString *srcFullPath = [srcDir stringByAppendingPathComponent:subPath];
  32. NSString *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];
  33. // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
  34. BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);
  35. // Create directory, or delete existing file and move file to destination
  36. if (isDirectory) {
  37. NSLog(@" create directory");
  38. [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
  39. if (err && *err) {
  40. NSLog(@"ERROR: %@", *err);
  41. return false;
  42. }
  43. }
  44. else {
  45. if ([fm fileExistsAtPath:potentialDstPath]) {
  46. NSLog(@" removeItemAtPath");
  47. [fm removeItemAtPath:potentialDstPath error:err];
  48. if (err && *err) {
  49. NSLog(@"ERROR: %@", *err);
  50. return false;
  51. }
  52. }
  53. NSLog(@" moveItemAtPath");
  54. [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
  55. if (err && *err) {
  56. NSLog(@"ERROR: %@", *err);
  57. return false;
  58. }
  59. }
  60. }
  61. [fm removeItemAtPath:srcDir error:err];
  62. if (err && *err) {
  63. NSLog(@"ERROR: %@", *err);
  64. return false;
  65. }
  66. return true;
  67. }
  68. + (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
  69. // 创建一个bitmap的context
  70. // 并把它设置成为当前正在使用的context
  71. UIGraphicsBeginImageContext(size);
  72. // 绘制改变大小的图片
  73. [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
  74. // 从当前context中创建一个改变大小后的图片
  75. UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  76. // 使当前的context出堆栈
  77. UIGraphicsEndImageContext();
  78. // 返回新的改变大小后的图片
  79. // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
  80. return scaledImage;
  81. }
  82. +(UIImage*)img_compress:(UIImage*)image kbsize:(float) size
  83. {
  84. //UIImage *image=[UIImage imageNamed:@"xxoo.jpeg"];
  85. NSData *imageData=UIImageJPEGRepresentation(image, 1.f);
  86. if(size>imageData.length/1024)
  87. return image;
  88. // CGFloat size=40.f;// kb
  89. CGFloat scale=size/(imageData.length/1024);
  90. scale = sqrt (scale);
  91. CGSize newsize=image.size;
  92. newsize.height = newsize.height*scale;
  93. newsize.width = newsize.width*scale;
  94. return [RAUtils scaleToSize:image size:newsize];
  95. // NSData *newData=UIImageJPEGRepresentation(image, scale);
  96. // UIImage* ret= [[UIImage alloc] initWithData:newData];
  97. //
  98. // return ret;
  99. }
  100. +(NSString*) FloatFormat:(float)value
  101. {
  102. if (fmodf(value, 1)==0)
  103. {
  104. return [NSString stringWithFormat:@"%.0f",value];
  105. } else if (fmodf(value*10, 1)==0)
  106. {
  107. return [NSString stringWithFormat:@"%.1f",value];
  108. }
  109. else if (fmodf(value*100, 1)==0)
  110. {
  111. return [NSString stringWithFormat:@"%.2f",value];
  112. }
  113. else if (fmodf(value*1000, 1)==0)
  114. {
  115. return [NSString stringWithFormat:@"%.3f",value];
  116. }
  117. else
  118. {
  119. return [NSString stringWithFormat:@"%.4f",value];
  120. }
  121. return nil;
  122. }
  123. +(UIViewController*) getViewController:(UIView*) view
  124. {
  125. for (UIView* next = [view superview]; next; next = next.superview) {
  126. UIResponder* nextResponder = [next nextResponder];
  127. if ([nextResponder isKindOfClass:[UIViewController class]]) {
  128. return (UIViewController*)nextResponder;
  129. }
  130. }
  131. return nil;
  132. }
  133. + (float)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
  134. {
  135. NSFileManager *fileManager = [[NSFileManager alloc] init];
  136. float size =0;
  137. NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
  138. for(int i = 0; i<[array count]; i++)
  139. {
  140. NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
  141. BOOL isDir;
  142. if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
  143. {
  144. NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
  145. size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
  146. }
  147. else
  148. {
  149. size+=[self fileSizeForDir:fullPath];
  150. }
  151. }
  152. return size;
  153. }
  154. +(NSDictionary*) error_dict:(NSError*)error
  155. {
  156. if(error==nil)
  157. return nil;
  158. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  159. [ret setValue:[NSString stringWithFormat:@"%d",error.code] forKey:@"error_code"];
  160. [ret setValue:error.domain forKey:@"err_domain"];
  161. [ret setValue:[error localizedDescription] forKey:@"err_message"];
  162. // [ret setObject:error.userInfo forKey:@"user_info"];
  163. return ret;
  164. }
  165. +(NSString*) current_date
  166. {
  167. NSDate * date = [NSDate date];
  168. NSTimeInterval sec = [date timeIntervalSinceNow];
  169. NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
  170. NSDateFormatter * df = [[NSDateFormatter alloc] init ];
  171. [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  172. NSString * na = [df stringFromDate:currentDate];
  173. return na;
  174. }
  175. +(void) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
  176. {
  177. if(title==nil)
  178. title = @"Message";
  179. return [self alert_view:msg title:title];
  180. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
  181. //block代码块取代了delegate
  182. // [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  183. // textField.text = self.save_name;
  184. //
  185. //
  186. // }];
  187. // UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  188. //
  189. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Delete Order"];
  190. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  191. //
  192. // NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
  193. //
  194. // dispatch_async(dispatch_get_main_queue(), ^{
  195. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  196. //
  197. //
  198. // if([[return_json valueForKey:@"result"] intValue]==2)
  199. // {
  200. //
  201. // [RAUtils error_alert:nil title:@"Order Delete"] ;
  202. // }
  203. // else
  204. // {
  205. // [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
  206. // }
  207. //
  208. //
  209. //
  210. //
  211. // });
  212. // });
  213. //
  214. //
  215. // }];
  216. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  217. //NSLog(@"Cancel");
  218. }];
  219. // [alertControl addAction:actionOne];
  220. [alertControl addAction:alertthree];
  221. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  222. }];
  223. [alertControl addAction:alertcancel];
  224. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  225. [vc presentViewController:alertControl animated:YES completion:nil];
  226. return;
  227. }
  228. +(void) neworder:(UIViewController*) vc selectorholder:(id)holder selector:(SEL)addtocart
  229. {
  230. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Create Order"];
  231. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  232. NSDictionary* return_json = [iSalesNetwork new_Order];
  233. dispatch_async(dispatch_get_main_queue(), ^{
  234. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  235. if([[return_json valueForKey:@"result"] intValue]==2)
  236. {
  237. int result=[[return_json valueForKey:@"result"] intValue];
  238. if(result==2)
  239. {
  240. //successed.
  241. NSString* order_code = [return_json valueForKey:@"orderCode"];
  242. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  243. appDelegate.order_code = order_code;
  244. appDelegate.order_status = [[return_json valueForKey:@"orderStatus"] intValue];
  245. [holder performSelector:addtocart];
  246. // [self ReloadData];
  247. // if(self.shopCartBlock!=nil)
  248. // {
  249. // UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
  250. //
  251. //
  252. // CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
  253. // UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
  254. // iv.image = img;
  255. // // [self.contentView addSubview:iv];
  256. // self.shopCartBlock(iv);
  257. //
  258. // }
  259. }
  260. }
  261. else
  262. {
  263. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Create Order" controller:vc] ;
  264. }
  265. });
  266. });
  267. }
  268. +(void) add_to_cart:(UIViewController*) vc selectorholder:(id)holder selector:(SEL)addtocart
  269. {
  270. UIApplication * app = [UIApplication sharedApplication];
  271. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  272. MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  273. if(appDelegate.bLogin==false)
  274. {
  275. LoginViewController * loginvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
  276. loginvc.returnValue = ^(bool blogin){
  277. if(blogin)
  278. {
  279. if(appDelegate.user_type==USER_ROLE_EMPLOYEE)
  280. {
  281. [main_vc checklogin:false];
  282. NSString* msg =@"";
  283. // if(appDelegate.contact_id.length>0)
  284. // {
  285. // msg = [msg stringByAppendingString:@"Customer:"];
  286. // msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  287. //
  288. // }
  289. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  290. //block代码块取代了delegate
  291. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  292. // vc.disable_refresh = true;
  293. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  294. ovc.showNavibar = true;
  295. //ovc.customer_id = appDelegate.contact_id;
  296. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  297. [holder performSelector:addtocart];
  298. };
  299. ovc.init_style = OL_OPEN;
  300. ovc.onCancel = ^(){
  301. // self.disable_refresh = false;
  302. };
  303. [vc.navigationController pushViewController:ovc animated:true];
  304. }];
  305. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  306. {
  307. //create new;
  308. // self.disable_refresh = true;
  309. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  310. {
  311. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  312. cvc.showNavibar = true;
  313. cvc.contact_type = @"Sales_Order_Customer";
  314. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  315. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  316. appDelegate.customerInfo = value;
  317. if(appDelegate.order_code==nil)
  318. [self neworder:vc selectorholder:holder selector:addtocart];
  319. // neworder();
  320. // [main_vc checklogin:true];
  321. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  322. //
  323. // if(self.returnValue)
  324. // self.returnValue(value);
  325. };
  326. cvc.onCancel = ^(){
  327. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  328. // self.disable_refresh = false;
  329. };
  330. cvc.onReset = ^(){
  331. // [main_vc checklogin:true];
  332. };
  333. [vc.navigationController pushViewController:cvc animated:true];
  334. }
  335. else
  336. {
  337. [self neworder:vc selectorholder:holder selector:addtocart];
  338. }
  339. }
  340. NSLog(@"No");
  341. }];
  342. [alertControl addAction:actionOne];
  343. [alertControl addAction:alertthree];
  344. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  345. }];
  346. [alertControl addAction:alertcancel];
  347. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  348. [vc presentViewController:alertControl animated:YES completion:nil];
  349. }
  350. else
  351. {
  352. //customer login;
  353. [main_vc checklogin:false];
  354. //[self addtocart];
  355. [holder performSelector:addtocart];
  356. }
  357. }
  358. };
  359. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
  360. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  361. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  362. [vc presentViewController:navi animated:YES completion:^{
  363. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  364. NSLog(@"LoginViewController present.........");
  365. // self.btop = false;
  366. // <#code#>
  367. }];
  368. }
  369. else
  370. {
  371. if(appDelegate.user_type==USER_ROLE_EMPLOYEE&&/*appDelegate.contact_id==nil&&*/appDelegate.order_code==nil)
  372. {
  373. if(appDelegate.contact_id.length==0)
  374. {
  375. NSString* msg =@"";
  376. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  377. //block代码块取代了delegate
  378. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  379. // vc.disable_refresh = true;
  380. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  381. ovc.showNavibar = true;
  382. //ovc.customer_id = appDelegate.contact_id;
  383. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  384. [holder performSelector:addtocart];
  385. };
  386. ovc.init_style = OL_OPEN;
  387. ovc.onCancel = ^(){
  388. // self.disable_refresh = false;
  389. };
  390. [vc.navigationController pushViewController:ovc animated:true];
  391. }];
  392. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  393. {
  394. //create new;
  395. // self.disable_refresh = true;
  396. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  397. {
  398. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  399. cvc.showNavibar = true;
  400. cvc.contact_type = @"Sales_Order_Customer";
  401. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  402. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  403. appDelegate.customerInfo = value;
  404. if(appDelegate.order_code==nil)
  405. [self neworder:vc selectorholder:holder selector:addtocart];
  406. // neworder();
  407. // [main_vc checklogin:true];
  408. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  409. //
  410. // if(self.returnValue)
  411. // self.returnValue(value);
  412. };
  413. cvc.onCancel = ^(){
  414. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  415. // self.disable_refresh = false;
  416. };
  417. cvc.onReset = ^(){
  418. // [main_vc checklogin:true];
  419. };
  420. [vc.navigationController pushViewController:cvc animated:true];
  421. }
  422. else
  423. {
  424. [self neworder:vc selectorholder:holder selector:addtocart];
  425. }
  426. }
  427. NSLog(@"No");
  428. }];
  429. [alertControl addAction:actionOne];
  430. [alertControl addAction:alertthree];
  431. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  432. }];
  433. [alertControl addAction:alertcancel];
  434. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  435. [vc presentViewController:alertControl animated:YES completion:nil];
  436. }
  437. else
  438. {
  439. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Checking Pending Order"];
  440. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  441. NSDictionary* return_json = [iSalesNetwork request_PendingOrder:appDelegate.contact_id];
  442. dispatch_async(dispatch_get_main_queue(), ^{
  443. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  444. if([[return_json valueForKey:@"result"] intValue]==2)
  445. {
  446. bool openPendingOrder= [[return_json valueForKey:@"hasPending"] boolValue];
  447. bool createNewOrder=appDelegate.can_create_order;
  448. if(openPendingOrder&&createNewOrder)
  449. {
  450. NSString* msg =@"";
  451. if(appDelegate.contact_id.length>0)
  452. {
  453. msg = [msg stringByAppendingString:@"Customer:"];
  454. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  455. }
  456. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  457. //block代码块取代了delegate
  458. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  459. // vc.disable_refresh = true;
  460. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  461. ovc.showNavibar = true;
  462. ovc.customer_id = appDelegate.contact_id;
  463. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  464. [holder performSelector:addtocart];
  465. };
  466. ovc.init_style = OL_OPEN;
  467. ovc.onCancel = ^(){
  468. // self.disable_refresh = false;
  469. };
  470. [vc.navigationController pushViewController:ovc animated:true];
  471. }];
  472. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  473. {
  474. //create new;
  475. // self.disable_refresh = true;
  476. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  477. {
  478. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  479. cvc.showNavibar = true;
  480. cvc.contact_type = @"Sales_Order_Customer";
  481. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  482. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  483. appDelegate.customerInfo = value;
  484. if(appDelegate.order_code==nil)
  485. [self neworder:vc selectorholder:holder selector:addtocart];
  486. // neworder();
  487. // [main_vc checklogin:true];
  488. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  489. //
  490. // if(self.returnValue)
  491. // self.returnValue(value);
  492. };
  493. cvc.onCancel = ^(){
  494. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  495. // self.disable_refresh = false;
  496. };
  497. cvc.onReset = ^(){
  498. // [main_vc checklogin:true];
  499. };
  500. [vc.navigationController pushViewController:cvc animated:true];
  501. }
  502. else
  503. {
  504. [self neworder:vc selectorholder:holder selector:addtocart];
  505. }
  506. }
  507. NSLog(@"No");
  508. }];
  509. [alertControl addAction:actionOne];
  510. [alertControl addAction:alertthree];
  511. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  512. }];
  513. [alertControl addAction:alertcancel];
  514. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  515. [vc presentViewController:alertControl animated:YES completion:nil];
  516. }
  517. else
  518. {
  519. if(openPendingOrder)
  520. {
  521. NSString* msg =@"";
  522. if(appDelegate.contact_id.length>0)
  523. {
  524. msg = [msg stringByAppendingString:@"Customer:"];
  525. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  526. }
  527. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  528. //block代码块取代了delegate
  529. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  530. // vc.disable_refresh = true;
  531. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  532. ovc.showNavibar = true;
  533. ovc.customer_id = appDelegate.contact_id;
  534. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  535. [holder performSelector:addtocart];
  536. };
  537. ovc.init_style = OL_OPEN;
  538. ovc.onCancel = ^(){
  539. // self.disable_refresh = false;
  540. };
  541. [vc.navigationController pushViewController:ovc animated:true];
  542. }];
  543. [alertControl addAction:actionOne];
  544. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  545. }];
  546. [alertControl addAction:alertcancel];
  547. // [alertControl addAction:alertthree];
  548. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  549. [vc presentViewController:alertControl animated:YES completion:nil];
  550. }
  551. else if(createNewOrder)
  552. {
  553. NSString* msg =@"";
  554. if(appDelegate.contact_id.length>0)
  555. {
  556. msg = [msg stringByAppendingString:@"Customer:"];
  557. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  558. }
  559. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  560. //block代码块取代了delegate
  561. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  562. {
  563. //create new;
  564. // self.disable_refresh = true;
  565. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  566. {
  567. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  568. cvc.showNavibar = true;
  569. cvc.contact_type = @"Sales_Order_Customer";
  570. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  571. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  572. appDelegate.customerInfo = value;
  573. if(appDelegate.order_code==nil)
  574. [self neworder:vc selectorholder:holder selector:addtocart];
  575. // neworder();
  576. // [main_vc checklogin:true];
  577. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  578. //
  579. // if(self.returnValue)
  580. // self.returnValue(value);
  581. };
  582. cvc.onCancel = ^(){
  583. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  584. // self.disable_refresh = false;
  585. };
  586. cvc.onReset = ^(){
  587. // [main_vc checklogin:true];
  588. };
  589. [vc.navigationController pushViewController:cvc animated:true];
  590. }
  591. else
  592. {
  593. [self neworder:vc selectorholder:holder selector:addtocart];
  594. }
  595. }
  596. NSLog(@"No");
  597. }];
  598. // [alertControl addAction:actionOne];
  599. [alertControl addAction:alertthree];
  600. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  601. }];
  602. [alertControl addAction:alertcancel];
  603. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  604. [vc presentViewController:alertControl animated:YES completion:nil];
  605. }
  606. else
  607. {
  608. [RAUtils message_alert:[return_json valueForKey:@"You donot have permission to access order"] title:@"Add To Cart" controller:vc];
  609. }
  610. }
  611. }
  612. else
  613. {
  614. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Check Pending Order" controller:vc] ;
  615. }
  616. });
  617. });
  618. }
  619. // // [main_vc checklogin:false];
  620. //
  621. // if(appDelegate.can_create_order)
  622. // {
  623. // NSString* msg =@"";
  624. // if(appDelegate.contact_id.length>0)
  625. // {
  626. // msg = [msg stringByAppendingString:@"\n\nCustomer:"];
  627. // msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  628. //
  629. // }
  630. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil),NSLocalizedString(@"Create new order", nil), nil];
  631. //
  632. // // alert.
  633. // [alert show];
  634. // }
  635. // else
  636. // {
  637. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil), nil];
  638. //
  639. // // alert.
  640. // [alert show];
  641. // }
  642. }
  643. else
  644. {
  645. // if(appDelegate.order_code==nil)
  646. // [ self neworder];
  647. // else
  648. [holder performSelector:addtocart];
  649. }
  650. }
  651. }
  652. +(void) add_recent_model:(NSDictionary*) model
  653. {
  654. NSMutableDictionary * newdict = [[NSMutableDictionary alloc]init];
  655. [newdict setObject:model forKey:@"item_0"];
  656. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  657. int count=[appDelegate.recent_model[@"count"] intValue];
  658. for(int i=0;i<count;i++)
  659. {
  660. NSMutableDictionary * mitem= appDelegate.recent_model[[NSString stringWithFormat:@"item_%d",i]];
  661. if([mitem[@"product_id"] isEqualToString:model[@"product_id"]])
  662. continue;
  663. [newdict setObject:mitem forKey:[NSString stringWithFormat:@"item_%lu",(unsigned long)newdict.allKeys.count]];
  664. }
  665. newdict[@"count"]=[NSString stringWithFormat:@"%lu",(unsigned long)newdict.allKeys.count];
  666. appDelegate.recent_model = newdict;
  667. //
  668. //
  669. // if(!bexist)
  670. // {
  671. // [appDelegate.recent_model setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
  672. // appDelegate.recent_model[@"count"]=[NSString stringWithFormat:@"%d",count+1];
  673. // }
  674. }
  675. +(void) alert_view :(NSString*) msg title:(NSString*) title
  676. {
  677. if(title==nil)
  678. title = @"Message";
  679. if(msg.length>0)
  680. {
  681. title=[NSString stringWithFormat:@"%@\n\n%@",title,msg];
  682. }
  683. UIAlertView * alert = [[UIAlertView alloc] initWithTitle: title message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
  684. [alert show];
  685. }
  686. + (long long) freeDiskSpaceInMegaBytes{
  687. struct statfs buf;
  688. long long freespace = -1;
  689. if(statfs("/var", &buf) >= 0){
  690. freespace = (long long)(buf.f_bsize * buf.f_bfree);
  691. }
  692. NSLog([NSString stringWithFormat:@"手机剩余存储空间为:%qi MB" ,freespace/1024/1024]);
  693. return freespace/1024/1024;
  694. }
  695. +(UIAlertView * ) waiting_alert :(NSString*) msg title:(NSString*) title
  696. {
  697. if(title==nil)
  698. title = @"Please Wait";
  699. if(msg==nil)
  700. msg= @"Waiting...";
  701. NSAssert(msg!=nil, @"error message from json is nil");
  702. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  703. [alert show];
  704. //
  705. //
  706. // UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
  707. // aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
  708. // // check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
  709. //// if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
  710. //// [alert setValue:aiView forKey:@"accessoryView"];
  711. //// }else{
  712. //// [alert addSubview:aiView];
  713. //// }
  714. //
  715. // aiView.hidden = false;
  716. // aiView.hidesWhenStopped = false;
  717. // [aiView startAnimating];
  718. //
  719. //[alert addSubview:aiView];
  720. return alert;
  721. //return nil;
  722. // return alert;
  723. // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
  724. //[alert show];
  725. }
  726. +(NSDictionary*) device_info
  727. {
  728. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  729. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  730. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  731. NSString* versionNum = [NSString stringWithFormat:@"Version: %@ Build %@",version,build];
  732. NSMutableDictionary * info = [[NSMutableDictionary alloc]init];
  733. [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  734. [info setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
  735. [info setValue:[[UIDevice currentDevice] model] forKey:@"model"];
  736. [info setValue:versionNum forKey:@"ver"];
  737. [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
  738. return info;
  739. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  740. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  741. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  742. }
  743. +(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
  744. {
  745. NSArray *stringArray = [string componentsSeparatedByString:separator];
  746. return stringArray;
  747. }
  748. +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim
  749. {
  750. NSMutableArray * marr = [arr mutableCopy];
  751. begin:
  752. for (NSString* item in marr) {
  753. if(item.length==0 )
  754. if( btrim)
  755. {
  756. [marr removeObject:item];
  757. goto begin;
  758. }
  759. }
  760. NSString * ret = [marr componentsJoinedByString:separator];
  761. return ret;
  762. }
  763. +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim brackets:(NSString*)brackets
  764. {
  765. if(brackets!=nil)
  766. separator = [NSString stringWithFormat:@"%@%@%@",brackets,separator,brackets];
  767. NSMutableArray * marr = [arr mutableCopy];
  768. begin:
  769. for (NSString* item in marr) {
  770. if(item.length==0 )
  771. if( btrim)
  772. {
  773. [marr removeObject:item];
  774. goto begin;
  775. }
  776. }
  777. NSString * ret = [marr componentsJoinedByString:separator];
  778. if(brackets!=nil)
  779. ret = [NSString stringWithFormat:@"%@%@%@",brackets,ret,brackets];
  780. return ret;
  781. }
  782. +(NSDictionary*) string2dict:(NSString*) str
  783. {
  784. if(str==nil)
  785. return nil;
  786. NSError *error = nil;
  787. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
  788. options: NSJSONReadingMutableContainers
  789. error: &error];
  790. NSLog(@"%@",string2dic);
  791. return string2dic;
  792. }
  793. +(UIColor*) strColor:(NSString*) color
  794. {
  795. if([color.lowercaseString isEqualToString:@"red"])
  796. return [UIColor redColor];
  797. return [UIColor blackColor];
  798. }
  799. +(NSString*) dict2string:(NSDictionary*) dict
  800. {
  801. if(dict==nil)
  802. return nil;
  803. // 将NSDictionary转化为NSData
  804. NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
  805. // 再将NSData转为字符串
  806. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  807. return jsonStr;
  808. }
  809. +(NSString*) base64en:(NSString*) string
  810. {
  811. if(string == nil)
  812. return nil;
  813. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  814. NSString *stringBase64 = [data base64EncodedStringWithOptions:0]; // base64格式的字符串
  815. return stringBase64;
  816. }
  817. +(NSString*) base64de:(NSString*) stringBase64
  818. {
  819. if(stringBase64==nil)
  820. return nil;
  821. NSData *data = [[NSData alloc] initWithBase64EncodedString:stringBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
  822. NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  823. return string;
  824. }
  825. +(void) deletefiles :(NSString*) path
  826. {
  827. // NSString *extension = @"m4r";
  828. NSFileManager *fileManager = [NSFileManager defaultManager];
  829. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  830. // NSString *documentsDirectory = [paths objectAtIndex:0];
  831. NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
  832. NSEnumerator *e = [contents objectEnumerator];
  833. NSString *filename;
  834. while ((filename = [e nextObject])) {
  835. bool result= [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
  836. if(!result)
  837. NSLog(@"delete file failed %@------%@",path,filename);
  838. }
  839. }
  840. +(NSMutableArray*)dictionary2array:(NSDictionary*)json count_fields:(NSString*) count_fields item_mark:(NSString*) item_mark items_mark:(NSString* )items_mark
  841. {
  842. if(json==nil)
  843. return nil;
  844. NSMutableArray* ret = [[NSMutableArray alloc] init];
  845. int count = [[json valueForKey:count_fields] intValue];
  846. NSDictionary* items = nil;
  847. if(items_mark==nil)
  848. items = json;
  849. else
  850. items = [json objectForKey:items_mark];
  851. for(int i=0;i<count;i++)
  852. {
  853. NSDictionary* obj = [items objectForKey:[NSString stringWithFormat:@"%@%d",item_mark,i]];
  854. [ret addObject:obj];
  855. }
  856. return ret;
  857. }
  858. +(NSDictionary*) error_json :(int)code err_msg:(NSString*)msg
  859. {
  860. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  861. //#define RESULT_FALSE 0
  862. //#define RESULT_TRUE 2
  863. //#define RESULT_NET_ERROR -3
  864. //#define RESULT_NET_NOTAVAILABLE -4
  865. //#define RESULT_ERROR -5
  866. //#define RESULT_LOCALFILE_ERROR -7
  867. //#define RESULT_USERAUTH_ERROR -9
  868. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  869. //#define RESULT_SESSION_EXPIRED -13
  870. //#define RESULT_VER_LOW
  871. if(msg.length<=0)
  872. {
  873. switch (code) {
  874. case RESULT_NET_NOTAVAILABLE:
  875. msg= MSG_NET_NOTAVAILABLE;
  876. break;
  877. default:
  878. // assert(@"UNDEFINE ERROR CODE!");
  879. break;
  880. }
  881. }
  882. // if(code==RESULT_NET_NOTAVAILABLE)
  883. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  884. // else
  885. [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
  886. [ret setValue:msg forKey:@"err_msg"];
  887. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  888. // options:0
  889. // error:nil];
  890. return ret;
  891. }
  892. + (CGRect)relativeFrameForScreenWithView:(UIView *)v
  893. {
  894. UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
  895. CGRect rect=[v convertRect: v.bounds toView:window];
  896. return rect;
  897. // BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
  898. //
  899. // CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  900. // if (!iOS7) {
  901. // screenHeight -= 20;
  902. // }
  903. // UIView *view = v;
  904. // CGFloat x = .0;
  905. // CGFloat y = .0;
  906. // while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
  907. // x += view.frame.origin.x;
  908. // y += view.frame.origin.y;
  909. // view = view.superview;
  910. // if ([view isKindOfClass:[UIScrollView class]]) {
  911. // x -= ((UIScrollView *) view).contentOffset.x;
  912. // y -= ((UIScrollView *) view).contentOffset.y;
  913. // }
  914. // }
  915. // return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
  916. }
  917. @end