DocumentPageViewController.m 51 KB

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