DocumentPageViewController.m 44 KB

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