DocumentPageViewController.m 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. //
  2. // DocumentPageViewController.m
  3. // AntsContract
  4. //
  5. // Created by Ray on 12/16/16.
  6. // Copyright © 2016 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "DocumentPageViewController.h"
  9. #import "PageViewController.h"
  10. #import "SignatureListViewController.h"
  11. #import "SignatureViewController.h"
  12. #import "PDFUtils.h"
  13. #import "ACNetwork.h"
  14. //#import "AFHTTPSessionManager.h"
  15. #import "AppDelegate.h"
  16. #import "ACNetwork.h"
  17. #import "RAUtils.h"
  18. #import "PDFViewController.h"
  19. #import "config.h"
  20. #import "AESCrypt.h"
  21. #import "CustomIOSAlertView.h"
  22. #import "ImageUtils.h"
  23. #import "PDFPage.h"
  24. #import "TextDrawable.h"
  25. #import "ImageDrawable.h"
  26. #import "RectDrawable.h"
  27. @interface DocumentPageViewController ()
  28. @end
  29. @implementation DocumentPageViewController
  30. -(NSMutableDictionary*) templateInit:(NSMutableDictionary*) template
  31. {
  32. NSString* temp = NSTemporaryDirectory();
  33. NSString* filename =[NSString stringWithFormat:@"%@.png", [[NSUUID UUID] UUIDString]];
  34. NSString* qrpath=[temp stringByAppendingPathComponent:filename];
  35. UIImage* qrimg=[RAUtils generateBarCode:self.docment_id width:300 height:44];//[QRCodeGenerator qrImageForString:order_code imageSize:240];
  36. bool bwrite=[UIImagePNGRepresentation(qrimg)writeToFile: qrpath atomically:YES];
  37. for(int i=0;i<[template[@"count"] intValue];i++)
  38. {
  39. NSMutableDictionary* page =template[[NSString stringWithFormat:@"page_%d",i]];
  40. for(int j=0;j<[page[@"count"] intValue];j++)
  41. {
  42. NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
  43. NSString* type = control[@"type"];
  44. NSString* field =control[@"field"];
  45. if([type isEqualToString:@"Label"])
  46. {
  47. if([field isEqualToString:@"doc_number"])
  48. {
  49. control[@"value"]= self.docment_id;
  50. }
  51. }
  52. else if([type isEqualToString:@"Image"])
  53. {
  54. NSString* name =control[@"name"];
  55. if([name isEqualToString:@"BarCode"])
  56. {
  57. if(bwrite)
  58. control[@"value"]= qrpath;
  59. }
  60. }
  61. else if([type isEqualToString:@"DatePicker"])
  62. {
  63. NSString* name =control[@"aname"];
  64. if([name isEqualToString:@"Today's Date"])
  65. {
  66. NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
  67. [formatter setDateFormat:@"MM/dd/yyyy"];
  68. NSString* date = [formatter stringFromDate:[NSDate date]] ;
  69. control[@"value"]= date;
  70. }
  71. }
  72. }
  73. }
  74. return template;
  75. }
  76. - (void)viewDidLoad {
  77. [super viewDidLoad];
  78. self.title = self.docment_id;
  79. // self.delegate = self;
  80. // self.dataSource = self;
  81. self.signatureData= [[NSMutableDictionary alloc] init];
  82. self.document = [PDFUtils OpenPDF:self.pdfPath];
  83. self.total_page = CGPDFDocumentGetNumberOfPages (self.document);
  84. self.controlTemplate = [self templateInit:[PDFUtils loadControl:self.templatePath]];
  85. // self.title = [NSString stringWithFormat:@"%@ [%d/%ld]", self.docment_id,1, self.total_page ];
  86. PageViewController* startingViewController=[self viewControllerAtIndex:0];
  87. // NSArray* viewControllers =[NSArray arrayWithObjects:page_0,nil];
  88. self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
  89. self.pageViewController.delegate = self;
  90. // PageViewController *startingViewController = [self viewControllerAtIndex:0 storyboard:self.storyboard];
  91. NSArray *viewControllers = @[startingViewController];
  92. [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
  93. self.pageViewController.dataSource = self;
  94. [self addChildViewController:self.pageViewController];
  95. [self.view addSubview:self.pageViewController.view];
  96. // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
  97. CGRect pageViewRect = self.view.bounds;
  98. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
  99. pageViewRect = pageViewRect;//CGRectInset(pageViewRect, 40.0, 40.0);
  100. }
  101. self.pageViewController.view.frame = pageViewRect;
  102. [self.pageViewController didMoveToParentViewController:self];
  103. // Do any additional setup after loading the view.
  104. }
  105. -(void) dealloc
  106. {
  107. CFRelease(self.document);
  108. }
  109. - (void)didReceiveMemoryWarning {
  110. [super didReceiveMemoryWarning];
  111. // Dispose of any resources that can be recreated.
  112. }
  113. - (IBAction)OnCancelClicked:(id)sender {
  114. if(self.no_save|| self.hide_control)
  115. {
  116. [self.navigationController popToRootViewControllerAnimated:false];
  117. return;
  118. }
  119. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Are you sure cancel customer? All your entered information will lost." message:nil preferredStyle:UIAlertControllerStyleAlert];
  120. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  121. [self.navigationController popToRootViewControllerAnimated:false];
  122. }];
  123. // [alertControl addAction:actionOne];
  124. [alertControl addAction:alertthree];
  125. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  126. }];
  127. [alertControl addAction:alertcancel];
  128. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  129. [self presentViewController:alertControl animated:YES completion:nil];
  130. }
  131. - (IBAction)onSignatureClicked:(id)sender {
  132. // CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
  133. //
  134. //
  135. // CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
  136. //
  137. // DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
  138. SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
  139. signatureVC.title=@"Signatures";
  140. signatureVC.signatureData = self.signatureData;
  141. signatureVC.blk_Add = ^()
  142. {
  143. __block UIImage* signimg=nil;
  144. SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
  145. vc.onReturnImg = ^(UIImage* img)
  146. {
  147. signimg = img;
  148. // if(signimg!=nil)
  149. // [PDFUtils addSignature:signimg to:self.signatureData];
  150. };
  151. // orderinfoVC.url_type = URL_REMOTE;
  152. // orderinfoVC.request_url=URL_CARTDELIVERY;
  153. //
  154. // orderinfoVC.params = params;
  155. //
  156. // orderinfoVC.delegate=self;
  157. //
  158. // if(checked.count==count)
  159. // {
  160. // orderinfoVC.have_tail = true
  161. // }
  162. [self.navigationController pushViewController:vc animated:true];
  163. };
  164. // signatureVC.blk_Fill =^(NSString* file, bool fillFullDoc)
  165. // {
  166. //
  167. //
  168. // for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
  169. // {
  170. // NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
  171. // if(!fillFullDoc && i!=self.current_page)
  172. // continue;
  173. // for(int j=0;j<[page[@"count"] intValue];j++)
  174. // {
  175. // NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
  176. // NSString* type = control[@"type"];
  177. // if(![type isEqualToString:@"Signature"])
  178. // continue;
  179. //
  180. // control[@"value"]=file;
  181. //
  182. //// NSString* name = control[@"aname"];
  183. //// bool required = [control[@"required"] boolValue];
  184. ////
  185. //// if(required==false)
  186. //// continue;
  187. //// if([type isEqualToString:@"Check"])
  188. //// {
  189. //// NSArray* arr = control[@"value"];
  190. //// if(arr.count==0)
  191. //// {
  192. //// ret=false;
  193. ////
  194. //// NSString* msg=[NSString stringWithFormat:@"%u Page %d %@ is missing.",fields.count+1,i+1,name];
  195. //// if(fields.count<15)
  196. //// [fields addObject:msg];
  197. //// else
  198. //// more++;
  199. //// }
  200. ////
  201. //// }
  202. //// else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
  203. //// {
  204. //// continue;
  205. //// }
  206. //// else
  207. //// {
  208. //// NSString* str = control[@"value"];
  209. //// if(str.length==0)
  210. //// {
  211. //// ret=false;
  212. //// NSString* msg=[NSString stringWithFormat:@"%lu Page %d %@ is missing.",fields.count+1,i+1,name];
  213. //// if(fields.count<15)
  214. //// [fields addObject:msg];
  215. //// else
  216. //// more++;
  217. //// }
  218. //// }
  219. // }
  220. // }
  221. //
  222. //
  223. // // NSString* file_name=[file lastPathComponent];
  224. ////
  225. //// NSData* img_data=[ImageUtils load_img:file];
  226. ////
  227. //// if(img_data!=nil)
  228. //// {
  229. ////
  230. //// UIImage* image=[UIImage imageWithData:img_data];
  231. //// touchImageView.image = image;
  232. ////
  233. //// long index = touchImageView.tag - CONTROL_BASE;
  234. //// self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
  235. ////
  236. //// }
  237. //
  238. // };
  239. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
  240. navi.modalPresentationStyle=UIModalPresentationPopover;
  241. UIPopoverPresentationController* popPc = navi.popoverPresentationController;
  242. popPc.permittedArrowDirections = UIPopoverArrowDirectionUp;
  243. popPc.barButtonItem = sender;
  244. popPc.delegate = nil;
  245. [self presentViewController:navi animated:true completion:nil];
  246. //// menu.selector = self.selector;
  247. ////
  248. //// menu.selectordelegate = self;
  249. //
  250. // // 1.创建一个UIPopover
  251. // UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
  252. //
  253. //
  254. //
  255. // UIPopoverPresentationController
  256. // // 2.设置尺寸
  257. // // popover.popoverContentSize = CGSizeMake(320, 44 * 5);
  258. //
  259. // // 3.从哪里显示出来 --> 指向item
  260. //
  261. // [popover presentPopoverFromRect:self.view.frame inView:self.view permittedArrowDirections:0 animated:YES];
  262. // // [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
  263. //
  264. //// self.popover = popover;
  265. // popover pop
  266. //
  267. // [self performSegueWithIdentifier:@"selector_popover" sender:self];
  268. }
  269. -(CGRect)WindowRect2PDFRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size
  270. {
  271. CGRect pdf_expand;
  272. float offset_x = 0;
  273. float offset_y = 0;
  274. float scale =1;
  275. if(pdf_rect.size.height>=pdf_rect.size.width)
  276. {
  277. pdf_expand = CGRectMake(0, 0, pdf_rect.size.height*window_size.width/window_size.height, pdf_rect.size.height);
  278. offset_x = (pdf_expand.size.width-pdf_rect.size.width)/2;
  279. scale = pdf_rect.size.height/window_size.height;
  280. }
  281. else
  282. {
  283. pdf_expand = CGRectMake(0, 0, pdf_rect.size.width, pdf_rect.size.width*window_size.height/window_size.width);
  284. offset_y = (pdf_expand.size.height-pdf_rect.size.height)/2;
  285. scale = pdf_rect.size.width/window_size.width;
  286. }
  287. float x=rect.origin.x*scale-offset_x;
  288. float y=rect.origin.y*scale-offset_y;
  289. float width = rect.size.width*scale;
  290. float height = rect.size.height*scale;
  291. return CGRectMake(x, y, width, height);
  292. }
  293. -(void) EndEditing
  294. {
  295. NSArray* arr =self.pageViewController.viewControllers;
  296. PageViewController *currentViewController = (PageViewController*)self.pageViewController.viewControllers[0];
  297. // PageViewController *currentViewController = (PageViewController*)self.pageViewController.viewControllers[self.current_page];
  298. [currentViewController EndEditing];
  299. }
  300. - (IBAction)onSaveClicked:(id)sender {
  301. [self EndEditing];
  302. if(self.no_save)
  303. {
  304. [RAUtils message_alert:@"Can not save pending document under offline mode." title:@"Save document" controller:self] ;
  305. return;
  306. }
  307. if([self verifyData]==false)
  308. return;
  309. NSString* pdffile = nil;
  310. NSString* zipfile = nil;
  311. NSString* jsonfile = nil;
  312. // for(int l=0;l<1;l++)
  313. {
  314. if(self.hide_control)
  315. {
  316. pdffile = self.pdfPath;
  317. }
  318. else
  319. {
  320. pdffile = [PDFUtils SavePDF:self.controlTemplate source:self.document window_rect:CGRectMake(0, 0, 768, 960) name:self.docment_id isnew:self.action==PDFEditActionNew];
  321. }
  322. zipfile=[ACNetwork prepareUploadFile:pdffile json:self.controlTemplate];
  323. //jsonfile = [ACNetwork getjsonPath:zip];
  324. }
  325. __weak typeof(self) weakSelf = self;
  326. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  327. if(appDelegate.accessMode == AppAccessModeOffline)
  328. {
  329. NSMutableDictionary * json = [[NSMutableDictionary alloc]init];
  330. json[@"json"]=@"json.json";
  331. json[@"pdf"]=pdffile.lastPathComponent;
  332. json[@"zip"]=zipfile.lastPathComponent;
  333. json[@"serial"]=[json[@"zip"] stringByDeletingPathExtension];
  334. json[@"create_by"]=appDelegate.user;
  335. json[@"agent_name"]=[self extract_data:@"agent_name"];
  336. json[@"doc_number"]=[self extract_data:@"doc_number"];
  337. json[@"job_date"]=[self extract_data:@"job_date"];
  338. json[@"customer_name"]=[self extract_data:@"customer_name"];
  339. json[@"signed_date"]=[self extract_data:@"signed_date"];
  340. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  341. NSMutableArray * arr_pending = [[defaults arrayForKey:@"pending_doc"] mutableCopy];
  342. if(arr_pending==nil)
  343. arr_pending = [[NSMutableArray alloc]init];
  344. [arr_pending addObject:json];
  345. [defaults setObject:arr_pending forKey:@"pending_doc"];
  346. [defaults synchronize];
  347. [weakSelf.navigationController popToRootViewControllerAnimated:false];
  348. if(weakSelf.OnSave)
  349. weakSelf.OnSave(pdffile,@"");
  350. }
  351. else
  352. {
  353. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
  354. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  355. NSDictionary* json = nil;
  356. json = [ACNetwork save_document:zipfile isnew:self.action==PDFEditActionNew];
  357. dispatch_async(dispatch_get_main_queue(), ^{
  358. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  359. // if([[logout_json valueForKey:@"result"] intValue]==2)
  360. // {
  361. // self.welcomeLabel.text=@"Not sign in";
  362. // // [sender setTitle:@"Sign in" forState:UIControlStateNormal];
  363. // [bbitem setTitle:@"Sign in"];
  364. //
  365. // self.buttonHIC.enabled = false;
  366. // self.buttonSRL.enabled = false;
  367. // self.coverView.hidden = false;
  368. // }
  369. // else
  370. // {
  371. // [RAUtils message_alert:[logout_json valueForKey:@"err_msg"] title:@"Sign out" controller:self] ;
  372. // }
  373. if([[json valueForKey:@"result"] intValue]==2)
  374. {
  375. [weakSelf.navigationController popToRootViewControllerAnimated:false];
  376. if(weakSelf.OnSave)
  377. weakSelf.OnSave(pdffile,json[@"subject"]);
  378. }
  379. else
  380. {
  381. // [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
  382. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Create Customer" message:@"Can not create new customer on server, do you want to create an offline document?" preferredStyle:UIAlertControllerStyleAlert];
  383. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  384. __block NSString* offline_docnumber =[ACNetwork offline_docnumber];
  385. if(offline_docnumber==nil)
  386. {
  387. [RAUtils message_alert:@"Offline document number prefix not found, Please check your user name and make sure you had signed in at least once." title:@"Create Customer" controller:self] ;
  388. return;
  389. }
  390. [appDelegate SwitchToOffline:appDelegate.user];
  391. NSMutableDictionary * json = [[NSMutableDictionary alloc]init];
  392. json[@"json"]=@"json.json";
  393. json[@"pdf"]=pdffile.lastPathComponent;
  394. json[@"zip"]=zipfile.lastPathComponent;
  395. json[@"serial"]=[json[@"zip"] stringByDeletingPathExtension];
  396. json[@"create_by"]=appDelegate.user;
  397. json[@"agent_name"]=[self extract_data:@"agent_name"];
  398. json[@"doc_number"]=[self extract_data:@"doc_number"];
  399. json[@"job_date"]=[self extract_data:@"job_date"];
  400. json[@"customer_name"]=[self extract_data:@"customer_name"];
  401. json[@"signed_date"]=[self extract_data:@"signed_date"];
  402. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  403. NSMutableArray * arr_pending = [[defaults arrayForKey:@"pending_doc"] mutableCopy];
  404. if(arr_pending==nil)
  405. arr_pending = [[NSMutableArray alloc]init];
  406. [arr_pending addObject:json];
  407. [defaults setObject:arr_pending forKey:@"pending_doc"];
  408. [defaults synchronize];
  409. [weakSelf.navigationController popToRootViewControllerAnimated:false];
  410. if(weakSelf.OnSave)
  411. weakSelf.OnSave(pdffile,@"");
  412. }];
  413. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  414. DebugLog(@"Cancel");
  415. }];
  416. [alertControl addAction:actionOne];
  417. [alertControl addAction:alertthree];
  418. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  419. [self presentViewController:alertControl animated:YES completion:nil];
  420. }
  421. });
  422. });
  423. }
  424. // return;
  425. // {
  426. //
  427. //
  428. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
  429. //
  430. //
  431. //// self.uploadProgress.progress = 0;
  432. //
  433. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  434. //
  435. //
  436. // {
  437. //
  438. // // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  439. // // [waitalert show];
  440. //
  441. //// NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  442. //
  443. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  444. //
  445. //
  446. //
  447. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  448. //
  449. //// if(appDelegate.user!=nil)
  450. //// [params setValue:appDelegate.user forKey:@"user"];
  451. //// // if(appDelegate.contact_id!=nil)
  452. //// // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  453. //// if(appDelegate.password!=nil)
  454. //// [params setValue:appDelegate.password forKey:@"password"];
  455. //
  456. //
  457. // [params setValue:[AESCrypt AES128Encrypt:appDelegate.user key:@"usai2010"] forKey:@"user"];
  458. // [params setValue:[AESCrypt AES128Encrypt:appDelegate.password key:@"usai2010"] forKey:@"password"];
  459. //
  460. // [params setValue:@"deviceMain" forKey:@"_operate"];
  461. //
  462. //
  463. // UIDevice * dev = [UIDevice currentDevice];
  464. // NSUUID* uuid =dev.identifierForVendor;
  465. //#if TARGET_IPHONE_SIMULATOR//模拟器
  466. // [params setValue:@"simulator_uuid" forKey:@"deviceid"];
  467. //#elif TARGET_OS_IPHONE//真机
  468. // [params setValue:uuid.UUIDString forKey:@"deviceid"];
  469. //#endif
  470. //
  471. //
  472. //
  473. // NSMutableString *body=[[NSMutableString alloc]init];
  474. // //参数的集合的所有key的集合
  475. // NSArray *keys= [params allKeys];
  476. // DebugLog(@"================parms==================");
  477. // //遍历keys
  478. // for(int i=0;i<[keys count];i++)
  479. // {
  480. // //得到当前key
  481. // NSString *key=[keys objectAtIndex:i];
  482. // //如果key不是pic,说明value是字符类型,比如name:Boris
  483. // if(![key isEqualToString:@"pic"])
  484. // {
  485. //// //添加分界线,换行
  486. //// [body appendFormat:@"%@\r\n",MPboundary];
  487. // //添加字段名称,换2行
  488. // [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  489. // //添加字段的值
  490. // [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  491. // DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  492. // }
  493. // }
  494. // DebugLog(@"================parms==================");
  495. //
  496. // NSData* data = [NSData dataWithContentsOfFile: zipfile];
  497. //
  498. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_PDF parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  499. // [formData appendPartWithFileData:data name:@"upfile" fileName:[zipfile lastPathComponent] mimeType:@"application/zip"];
  500. // } error:nil];
  501. //
  502. //
  503. // // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  504. // // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  505. // // } error:nil];
  506. // //
  507. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  508. //
  509. //
  510. //
  511. // //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  512. //
  513. // //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
  514. //
  515. // //
  516. // NSProgress *progress = nil;
  517. //
  518. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  519. //
  520. // // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  521. //
  522. //
  523. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  524. //
  525. // if (error) {
  526. //
  527. // NSString* err_msg = [error localizedDescription];
  528. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  529. //
  530. //
  531. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  532. //
  533. // DebugLog(@"data string: %@",str);
  534. // [RAUtils message_alert:@"Can not connect to server please try again." title:@"Save document" controller:weakSelf] ;
  535. //
  536. // } else {
  537. // DebugLog(@"response ");
  538. //
  539. //
  540. //
  541. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  542. //
  543. // // 再将NSData转为字符串
  544. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  545. //
  546. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  547. //
  548. // DebugLog(@"data string: %@",jsonStr);
  549. //
  550. // NSDictionary* json = responseObject;
  551. //
  552. //
  553. //
  554. //
  555. // if([[json valueForKey:@"result"] intValue]==2)
  556. // {
  557. //
  558. // [weakSelf.navigationController popToRootViewControllerAnimated:false];
  559. ////
  560. ////
  561. // if(weakSelf.OnSave)
  562. // weakSelf.OnSave(pdffile);
  563. //
  564. //
  565. // }
  566. // else
  567. // {
  568. // [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
  569. // }
  570. //
  571. //
  572. // }
  573. // // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  574. // }];
  575. //
  576. //
  577. //
  578. //
  579. // // [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  580. // //
  581. //
  582. //
  583. //
  584. //
  585. //
  586. //
  587. // [uploadTask resume];
  588. //
  589. // }
  590. // }
  591. // [PDFUtils savep
  592. }
  593. -(void) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData
  594. {
  595. if(true)
  596. {
  597. NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)];
  598. int newidx = [self.signatureData[@"count"] intValue];
  599. // [@"file"]= newfile;
  600. NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
  601. item[@"file"]=newfile;
  602. signatureData[[NSString stringWithFormat:@"item_%d",newidx]] = item;
  603. signatureData[@"count"]=[NSNumber numberWithInt:newidx+1];
  604. }
  605. }
  606. -(NSString *) saveTempSignature:(NSData *) image
  607. {
  608. NSString* tempDir = NSTemporaryDirectory();
  609. NSString *saveFileName=[NSString stringWithFormat:@"%@.png",[[NSUUID UUID ] UUIDString] ] ;
  610. NSString *newFilePath=[tempDir stringByAppendingPathComponent:saveFileName];
  611. bool bsuccess=[image writeToFile:newFilePath atomically:YES];
  612. if(bsuccess)
  613. {
  614. return newFilePath;
  615. }
  616. else
  617. {
  618. return nil;
  619. }
  620. }
  621. /*
  622. #pragma mark - Navigation
  623. // In a storyboard-based application, you will often want to do a little preparation before navigation
  624. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  625. // Get the new view controller using [segue destinationViewController].
  626. // Pass the selected object to the new view controller.
  627. }
  628. */
  629. - (PageViewController *)viewControllerAtIndex:(NSUInteger)index
  630. {
  631. //Return the PDFViewController for the given index.
  632. if ((self.total_page == 0 )|| (index > self.total_page) ) {
  633. return nil;
  634. }
  635. //Create a new view controller and pass suitable data.
  636. // PageViewController *PageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
  637. PageViewController *PageViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PageViewController"];
  638. PageViewController.pageRef = CGPDFDocumentGetPage (self.document , index+1);
  639. PageViewController.pageIndex = index;
  640. PageViewController.hide_control = self.hide_control;
  641. __weak typeof(self) weakSelf = self;
  642. PageViewController.blk_Fill = ^(NSString* file,NSString* subtype,bool fillFullDoc)
  643. {
  644. for(int i=0;i<[weakSelf.controlTemplate[@"count"] intValue];i++)
  645. {
  646. NSMutableDictionary* page =weakSelf.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
  647. if(!fillFullDoc && i!=weakSelf.current_page)
  648. continue;
  649. for(int j=0;j<[page[@"count"] intValue];j++)
  650. {
  651. NSMutableDictionary* dest =page[[NSString stringWithFormat:@"control_%d",j]];
  652. NSString* type = dest[@"type"];
  653. if(![type isEqualToString:@"Signature"])
  654. continue;
  655. if([dest[@"name"] isEqualToString:subtype])
  656. {
  657. dest[@"value"]=file;
  658. }
  659. }
  660. }
  661. // NSString* file_name=[file lastPathComponent];
  662. //
  663. // NSData* img_data=[ImageUtils load_img:file];
  664. //
  665. // if(img_data!=nil)
  666. // {
  667. //
  668. // UIImage* image=[UIImage imageWithData:img_data];
  669. // touchImageView.image = image;
  670. //
  671. // long index = touchImageView.tag - CONTROL_BASE;
  672. // self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
  673. //
  674. // }
  675. };
  676. PageViewController.controlTemplate = self.controlTemplate[[NSString stringWithFormat:@"page_%lu",(unsigned long)index]];
  677. PageViewController.signatureData = self.signatureData;
  678. //PageViewController.pdfview = [self.pagePDF objectAtIndex:index];
  679. /*
  680. PageViewController.pdfview = [[PDFView alloc]initWithFrame:self.view.frame atPage:index];
  681. [PageViewController.view addSubview:PageViewController.pdfview];
  682. NSLog(@"index = %d",index);
  683. */
  684. return PageViewController;
  685. }
  686. - (NSUInteger) indexOfViewController:(PageViewController *)viewController
  687. {
  688. return viewController.pageIndex;//[self.pagePDF indexOfObject:viewController.pdfview];
  689. }
  690. - (NSString*) extract_data:(NSString*)field_name
  691. {
  692. for(int p=0;p<[self.controlTemplate[@"count"] intValue];p++)
  693. {
  694. NSDictionary* page=self.controlTemplate[[NSString stringWithFormat:@"page_%d",p]];
  695. for(int c=0;c<[page[@"count"] intValue];c++)
  696. {
  697. NSDictionary* control=page[[NSString stringWithFormat:@"control_%d",c]];
  698. if([control[@"field"] isEqualToString:field_name])
  699. {
  700. return control[@"value"]==nil?@"":control[@"value"];
  701. }
  702. }
  703. }
  704. return @"";
  705. }
  706. #pragma mark verify data
  707. - (UIView *)createDemoView:(NSString*) msg
  708. {
  709. UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 200)];
  710. // UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 270, 180)];
  711. // [imageView setImage:[UIImage imageNamed:@"demo"]];
  712. UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 270, 10)];
  713. titleLabel.font = [UIFont boldSystemFontOfSize:20];
  714. titleLabel.text=@"Missing fields:";
  715. titleLabel.numberOfLines = 0;
  716. titleLabel.lineBreakMode =NSLineBreakByWordWrapping;
  717. // titleLabel.textAlignment = NSTextAlignmentRight;
  718. titleLabel.textAlignment = NSTextAlignmentCenter;
  719. CGSize constraintkey = CGSizeMake(270, 20000.0f);//key label width is 40% cell width;
  720. CGSize sizetitle = [@"Missing fields:" sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  721. //[titleLabel sizeToFit];
  722. // titleLabel.center.x = demoView.center.x;
  723. titleLabel.frame = CGRectMake(10, 10, 270, sizetitle.height);
  724. [demoView addSubview:titleLabel];
  725. UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, 10)];
  726. lineLabel.font = [UIFont boldSystemFontOfSize:17];
  727. lineLabel.text=msg;
  728. lineLabel.numberOfLines = 0;
  729. lineLabel.lineBreakMode =NSLineBreakByWordWrapping;
  730. constraintkey = CGSizeMake(260, 20000.0f);
  731. CGSize sizemsg = [msg sizeWithFont:[UIFont boldSystemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  732. lineLabel.frame = CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, sizemsg.height);
  733. //[lineLabel sizeToFit];
  734. [demoView addSubview:lineLabel];
  735. demoView.frame = CGRectMake(0, 0, 290, lineLabel.frame.origin.y+lineLabel.frame.size.height+25);
  736. return demoView;
  737. }
  738. -(bool) verifyData
  739. {
  740. if(NO_SAVE_VERIFY)
  741. return true;
  742. // return true;
  743. bool ret=true;
  744. int more=0;
  745. NSMutableArray* fields=[[NSMutableArray alloc] init];
  746. for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
  747. {
  748. NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
  749. for(int j=0;j<[page[@"count"] intValue];j++)
  750. {
  751. NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
  752. NSString* type = control[@"type"];
  753. NSString* name = control[@"aname"];
  754. bool required = [control[@"required"] boolValue];
  755. if(required==false)
  756. continue;
  757. if([type isEqualToString:@"Check"])
  758. {
  759. NSArray* arr = control[@"value"];
  760. if(arr.count==0)
  761. {
  762. ret=false;
  763. NSString* msg=[NSString stringWithFormat:@"%u. Page %d: %@",fields.count+1,i+1,name];
  764. if(fields.count<15)
  765. [fields addObject:msg];
  766. else
  767. more++;
  768. }
  769. }
  770. else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
  771. {
  772. continue;
  773. }
  774. else
  775. {
  776. NSString* str = control[@"value"];
  777. if(str.length==0)
  778. {
  779. ret=false;
  780. NSString* msg=[NSString stringWithFormat:@"%lu. Page %d: %@",fields.count+1,i+1,name];
  781. if(fields.count<15)
  782. [fields addObject:msg];
  783. else
  784. more++;
  785. }
  786. }
  787. }
  788. }
  789. if(ret==false)
  790. {
  791. if(more>0)
  792. {
  793. NSString* msg=[NSString stringWithFormat:@"And %d more missing fields.",more];
  794. [fields addObject:@"......"];
  795. [fields addObject:msg];
  796. }
  797. NSString* missfields=[fields componentsJoinedByString:@"\n"];
  798. NSString* msg = [NSString stringWithFormat:@"%@",missfields];
  799. CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
  800. // Add some custom content to the alert view
  801. [alertView setContainerView:[self createDemoView:msg]];
  802. // Modify the parameters
  803. [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"OK", nil]];
  804. //[alertView setDelegate:self];
  805. // You may use a Block, rather than a delegate.
  806. [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
  807. // DebugLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, (int)[alertView tag]);
  808. [alertView close];
  809. }];
  810. // [alertView setUseMotionEffects:true];
  811. // And launch the dialog
  812. [alertView sizeToFit];
  813. [alertView show];
  814. }
  815. return ret;
  816. }
  817. //#pragma mark - Page View Controller Data Source
  818. - (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed
  819. {
  820. // self.title = [NSString stringWithFormat:@"%@ [%ld/%ld]", self.docment_id,((PageViewController*)self.pageViewController.viewControllers[0]).pageIndex+1, self.total_page ];
  821. }
  822. - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
  823. {
  824. NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
  825. if ((index == 0 ) || (index == NSNotFound)){
  826. return nil;
  827. }
  828. // self.current_page= index;
  829. index--;
  830. return [self viewControllerAtIndex:index];
  831. }
  832. - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
  833. {
  834. NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
  835. if (index == NSNotFound)
  836. {
  837. return nil;
  838. }
  839. // self.current_page= index;
  840. index++;
  841. if (index == self.total_page){
  842. return nil;
  843. }
  844. return [self viewControllerAtIndex:index];
  845. }
  846. #pragma mark - UIPageViewController delegate methods
  847. - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
  848. if (true||UIInterfaceOrientationIsPortrait(orientation) || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)) {
  849. // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
  850. UIViewController *currentViewController = self.pageViewController.viewControllers[0];
  851. NSArray *viewControllers = @[currentViewController];
  852. [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
  853. self.pageViewController.doubleSided = NO;
  854. return UIPageViewControllerSpineLocationMin;
  855. }
  856. // // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
  857. // PageViewController *currentViewController = self.pageViewController.viewControllers[0];
  858. // NSArray *viewControllers = nil;
  859. //
  860. // NSUInteger indexOfCurrentViewController = [self indexOfViewController:currentViewController];
  861. // if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) {
  862. // UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
  863. // viewControllers = @[currentViewController, nextViewController];
  864. // } else {
  865. // UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
  866. // viewControllers = @[previousViewController, currentViewController];
  867. // }
  868. // [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
  869. //
  870. //
  871. // return UIPageViewControllerSpineLocationMid;
  872. }
  873. @end