DetailPageViewController.m 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052
  1. //
  2. // DetailPageViewController.m
  3. // Apex Mobile
  4. //
  5. // Created by Ray on 14-3-8.
  6. // Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "DetailPageViewController.h"
  9. #import "AMShipMap.h"
  10. #define DEF_CELL_HEIGHT 44
  11. #define DEF_TABLE_HEIGHT 44
  12. #define LINE_WIDTH 0
  13. #define CELL_MARGIN 15
  14. #define LABEL_MARGIN 0
  15. #define NEW_MAPCELL_MARGIN 8
  16. #import "TabBarController.h"
  17. #import "DetailCellTracking.h"
  18. #import <QuickLook/QuickLook.h>
  19. #import "DetailCellKVNew.h"
  20. #import "MyQLPreviewController.h"
  21. #import "LPShareActivity.h"
  22. #import "AMCommEditCell.h"
  23. #import "AMCommHeadCell.h"
  24. #import "AMCommContentCell.h"
  25. #import <Contacts/Contacts.h>
  26. #import <ContactsUI/ContactsUI.h>
  27. #define COMM_ID_HEAD @"COMM_ID_HEAD"
  28. #define COMM_ID_CONTENT @"COMM_ID_CONTENT"
  29. #define COMM_ID_EDIT @"COMM_ID_EDIT"
  30. @interface DetailHUD : UIView
  31. @property (nonatomic,strong) UILabel *msgLb;
  32. @end
  33. @implementation DetailHUD
  34. + (void)show:(NSString *)msg inView:(UIView *)view {
  35. if (!msg) {
  36. return;
  37. }
  38. DetailHUD *hud = [[DetailHUD alloc] initWithFrame:CGRectZero];
  39. hud.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.9];
  40. hud.msgLb.text = msg;
  41. [hud layoutSize];
  42. for (UIView *sub in view.subviews) {
  43. if ([sub isKindOfClass:self]) {
  44. sub.hidden = YES;
  45. }
  46. }
  47. [view addSubview:hud];
  48. [hud performSelector:@selector(hide) withObject:nil afterDelay:3.0f];
  49. }
  50. - (UILabel *)msgLb {
  51. if (!_msgLb) {
  52. _msgLb = [[UILabel alloc] initWithFrame:CGRectZero];
  53. _msgLb.textColor = [UIColor whiteColor];
  54. _msgLb.font = [UIFont systemFontOfSize:14.0f];
  55. [self addSubview:_msgLb];
  56. }
  57. return _msgLb;
  58. }
  59. - (void)layoutSize {
  60. [self.msgLb sizeToFit];
  61. CGSize size = self.msgLb.bounds.size;
  62. CGFloat height = size.height + 20;
  63. CGFloat width = size.width + 20;
  64. if (height < 30) {
  65. height = 30;
  66. }
  67. if (width < 30) {
  68. width = 30;
  69. }
  70. self.msgLb.center = CGPointMake(width * 0.5, height * 0.5);
  71. self.bounds = CGRectMake(0, 0, width, height);
  72. self.layer.cornerRadius = 5.0f;
  73. self.layer.masksToBounds = YES;
  74. }
  75. - (void)willMoveToSuperview:(UIView *)newSuperview {
  76. [super willMoveToSuperview:newSuperview];
  77. if (newSuperview) {
  78. self.center = CGPointMake(newSuperview.bounds.size.width * 0.5, newSuperview.bounds.size.height * 0.5);
  79. }
  80. }
  81. - (void)layoutSubviews {
  82. [super layoutSubviews];
  83. if (self.superview) {
  84. self.center = CGPointMake(self.superview.bounds.size.width * 0.5, self.superview.bounds.size.height * 0.5);
  85. }
  86. }
  87. - (void)hide {
  88. [self removeFromSuperview];
  89. }
  90. @end
  91. @interface DetailPageViewController () <QLPreviewControllerDataSource,QLPreviewControllerDelegate,DetailKVCellTapDelegate,AMCommHeadCellDelegate,AMCommContentCellDelegate,AMCommEditCellDelegate,CNContactPickerDelegate,AMShipMapDelegate>
  92. @property (nonatomic,strong) MyQLPreviewController *quickLook;
  93. @property (nonatomic,copy) NSString *documentPath;
  94. @property (nonatomic,copy) NSString *email;
  95. @property (nonatomic,copy) NSString *email_subject;
  96. @property (nonatomic,copy) NSString *email_content;
  97. @property (nonatomic,strong) IBOutlet AMShipMap *shipMap;
  98. @property (nonatomic,weak) UITableViewCell *editingCell;
  99. @property (nonatomic,strong) NSIndexPath *editingIndexPath;
  100. @property (nonatomic,strong) NSIndexPath *contactSelectIndexPath;
  101. @property (nonatomic,weak) UITapGestureRecognizer *tap;
  102. @property (nonatomic,assign) BOOL showKeyboard;
  103. @property (nonatomic,strong) NSIndexPath *containerSelectedIndexPath;
  104. @end
  105. @implementation DetailPageViewController
  106. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  107. {
  108. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  109. if (self) {
  110. // Custom initialization
  111. }
  112. return self;
  113. }
  114. -(void)changeCell
  115. {
  116. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  117. reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
  118. [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
  119. DebugLog(@"refresh!!!!!!!!");
  120. }
  121. -(void)ReloadData
  122. {
  123. // Count ++ ;
  124. // [mytabelview reloadData];
  125. [self loadpage];
  126. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  127. [reF endRefreshing];
  128. }
  129. - (void)viewDidLoad
  130. {
  131. [super viewDidLoad];
  132. // self.webviewoprationQueue = [[NSOperationQueue alloc] init];
  133. // self.webviewoprationQueue.maxConcurrentOperationCount = 1;
  134. UIRefreshControl *ref = [[UIRefreshControl alloc]init];
  135. ref.tag = 200 ;
  136. ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"drag to refresh"];
  137. ref.tintColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
  138. // ref.hidden = true;
  139. [ref addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged];
  140. [self.table addSubview:ref];
  141. if(self.tabBarController.tabBar.hidden==true)
  142. {
  143. CGRect frame = self.table.frame;
  144. frame.size.height +=40;
  145. self.table.frame=frame;
  146. }
  147. // self.view.backgroundColor= [UIColor whiteColor];
  148. [self loadpage];
  149. // Do any additional setup after loading the view.
  150. UIBarButtonItem *previewMenuBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(quickLookMenuClick:)];
  151. self.quickLook.navigationItem.rightBarButtonItem = previewMenuBtn;
  152. [self configureMap];
  153. [self configureTableView];
  154. }
  155. - (void)viewWillAppear:(BOOL)animated {
  156. [super viewWillAppear:animated];
  157. NSString *action_type = [self.params objectForKey:@"action_type"];
  158. if ([action_type isEqualToString:@"Detail"]) { // 避免Tap与Tacking中Cell点击冲突
  159. [self startListenKeyboard];
  160. }
  161. if (self.shipMap) {
  162. [self.shipMap shipMapWillAppear];
  163. }
  164. }
  165. - (void)viewWillDisappear:(BOOL)animated {
  166. [super viewWillDisappear:animated];
  167. [self stopListenKeyboard];
  168. if (self.shipMap) {
  169. [self.shipMap shipMapWillDisappear];
  170. }
  171. }
  172. - (void)configureTableView {
  173. [self.table registerNib:[UINib nibWithNibName:@"AMCommHeadCell" bundle:nil] forCellReuseIdentifier:COMM_ID_HEAD];
  174. [self.table registerNib:[UINib nibWithNibName:@"AMCommContentCell" bundle:nil] forCellReuseIdentifier:COMM_ID_CONTENT];
  175. [self.table registerNib:[UINib nibWithNibName:@"AMCommEditCell" bundle:nil] forCellReuseIdentifier:COMM_ID_EDIT];
  176. }
  177. - (void)configureMap {
  178. if (!self.showMap) {
  179. NSArray *constraints = [[self.view constraints] mutableCopy];
  180. // 删除Table与Map相关约束
  181. for (NSLayoutConstraint *constaint in constraints) {
  182. if ([constaint.identifier isEqualToString:@"top_constraint"]) {
  183. [self.view removeConstraint:constaint];
  184. } else if ([constaint.identifier isEqualToString:@"ratio_constraint"]) {
  185. [self.view removeConstraint:constaint];
  186. }
  187. }
  188. // 移除地图
  189. [self.shipMap removeFromSuperview];
  190. self.shipMap = nil;
  191. // 设置新约束
  192. NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.table
  193. attribute:NSLayoutAttributeTop
  194. relatedBy:NSLayoutRelationEqual
  195. toItem:self.topLayoutGuide
  196. attribute:NSLayoutAttributeBottom
  197. multiplier:1.0
  198. constant:0];
  199. [self.view addConstraint:top];
  200. [self.view layoutIfNeeded];
  201. } else {
  202. self.shipMap.showCurrent = YES;
  203. self.shipMap.showPoe = YES;
  204. self.shipMap.showPol = YES;
  205. self.shipMap.showPod = YES;
  206. self.shipMap.showPor = YES;
  207. self.shipMap.showOrigin = YES;
  208. self.shipMap.showDestination = YES;
  209. self.shipMap.delegate = self;
  210. }
  211. }
  212. - (void)saveDocumentClick:(id)sender {
  213. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  214. NSString *path = [paths objectAtIndex:0];
  215. NSString *filePath = [path stringByAppendingPathComponent:[self.documentPath lastPathComponent]];
  216. NSError *err;
  217. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  218. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  219. }
  220. [[NSFileManager defaultManager] moveItemAtPath:self.documentPath toPath:filePath error:&err];
  221. UIAlertController *alertVC;
  222. UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  223. }];
  224. if (err) {
  225. alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"save document failed:\n%@",err.localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
  226. } else {
  227. alertVC = [UIAlertController alertControllerWithTitle:nil message:@"Document Saved" preferredStyle:UIAlertControllerStyleAlert];
  228. }
  229. [alertVC addAction:action];
  230. [self presentViewController:alertVC animated:YES completion:nil];
  231. }
  232. - (void)didReceiveMemoryWarning
  233. {
  234. [super didReceiveMemoryWarning];
  235. // Dispose of any resources that can be recreated.
  236. }
  237. -(void) loadpage
  238. {
  239. // [self.params setValue:[NSString stringWithFormat:@"%d",self.offset] forKey:@"offset"];
  240. // self.prepageButton.enabled=false;
  241. // self.nextpageButton.enabled=false;
  242. self.mum.center = self.view.center;
  243. __weak typeof(self) weakSelf = self;
  244. NSTimeInterval animationDuration = 0.30f;
  245. [UIView beginAnimations:@"ResizeView" context:nil];
  246. [UIView setAnimationDuration:animationDuration];
  247. self.mum.hidden = false;
  248. self.table.hidden = true;
  249. [UIView commitAnimations];
  250. if (self.showMap) {
  251. [self.params setObject:@(YES) forKey:@"request_location"];
  252. }
  253. if ([[self.params objectForKey:@"action_type"] isEqualToString:@"Detail"]) {
  254. [self.params setObject:@(YES) forKey:@"request_communication"];
  255. }
  256. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  257. self.content=[RANetwork get_detailcontent:self.params];
  258. // PageData* pageData=nil;
  259. // if(self.recordCount==-1)
  260. // self.recordCount=[RANetwork get_recordcount: self.params ];
  261. // if(self.recordCount>0)
  262. // {
  263. // self.pageData=[RANetwork get_pagedata:self.params];
  264. // // self.pageData=[RANetwork]
  265. // }
  266. //
  267. dispatch_async(dispatch_get_main_queue(), ^{
  268. NSTimeInterval animationDuration = 0.30f;
  269. [UIView beginAnimations:@"ResizeView" context:nil];
  270. [UIView setAnimationDuration:animationDuration];
  271. self.mum.hidden = true;
  272. if(self.content.result_code!=RESULT_TRUE)
  273. {
  274. self.table.hidden =false;
  275. [self.table reloadData];
  276. }
  277. else
  278. if([self.content get_segmentcount]==0)
  279. {
  280. self.table.hidden =true;
  281. self.norecordLabel.hidden=false;
  282. if(self.tabBarController.childViewControllers.count==1)
  283. {
  284. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle: @"Warning"
  285. message: @"No Search Result."
  286. preferredStyle: UIAlertControllerStyleAlert];
  287. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Back" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  288. [weakSelf.navigationController popViewControllerAnimated:false];
  289. }];
  290. [alertVC addAction:action];
  291. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  292. }
  293. }
  294. else
  295. {
  296. self.table.hidden =false;
  297. [self.table reloadData];
  298. self.email = [self.content.originContent objectForKey:@"email"];
  299. self.email_subject = [self.content.originContent objectForKey:@"email_subject"];
  300. self.email_content = [self.content.originContent objectForKey:@"email_content"];
  301. }
  302. [UIView commitAnimations];
  303. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  304. bool autologin =[defaults boolForKey:@"autologin"];
  305. if(!autologin)
  306. {
  307. TabBarController * viewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginTabBar"];
  308. [self presentViewController:viewController animated:YES completion:^{
  309. }];
  310. }
  311. // 设置默认选中第一个Container
  312. for (NSInteger i = 0; i < self.content.segments.count; i++) {
  313. NSMutableDictionary* segment = [self.content.segments[i] mutableCopy];
  314. NSString* type =[segment valueForKey:@"_type"];
  315. if([type isEqualToString:@"tracking"]) {
  316. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:i];
  317. [self.table selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  318. [self tableView:self.table didSelectRowAtIndexPath:indexPath];
  319. break;
  320. }
  321. }
  322. // [self.table setNeedsDisplay];
  323. // if(self.recordCount<2000)
  324. // self.countView.title = [NSString stringWithFormat:@"%d records",self.recordCount];
  325. // else
  326. // self.countView.title = @"2000+ records";
  327. //
  328. // if(self.offset<self.pageData.get_count)
  329. // self.prepageButton.enabled=false;
  330. // else
  331. // self.prepageButton.enabled=true;
  332. // if(self.offset+self.pageData.get_count>=self.recordCount)
  333. // self.nextpageButton.enabled=false;
  334. // else
  335. // self.nextpageButton.enabled=true;
  336. // [self.grid initgrid :self.pageData];
  337. });
  338. });
  339. }
  340. //- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
  341. //{
  342. //// [self.table beginUpdates];
  343. // [self.table reloadData];
  344. //// [self.table endUpdates];
  345. //
  346. //}
  347. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  348. __weak typeof(self) weakSelf = self;
  349. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
  350. // 动画前
  351. } completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
  352. // 动画后
  353. [weakSelf.table reloadData];
  354. }];
  355. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  356. }
  357. //// 是否支持屏幕旋转
  358. //- (BOOL)shouldAutorotate {
  359. //
  360. //
  361. // return YES;
  362. //}
  363. //// 支持的旋转方向
  364. //- (NSUInteger)supportedInterfaceOrientations {
  365. // return UIInterfaceOrientationLandscapeRight;//UIInterfaceOrientationMaskAllButUpsideDown;
  366. //}
  367. //// 一开始的屏幕旋转方向
  368. //- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
  369. // return UIInterfaceOrientationLandscapeRight;
  370. //}
  371. - (void)showDocument:(NSString *)url {
  372. __weak typeof(self) weakSelf = self;
  373. // show alert
  374. UIAlertController *alertController = [UIAlertController alertControllerWithTitle: nil
  375. message: @"loading..."
  376. preferredStyle: UIAlertControllerStyleAlert];
  377. UIViewController *customVC = [[UIViewController alloc] init];
  378. UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  379. spinner.color = [UIColor darkGrayColor];
  380. [spinner startAnimating];
  381. [customVC.view addSubview:spinner];
  382. [customVC.view addConstraint:[NSLayoutConstraint
  383. constraintWithItem: spinner
  384. attribute:NSLayoutAttributeCenterX
  385. relatedBy:NSLayoutRelationEqual
  386. toItem:customVC.view
  387. attribute:NSLayoutAttributeCenterX
  388. multiplier:1.0f
  389. constant:0.0f]];
  390. [customVC.view addConstraint:[NSLayoutConstraint
  391. constraintWithItem: spinner
  392. attribute:NSLayoutAttributeCenterY
  393. relatedBy:NSLayoutRelationEqual
  394. toItem:customVC.view
  395. attribute:NSLayoutAttributeCenterY
  396. multiplier:1.0f
  397. constant:0.0f]];
  398. [alertController setValue:customVC forKey:@"contentViewController"];
  399. [self presentViewController: alertController animated: YES completion: nil];
  400. // download
  401. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  402. // NSArray *paths = NSSearchPathForDirectoriesInDomains(nstem, NSUserDomainMask, YES);
  403. // NSString *documents = [paths objectAtIndex:0];
  404. // NSString *cacheDir = [documents stringByAppendingPathComponent:[module_name stringByAppendingString:@"_download"]];
  405. NSString *cacheDir = NSTemporaryDirectory();
  406. if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDir]) {
  407. [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:nil];
  408. }
  409. // NSString *path = [cacheDir stringByAppendingPathComponent:[NSUUID UUID].UUIDString];
  410. [RANetwork download_file:nil url:url toCachePath:cacheDir progressHandler:^(NSURLSessionTask *task, double progress) {
  411. DebugLog(@"download progress %f",progress);
  412. } completionHandler:^(NSMutableDictionary *result) {
  413. dispatch_async(dispatch_get_main_queue(), ^{
  414. weakSelf.documentPath = nil;
  415. [alertController dismissViewControllerAnimated:YES completion:^{
  416. if ([[result objectForKey:@"result"] intValue] == RESULT_TRUE) {
  417. NSString *cachePath = [result objectForKey:@"path"];
  418. weakSelf.documentPath = cachePath;
  419. if (cachePath) { // push 必须在completion中
  420. [weakSelf.navigationController pushViewController:weakSelf.quickLook animated:YES];
  421. }
  422. } else {
  423. NSString *msg = [result objectForKey:@"msg"];
  424. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle: @"Warning"
  425. message: msg
  426. preferredStyle: UIAlertControllerStyleAlert];
  427. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  428. }];
  429. [alertVC addAction:action];
  430. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  431. }
  432. }];
  433. });
  434. DebugLog(@"download result %@",result);
  435. }];
  436. });
  437. }
  438. #pragma mark - WKNavigationDelegate
  439. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
  440. {
  441. NSLog(@"webview didFinishNavigation");
  442. UITableViewCell *cell = (UITableViewCell *)[[webView superview] superview];
  443. NSIndexPath *indexPath = [self.table indexPathForCell:cell];
  444. if(indexPath==nil)
  445. {//for ios7
  446. cell = (UITableViewCell *) webView.superview.superview.superview;
  447. indexPath = [self.table indexPathForCell:cell];
  448. }
  449. float height= [[self.content.webviewHeight valueForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.section]] floatValue];
  450. if(height>0)
  451. return;
  452. [webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable fitHeight,NSError * _Nullable error) {
  453. CGRect frame = webView.frame;
  454. frame.size.height = [fitHeight floatValue];
  455. //webView.frame = frame;
  456. [self.content.webviewHeight setObject:[NSString stringWithFormat:@"%f",frame.size.height/*webView.scrollView.contentSize.height*/] forKey:[NSString stringWithFormat:@"%ld",(long)indexPath.section]];
  457. DebugLog(@"webViewDidFinishLoad ^^^^^^^^^^^^^^^^^reloadRowsAtIndexPaths");
  458. if (![[self.table indexPathsForVisibleRows] containsObject:indexPath])
  459. {
  460. //cell 已无法显示。
  461. return;
  462. }
  463. dispatch_async(dispatch_get_main_queue(), ^{
  464. NSLog(@"reload tableview!!! %f",frame.size.height);
  465. // UI更新代码
  466. // [self.table reloadData];
  467. // [self.detailTable reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
  468. [self.table reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
  469. //[self.editorTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  470. });
  471. }];
  472. }
  473. //禁止链接跳转
  474. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  475. NSLog(@"%s",__func__);
  476. NSLog(@"navigationAction = %@, \r!!!!!!!!!!!!!!!!!!!!!!\n request = %@",navigationAction,navigationAction.request.URL);
  477. if(navigationAction.navigationType != WKNavigationTypeLinkActivated)
  478. return decisionHandler(WKNavigationActionPolicyAllow);
  479. // NSString *currentURL =[webView.request.URL lastPathComponent];// [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
  480. NSString* str = navigationAction.request.URL.absoluteString;
  481. if([str isEqualToString:@"about:blank"])
  482. return decisionHandler(WKNavigationActionPolicyAllow);;
  483. [self showDocument:navigationAction.request.URL.absoluteString];
  484. return decisionHandler(WKNavigationActionPolicyCancel);;
  485. }
  486. #pragma mark - Section Switch
  487. - (void)sectionSwitchClick:(UIButton *)sender {
  488. NSInteger section = sender.tag - 1020;
  489. NSMutableArray *segments = [self.content.segments mutableCopy];
  490. NSMutableDictionary* segment = [self.content.segments[section] mutableCopy];
  491. NSString* type =[segment valueForKey:@"_type"];
  492. if([type isEqualToString:@"tracking"])
  493. {
  494. BOOL close = [[segment objectForKey:@"close"] boolValue];
  495. if (!close) {
  496. close = YES;
  497. } else {
  498. close = NO;
  499. }
  500. [segment setValue:@(close) forKey:@"close"];
  501. segments[section] = segment;
  502. self.content.segments = segments;
  503. // [self.table reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
  504. [self.table reloadData];
  505. }
  506. }
  507. - (void)copyTap:(UITapGestureRecognizer *)tap {
  508. UILabel *lb = (UILabel *)tap.view;
  509. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  510. pasteboard.string = lb.text;
  511. [DetailHUD show:[NSString stringWithFormat:@"%@ Copied",lb.text] inView:self.view];
  512. }
  513. #pragma mark - Table view data source
  514. //
  515. //- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
  516. //{
  517. // return 40;
  518. //}
  519. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
  520. {
  521. DebugLog(@"heightForRowAtIndexPath");
  522. // float height = [self.content itemHeightAtIndexPath:indexPath];
  523. NSString* type = [self.content get_segmenttype:indexPath.section];
  524. if([type isEqualToString:@"table"])
  525. {
  526. // [self.content.webviewHeight setObject:[NSString stringWithFormat:@"%f",webView.frame.size.height] forKey:[NSString stringWithFormat:@"%d",webView.tag]];
  527. float height= [[self.content.webviewHeight valueForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.section]] floatValue];
  528. if(height==0)
  529. height=DEF_TABLE_HEIGHT;
  530. // DebugLog(@"heightForRowAtIndexPath...............webview,hight = %f section=%ld",height,indexPath.section);
  531. //wait(1000);
  532. return height;
  533. }
  534. else if([type isEqualToString:@"tracking"])
  535. {
  536. return 64;
  537. }
  538. else if([type isEqualToString:@"mapping"])
  539. {
  540. // NSString *CellIdentifier = @"detail_item_kvnew";
  541. // DetailCellKVNew *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  542. NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  543. NSString* key =[item allKeys][0];
  544. // [cell.keyLabel sizeToFit];
  545. NSString* val=[item valueForKey:key];
  546. if([val isEqual:[NSNull null]])
  547. val=@"";
  548. // cell.keyLabel.text = key;
  549. // cell.valLabel.htmlText = val;
  550. // UILabel* l = [UILabel new];
  551. // l.text =@"Place_Of_Receipt";
  552. // CGSize size= [l sizeThatFits:CGSizeMake(116,MAXFLOAT)];
  553. float width = tableView.frame.size.width;
  554. // width-=CELL_MARGIN*2;
  555. CGSize constraintkey = CGSizeMake(width*0.4-2*NEW_MAPCELL_MARGIN, MAXFLOAT);//key label width is 40% cell width;
  556. CGSize constraintval = CGSizeMake(width*0.6-2*NEW_MAPCELL_MARGIN, MAXFLOAT);//val label width is 60% cell width;
  557. /*
  558. NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default
  559. NSLineBreakByCharWrapping, // Wrap at character boundaries
  560. NSLineBreakByClipping, // Simply clip
  561. NSLineBreakByTruncatingHead, // Truncate at head of line: "...wxyz"
  562. NSLineBreakByTruncatingTail,
  563. */
  564. UIFont * F1=[UIFont systemFontOfSize:13];
  565. UIFont * F2=[UIFont fontWithName:@".SFUIText-Bold" size:13];//[UIFont boldSystemFontOfSize:13];
  566. // [UILabel setFont:];
  567. MDHTMLLabel* keylabel = [MDHTMLLabel new];
  568. keylabel.font = F2;
  569. keylabel.numberOfLines = 0;
  570. keylabel.lineBreakMode = NSLineBreakByTruncatingTail;
  571. keylabel.frame = CGRectMake(0, 0, constraintkey.width, constraintkey.height);
  572. keylabel.text=key;
  573. CGSize calkeysize= [keylabel sizeThatFits:constraintkey];
  574. if([key isEqualToString:@"Place_Of_Delivery"])
  575. {
  576. // int abc=0;
  577. }
  578. // [keylabel sizeToFit];
  579. // CGRect r = keylabel.frame;
  580. MDHTMLLabel* vallabel = [MDHTMLLabel new];
  581. vallabel.font = F1;
  582. vallabel.numberOfLines = 0;
  583. vallabel.lineBreakMode = NSLineBreakByWordWrapping;
  584. vallabel.htmlText=val;
  585. vallabel.frame = CGRectMake(0, 0, constraintval.width, constraintval.height);
  586. CGSize calvalsize= [vallabel sizeThatFits:constraintval];
  587. float height = MAX(calkeysize.height,calvalsize.height)+NEW_MAPCELL_MARGIN*2;
  588. height = MAX(height+LINE_WIDTH, DEF_CELL_HEIGHT);
  589. return height;
  590. //
  591. // NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  592. // NSString* key =[item allKeys][0];
  593. // // [cell.keyLabel sizeToFit];
  594. // NSString* val=[item valueForKey:key];
  595. // if([val isEqual:[NSNull null]])
  596. // val=@"";
  597. // if(val==nil)
  598. // val=@"";
  599. // if([val isEqualToString:@"null"])
  600. // val=@"";
  601. //
  602. //
  603. //
  604. // CGRect frame;
  605. // frame.size = constraintval;
  606. // frame.origin.x=0;
  607. // frame.origin.y=0;
  608. // RTLabel* rtlabel = [[RTLabel alloc] initWithFrame:frame];
  609. // [rtlabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
  610. // // rtlabel.lineSpacing = 20.0;
  611. // [rtlabel setText: val];
  612. // CGSize sizeval=rtlabel.optimumSize;
  613. //
  614. //
  615. // CGSize sizekey = [key sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  616. // // CGSize sizeval = [val sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintval lineBreakMode:NSLineBreakByWordWrapping];
  617. // float height = MAX(sizekey.height,sizeval.height);
  618. // height = MAX(height+LINE_WIDTH, DEF_CELL_HEIGHT);
  619. //
  620. // /*
  621. // NSString *text = [items objectAtIndex:[indexPath row]];
  622. //
  623. // CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
  624. //
  625. // CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
  626. //
  627. // CGFloat height = MAX(size.height, 44.0f);
  628. //
  629. // return height + (CELL_CONTENT_MARGIN * 2);
  630. // */
  631. // // NSString *CellIdentifier = @"detail_item_kv";
  632. // // DetailCellKV *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  633. // // NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  634. // // cell.keyLabel.text=[item allKeys][0];
  635. // // [cell.keyLabel sizeToFit];
  636. // // cell.valLabel.text= [item valueForKey:cell.keyLabel.text];
  637. // // [cell.valLabel sizeToFit];
  638. // //
  639. // // return MAX(cell.keyLabel.frame.size.height,cell.valLabel.frame.size.height);
  640. // return height;
  641. }
  642. else if ([type isEqualToString:@"communication"]) {
  643. NSInteger rowCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
  644. if (indexPath.row == 0) {
  645. return 118.0f;
  646. } else if (indexPath.row == rowCount - 1) {
  647. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  648. NSString *edit_content = [segment objectForKey:@"edit_content"];
  649. CGFloat h = 40.0f; // 输入框高度,最小40
  650. if (edit_content && edit_content.length > 0) {
  651. AMCommEditCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"AMCommEditCell" owner:nil options:nil] objectAtIndex:0];
  652. h = [cell heightForContent:edit_content withTableWidth:CGRectGetWidth(tableView.bounds)];
  653. if (h < 40.0f) {
  654. h = 40.0f;
  655. } else if (h > 100.0f) { // 输入框高度,最大100
  656. h = 100.0f;
  657. }
  658. } else {
  659. h = 40.0f;
  660. }
  661. return 50.0f + h;
  662. } else {
  663. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  664. NSString *itemKey = [NSString stringWithFormat:@"item%ld",indexPath.row - 1];
  665. NSDictionary *item = [[segment objectForKey:itemKey] mutableCopy];
  666. CGFloat height = [[item objectForKey:@"content_height"] floatValue];
  667. if (height <= 0) {
  668. NSString *content = [item objectForKey:@"msg"];
  669. if (content && content.length > 0) {
  670. NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f]};
  671. CGSize resSize = [content boundingRectWithSize:CGSizeMake(CGRectGetWidth(tableView.bounds) - 11, MAXFLOAT)
  672. options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
  673. attributes:attribute
  674. context:nil].size;
  675. height = resSize.height;
  676. } else {
  677. height = 0;
  678. }
  679. [item setValue:@(height) forKey:@"content_height"];
  680. [segment setObject:item forKey:itemKey];
  681. NSMutableArray *arr = [self.content.segments mutableCopy];
  682. [arr replaceObjectAtIndex:indexPath.section withObject:segment];
  683. self.content.segments = arr;
  684. }
  685. return 71.5 + height;
  686. }
  687. }
  688. else
  689. {
  690. DebugLog(@"cellForRowAtIndexPath =====> list");
  691. float width = tableView.frame.size.width;
  692. width-=CELL_MARGIN*2;
  693. CGSize constraintval = CGSizeMake(width, 20000.0f);//val label width is 60% cell width;
  694. NSDictionary* item = self.content.segments[indexPath.section];
  695. NSString* text=[item valueForKey:[NSString stringWithFormat:@"line%ld",(long)indexPath.row]];
  696. if([text isEqual:[NSNull null]])
  697. text=@"";
  698. if(text==nil)
  699. text=@"";
  700. if([text isEqualToString:@"null"])
  701. text=@"";
  702. // CGRect frame;
  703. // frame.size = constraintval;
  704. // frame.origin.x=0;
  705. // frame.origin.y=0;
  706. // CGSize sizeText = [text sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:constraintval lineBreakMode:NSLineBreakByWordWrapping];
  707. // CGSize sizeval = [val sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintval lineBreakMode:NSLineBreakByWordWrapping];
  708. CGSize sizeText = [text boundingRectWithSize:constraintval options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:13.0]} context:nil].size;
  709. float height = sizeText.height;
  710. height = MAX(height+LINE_WIDTH, DEF_CELL_HEIGHT);
  711. return height;
  712. }
  713. // return height;
  714. }
  715. //- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  716. //{
  717. // UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
  718. // myView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
  719. // UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)];
  720. // titleLabel.textColor=[UIColor whiteColor];
  721. // titleLabel.backgroundColor = [UIColor clearColor];
  722. // titleLabel.text =[self.content get_segmentname:section];
  723. // [titleLabel sizeToFit];
  724. // [myView addSubview:titleLabel];
  725. //
  726. // return myView;
  727. //}
  728. //- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
  729. //{
  730. // UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
  731. // myView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
  732. //// UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)];
  733. //// titleLabel.textColor=[UIColor whiteColor];
  734. //// titleLabel.backgroundColor = [UIColor grayColor];
  735. //// titleLabel.text =[self.content get_segmentname:section];
  736. //// [titleLabel sizeToFit];
  737. //// [myView addSubview:titleLabel];
  738. //
  739. // return myView;
  740. //}
  741. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  742. {
  743. DebugLog(@"numberOfSectionsInTableView=%ld",[self.content get_segmentcount]);
  744. return [self.content get_segmentcount];
  745. }
  746. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  747. {
  748. DebugLog(@"numberOfRowsInSection=%d",[self.content get_itemcount:section]);
  749. NSMutableDictionary* segment = [self.content.segments[section] mutableCopy];
  750. NSString* type =[segment valueForKey:@"_type"];
  751. if ([type isEqualToString:@"communication"]) {
  752. return [self.content get_itemcount:section] + 2;
  753. } else {
  754. return [self.content get_itemcount:section];
  755. }
  756. }
  757. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  758. DebugLog(@"titleForHeaderInSection=%@",[self.content get_segmentname:section]);
  759. return [self.content get_segmentname:section];
  760. }
  761. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  762. NSMutableDictionary* segment = [self.content.segments[section] mutableCopy];
  763. NSString* type =[segment valueForKey:@"_type"];
  764. CGFloat w = tableView.frame.size.width;
  765. UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, 30)];
  766. UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, w - 100, 30)];
  767. titleLb.font = [UIFont systemFontOfSize:15.0f];
  768. titleLb.textColor = APGRAYCOLOR;
  769. titleLb.text = [self tableView:tableView titleForHeaderInSection:section];
  770. [header addSubview:titleLb];
  771. if([type isEqualToString:@"tracking"])
  772. {
  773. BOOL close = [[segment objectForKey:@"close"] boolValue];
  774. NSString *title = @"Show";
  775. if (!close) {
  776. title = @"Hide";
  777. } else {
  778. title = @"Show";
  779. }
  780. UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  781. btn.frame = CGRectMake(w - 70, 0, 60, 30);
  782. btn.tag = 1020 + section;
  783. [btn setTitle:title forState:UIControlStateNormal];
  784. [btn setTitleColor:APGRAYCOLOR forState:UIControlStateNormal];
  785. [btn addTarget:self action:@selector(sectionSwitchClick:) forControlEvents:UIControlEventTouchUpInside];
  786. [header addSubview:btn];
  787. // Tap Copy
  788. UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(copyTap:)];
  789. tapGesture.numberOfTapsRequired = 2;
  790. [titleLb addGestureRecognizer:tapGesture];
  791. titleLb.userInteractionEnabled = YES;
  792. }
  793. return header;
  794. }
  795. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  796. {
  797. return 30;
  798. }
  799. - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
  800. {
  801. return 0.0001;
  802. }
  803. //- (UIImage *) imageWithTintColor:(UIImage*)source Color:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode {
  804. // //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
  805. // UIGraphicsBeginImageContextWithOptions(source.size, NO, 0.0f); [tintColor setFill];
  806. // CGRect bounds = CGRectMake(0, 0, source.size.width, source.size.height); UIRectFill(bounds);
  807. // //Draw the tinted image in context
  808. // [source drawInRect:bounds blendMode:blendMode alpha:1.0f];
  809. // if (blendMode != kCGBlendModeDestinationIn)
  810. // {
  811. // [source drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
  812. // }
  813. // UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
  814. // UIGraphicsEndImageContext();
  815. // return tintedImage;
  816. //}
  817. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  818. {
  819. // NSString *CellIdentifier = @"testcell";
  820. // return [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  821. NSString* type = [self.content get_segmenttype:indexPath.section];
  822. if([type isEqualToString:@"table"])
  823. {
  824. DebugLog(@"cellForRowAtIndexPath =====> table");
  825. static NSString *CellIdentifier = @"detail_item_web";
  826. DetailCellWeb *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  827. NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  828. NSString* tablecontent = [item valueForKey:@"content"];
  829. cell.webView.tag = indexPath.section;
  830. // cell.webView.scrollView.contentSize.height = 0;
  831. cell.webView.scrollView.bounces=NO;
  832. cell.webView.scrollView.directionalLockEnabled = true;
  833. CGSize size= cell.webView.scrollView.contentSize;
  834. size.height=10;
  835. cell.webView.scrollView.contentSize=size;
  836. cell.webView.navigationDelegate=self;
  837. // nsstring* c = [NSString stringwith]
  838. // NSString *filePath = [[NSBundle mainBundle]pathForResource:@"about" ofType:@"htm"];
  839. // NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
  840. [cell.webView loadHTMLString:tablecontent baseURL:nil];
  841. // dispatch_async(dispatch_get_main_queue(), ^{
  842. //
  843. // wait(5000);
  844. // DebugLog(@"!!!!!!!!!!!!!!!!!!!!!!!!!!!webview section=%ld height=%f",indexPath.section,cell.webView.scrollView.contentSize.height);
  845. //
  846. //// DebugLog(@"url:%@", [self.webView stringByEvaluatingJavaScriptFromString:@"window.location.href;"]); // shows google.com instead of about:blank
  847. // });
  848. // CGRect rect = cell.webView.frame;
  849. // [self.content set_itemheight:cell.webView.frame.size.height AtIndexPath:indexPath];
  850. // [cell.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
  851. return cell;
  852. }
  853. else if([type isEqualToString:@"tracking"])
  854. {
  855. DebugLog(@"cellForRowAtIndexPath =====> table");
  856. static NSString *CellIdentifier = @"detail_item_tracking";
  857. DetailCellTracking *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  858. NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  859. if(indexPath.row==0)
  860. {
  861. cell.trackingIcon.tintColor=UIColorFromRGB(0x1e7ffb);
  862. cell.trackingIcon.image = [[UIImage imageNamed:item[@"icon"]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  863. }
  864. else
  865. {
  866. cell.trackingIcon.tintColor=[UIColor grayColor];
  867. cell.trackingIcon.image = [[UIImage imageNamed:item[@"icon"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
  868. }
  869. cell.trackingMsg.text=item[@"msg"];
  870. // NSString* tablecontent = [item valueForKey:@"content"];
  871. // cell.webView.tag = indexPath.section;
  872. // // cell.webView.scrollView.contentSize.height = 0;
  873. // cell.webView.scrollView.bounces=NO;
  874. // cell.webView.scrollView.directionalLockEnabled = true;
  875. // CGSize size= cell.webView.scrollView.contentSize;
  876. // size.height=10;
  877. // cell.webView.scrollView.contentSize=size;
  878. //
  879. //
  880. // [cell.webView loadHTMLString:tablecontent baseURL:nil];
  881. return cell;
  882. }
  883. else if([type isEqualToString:@"mapping"])
  884. {
  885. NSString *CellIdentifier = @"detail_item_kvnew";
  886. DetailCellKVNew *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  887. NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  888. NSString* key =[item allKeys][0];
  889. // [cell.keyLabel sizeToFit];
  890. NSString* val=[item valueForKey:key];
  891. // if([val isEqual:[NSNull null]])
  892. // val=@"";
  893. cell.keyLabel.text = key;
  894. cell.valLabel.htmlText = val;
  895. if([key isEqualToString:@"Place_Of_Delivery"])
  896. {
  897. // int abc=0;
  898. }
  899. NSLog(@"key %@ val %@",key,val);
  900. cell.tapDelegate = self;
  901. // UIView * lineview = [[LineView alloc] initWithFrame:cell.contentView.frame];
  902. // lineview.userInteractionEnabled = NO;// 不设为NO会屏蔽cell的点击事件
  903. // lineview.backgroundColor = [UIColor clearColor];// 设为透明从而使得cell.backgroundColor有效.
  904. // lineview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  905. // [cell.contentView addSubview:lineview];// cell.contentView是个readonly属性,所以别想着替换contentView了.
  906. return cell;
  907. // float width = tableView.frame.size.width;
  908. //
  909. // width-=CELL_MARGIN*2;
  910. // CGSize constraintkey = CGSizeMake(width*0.4-2*LABEL_MARGIN, 20000.0f);//key label width is 40% cell width;
  911. // CGSize constraintval = CGSizeMake(width*0.6-2*LABEL_MARGIN, 20000.0f);//val label width is 60% cell width;
  912. // NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
  913. // NSString* key =[item allKeys][0];
  914. // // [cell.keyLabel sizeToFit];
  915. // NSString* val=[item valueForKey:key];
  916. // if([val isEqual:[NSNull null]])
  917. // val=@"";
  918. // if(val==nil)
  919. // val=@"";
  920. // if([val isEqualToString:@"null"])
  921. // val=@"";
  922. //
  923. //
  924. //
  925. //
  926. // CGRect frame;
  927. // frame.size = constraintval;
  928. // frame.origin.x=0;
  929. // frame.origin.y=0;
  930. // RTLabel* rtlabel = [[RTLabel alloc] initWithFrame:frame];
  931. // [rtlabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
  932. // // rtlabel.lineSpacing = 20.0;
  933. // [rtlabel setText: val];
  934. // CGSize sizeval=rtlabel.optimumSize;
  935. // CGSize sizekey = [key sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  936. // // CGSize sizeval = [val sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintval lineBreakMode:NSLineBreakByWordWrapping];
  937. //// DebugLog(@"tableView width:%f",width);
  938. ////
  939. //// DebugLog(@"key width= %f val width = %f",constraintkey.width,constraintval.width);
  940. //// DebugLog(@"key = %@ val = %@",key,val);
  941. // float height = MAX(sizekey.height,sizeval.height);
  942. // height = MAX(height, DEF_CELL_HEIGHT-LINE_WIDTH);
  943. // sizekey.height = height;
  944. // sizekey.width = constraintkey.width;
  945. // // sizeval.height = height;
  946. // sizeval.width =constraintval.width;
  947. //
  948. // NSString *CellIdentifier = @"detail_item_kv";
  949. // DetailCellKV *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  950. // if(cell==nil)
  951. // DebugLog(@"cell is nil.........................");
  952. //
  953. //
  954. // // CGRect framekey ;
  955. // // framekey.origin.x=CELL_MARGIN;
  956. // // framekey.origin.y=LINE_WIDTH;
  957. // // framekey.size = sizekey;
  958. // // UILabel* keyLabel = [[UILabel alloc]initWithFrame:framekey];
  959. // // keyLabel.lineBreakMode = NSLineBreakByWordWrapping;
  960. // // keyLabel.backgroundColor = [UIColor grayColor];
  961. // // keyLabel.text = key;
  962. // //
  963. // // CGRect frameval;
  964. // // frameval.origin.x=constraintkey.width+CELL_MARGIN;
  965. // // frameval.origin.y=LINE_WIDTH;
  966. // // frameval.size = sizeval;
  967. // //
  968. // // UILabel* valLabel = [[UILabel alloc]initWithFrame:frameval];
  969. // // valLabel.lineBreakMode = NSLineBreakByWordWrapping;
  970. // // valLabel.text = val;
  971. // //
  972. // // for(UIView* v in cell.contentView.subviews)
  973. // // {
  974. // // [v removeFromSuperview];
  975. // //
  976. // // }
  977. // //
  978. // // [cell.contentView addSubview:keyLabel];
  979. // // [cell.contentView addSubview:valLabel];
  980. //
  981. //
  982. // CGRect framekey = cell.keyLabel.frame;
  983. // framekey.origin.x=CELL_MARGIN+LABEL_MARGIN;
  984. // framekey.origin.y=LINE_WIDTH;
  985. // framekey.size = sizekey;
  986. // cell.keyLabel.frame = framekey;
  987. // cell.keyLabel.text=key;
  988. // CGRect frameval = cell.valLabel.frame;
  989. // frameval.origin.x=constraintkey.width+CELL_MARGIN+3*LABEL_MARGIN; //2 margin for key 1 margin for value self
  990. // frameval.origin.y=LINE_WIDTH;
  991. // frameval.size = sizeval;
  992. // cell.valLabel.frame = frameval;
  993. // // [cell.valLabel setTextAlignment:RTTextAlignmentCenter];
  994. // cell.valLabel.text= val;
  995. // CGPoint rcenter;
  996. // rcenter.x = width * 0.4+width * 0.6/2;
  997. // rcenter.y = height /2;
  998. // cell.valLabel.center=rcenter;
  999. //// cell.valLabel.backgroundColor =[UIColor redColor];
  1000. //
  1001. //// cell.contentView.superview.backgroundColor = [UIColor clearColor];
  1002. //// cell.backgroundColor = [UIColor whiteColor];
  1003. // UIView * lineview = [[LineView alloc] initWithFrame:cell.contentView.frame];
  1004. // lineview.userInteractionEnabled = NO;// 不设为NO会屏蔽cell的点击事件
  1005. // lineview.backgroundColor = [UIColor clearColor];// 设为透明从而使得cell.backgroundColor有效.
  1006. // lineview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  1007. // [cell.contentView addSubview:lineview];// cell.contentView是个readonly属性,所以别想着替换contentView了.
  1008. //
  1009. //
  1010. //
  1011. // // [cell.valLabel sizeToFit];
  1012. // // cell.anameLabel.text = [field valueForKey:@"aname"];
  1013. // // [cell.anameLabel sizeToFit];
  1014. // // DebugLog(@"cellForRowAtIndexPath%@",[field valueForKey:@"aname"]);
  1015. // // Configure the cell...
  1016. // // CGRect rect = cell.frame;
  1017. // // [self.content set_itemheight:100 AtIndexPath:indexPath];
  1018. // return cell;
  1019. }
  1020. else if ([type isEqualToString:@"communication"]) {
  1021. NSInteger rowCount = [tableView numberOfRowsInSection:indexPath.section];
  1022. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  1023. if (indexPath.row == 0) { // head
  1024. AMCommHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:COMM_ID_HEAD forIndexPath:indexPath];
  1025. NSString *to = [segment objectForKey:@"receipt"];
  1026. NSString *cc = [segment objectForKey:@"cc"];
  1027. [cell setTo:to];
  1028. [cell setCc:cc];
  1029. cell.delegate = self;
  1030. return cell;
  1031. } else if (indexPath.row == rowCount - 1) { // edit
  1032. AMCommEditCell *cell = [tableView dequeueReusableCellWithIdentifier:COMM_ID_EDIT forIndexPath:indexPath];
  1033. NSString *editContent = [segment objectForKey:@"edit_content"];
  1034. [cell setEmail:editContent];
  1035. cell.delegate = self;
  1036. return cell;
  1037. } else { // content
  1038. AMCommContentCell *cell = [tableView dequeueReusableCellWithIdentifier:COMM_ID_CONTENT forIndexPath:indexPath];
  1039. NSDictionary *item = [segment objectForKey:[NSString stringWithFormat:@"item%ld",indexPath.row - 1]];
  1040. NSString *sender = [item objectForKey:@"Sender"];
  1041. NSString *content = [item objectForKey:@"msg"];
  1042. NSString *time = [item objectForKey:@"mst_time"];
  1043. NSString *email = [item objectForKey:@"email_url"];
  1044. [cell setSender:sender];
  1045. [cell setContent:content];
  1046. [cell setTime:time];
  1047. [cell setEmail:email];
  1048. cell.delegate = self;
  1049. return cell;
  1050. }
  1051. }
  1052. else
  1053. {
  1054. DebugLog(@"cellForRowAtIndexPath =====> list");
  1055. static NSString *CellIdentifier = @"detail_item_list";
  1056. float width = tableView.frame.size.width;
  1057. width-=CELL_MARGIN*2;
  1058. CGSize constraintkey = CGSizeMake(width, 20000.0f);//key label width is 40% cell width;
  1059. NSDictionary* item = self.content.segments[indexPath.section];
  1060. NSString* val=[item valueForKey:[NSString stringWithFormat:@"line%ld",(long)indexPath.row]];
  1061. if([val isEqual:[NSNull null]])
  1062. val=@"";
  1063. if(val==nil)
  1064. val=@"";
  1065. if([val isEqualToString:@"null"])
  1066. val=@"";
  1067. // CGSize sizeval = [val sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  1068. CGSize sizeval = [val boundingRectWithSize:constraintkey options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:13.0]} context:nil].size;
  1069. float height = sizeval.height;
  1070. height = MAX(height, DEF_CELL_HEIGHT-LINE_WIDTH);
  1071. sizeval.height = height;
  1072. sizeval.width = constraintkey.width;
  1073. //创建cell
  1074. DetailCellList *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  1075. CGRect framekey = cell.listLabel.frame;
  1076. framekey.origin.x=CELL_MARGIN;
  1077. framekey.origin.y=LINE_WIDTH;
  1078. framekey.size = sizeval;
  1079. cell.listLabel.frame = framekey;
  1080. cell.listLabel.text= val;
  1081. return cell;
  1082. }
  1083. return nil;
  1084. }
  1085. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  1086. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  1087. NSString* type =[segment valueForKey:@"_type"];
  1088. NSString* port = self.content.originContent[@"backup_port"];
  1089. if([type isEqualToString:@"tracking"]) {
  1090. NSDictionary *location = [segment objectForKey:@"location"];
  1091. [self.shipMap showShipAnnotaion:location backupLocation:port];
  1092. self.containerSelectedIndexPath = indexPath;
  1093. }
  1094. }
  1095. #pragma mark - Quick Look
  1096. - (MyQLPreviewController *)quickLook {
  1097. if (!_quickLook)
  1098. {
  1099. _quickLook = [[MyQLPreviewController alloc] init];
  1100. _quickLook.delegate = self;
  1101. _quickLook.dataSource = self;
  1102. }
  1103. else
  1104. {
  1105. [_quickLook reloadData];
  1106. }
  1107. return _quickLook;
  1108. }
  1109. #pragma mark - QuickLook Data Source
  1110. - (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
  1111. return 1;
  1112. }
  1113. - (id <QLPreviewItem>) previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
  1114. return [NSURL fileURLWithPath:self.documentPath];
  1115. }
  1116. #pragma mark - QuickLook Delegate
  1117. - (void) previewControllerDidDismiss:(QLPreviewController *)controller {
  1118. }
  1119. /**
  1120. * 文件内部链接点击不进行外部跳转
  1121. */
  1122. - (BOOL) previewController:(QLPreviewController *)controller shouldOpenURL:(NSURL *)url forPreviewItem:(id<QLPreviewItem>)item {
  1123. return NO;
  1124. }
  1125. #pragma mark - KVDetail Tap Delegate
  1126. - (void)detailCell:(DetailCellKVNew *)cell doubleTapedForValue:(NSString *)value {
  1127. // NSIndexPath *indexPath = [self.table indexPathForCell:cell];
  1128. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1129. pasteboard.string = value;
  1130. [DetailHUD show:[NSString stringWithFormat:@"%@ Copied",cell.keyLabel.text] inView:self.view];
  1131. }
  1132. #pragma mark - Quick Look Menu Action
  1133. - (void)saveDocument {
  1134. NSMutableDictionary *emailInfo = [NSMutableDictionary new];
  1135. if (self.email.length==0) {
  1136. self.email=@"";
  1137. }
  1138. if (self.email_subject.length==0) {
  1139. self.email_subject=@"";
  1140. }
  1141. if (self.email_content.length==0) {
  1142. self.email_content=@"";
  1143. }
  1144. [emailInfo setValue:self.email forKey:@"reciptions"];
  1145. [emailInfo setValue:self.email_subject forKey:@"subject"];
  1146. [emailInfo setValue:self.email_content forKey:@"content"];
  1147. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1148. NSString *path = [paths objectAtIndex:0];
  1149. NSString *filePath = [path stringByAppendingPathComponent:[self.documentPath lastPathComponent]];
  1150. NSString *emailPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@".%@",[[self.documentPath stringByDeletingPathExtension] lastPathComponent]]];
  1151. NSError *err;
  1152. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  1153. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1154. }
  1155. [[NSFileManager defaultManager] moveItemAtPath:self.documentPath toPath:filePath error:&err];
  1156. NSData* saved_email_data = [RAConvertor dict2data:emailInfo];
  1157. [saved_email_data writeToFile:emailPath atomically:NO];
  1158. UIAlertController *alertVC;
  1159. UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1160. }];
  1161. if (err) {
  1162. alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"save document failed:\n%@",err.localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
  1163. } else {
  1164. alertVC = [UIAlertController alertControllerWithTitle:nil message:@"Document Saved" preferredStyle:UIAlertControllerStyleAlert];
  1165. }
  1166. [alertVC addAction:action];
  1167. [self presentViewController:alertVC animated:YES completion:nil];
  1168. }
  1169. - (void)shareDocument {
  1170. return [self share_activity];
  1171. }
  1172. -(void) share_activity
  1173. {
  1174. // 设置分享内容
  1175. // NSString *text = @"分享内容";
  1176. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1177. NSString *path = [paths objectAtIndex:0];
  1178. NSString *filePath = [path stringByAppendingPathComponent:[self.documentPath lastPathComponent]];
  1179. // 没有保存的情况
  1180. if ([[NSFileManager defaultManager] fileExistsAtPath:self.documentPath]) {
  1181. filePath = self.documentPath;
  1182. }
  1183. NSURL *url = [NSURL fileURLWithPath:filePath];
  1184. NSArray *activityItems = @[url];
  1185. LPShareActivity *share = [[LPShareActivity alloc] init];
  1186. share.to = [self.email componentsSeparatedByString:@","];//@[@"676767@qq.com"];
  1187. share.subject = self.email_subject;//@"test subject";
  1188. share.body = self.email_content;// @"body";
  1189. share.filePath = filePath;
  1190. share.handle = ^(UIViewController *vc) {
  1191. [self presentViewController:vc animated:YES completion:^{
  1192. // [share activityDidFinish:YES];
  1193. // ...
  1194. }];
  1195. };
  1196. // 服务类型控制器
  1197. UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:@[share]];
  1198. // _activityViewController = activityViewController;
  1199. // activityViewController.excludedActivityTypes = @[UIActivityTypeMail];
  1200. activityViewController.modalInPopover = true;
  1201. [self presentViewController:activityViewController animated:YES completion:nil];
  1202. // 选中分享类型
  1203. [activityViewController setCompletionWithItemsHandler:^(NSString * __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
  1204. // 显示选中的分享类型
  1205. NSLog(@"act type %@",activityType);
  1206. if (completed) {
  1207. NSLog(@"ok");
  1208. }else {
  1209. NSLog(@"not ok");
  1210. }
  1211. }];
  1212. }
  1213. - (void)quickLookMenuClick:(id)sender {
  1214. UIAlertController *menuAlert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1215. __weak typeof(self) weakSelf = self;
  1216. UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"Save Document" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1217. [weakSelf saveDocument];
  1218. }];
  1219. UIAlertAction *shareAction = [UIAlertAction actionWithTitle:@"Share Document" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1220. [weakSelf shareDocument];
  1221. }];
  1222. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  1223. }];
  1224. [menuAlert addAction:saveAction];
  1225. [menuAlert addAction:shareAction];
  1226. [menuAlert addAction:cancelAction];
  1227. [self presentViewController:menuAlert animated:YES completion:nil];
  1228. }
  1229. #pragma mark - Keyboard
  1230. - (void)startListenKeyboard {
  1231. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  1232. // 键盘通知
  1233. [notificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  1234. [notificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  1235. [notificationCenter addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
  1236. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToHideKeyboard:)];
  1237. [self.view addGestureRecognizer:tap];
  1238. self.tap = tap;
  1239. }
  1240. - (void)stopListenKeyboard {
  1241. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  1242. [notificationCenter removeObserver:self];
  1243. [self.view removeGestureRecognizer:self.tap];
  1244. }
  1245. - (void)tapToHideKeyboard:(UITapGestureRecognizer *)tap {
  1246. [self.view endEditing:YES];
  1247. }
  1248. /**键盘隐藏*/
  1249. - (void)keyboardWillHide:(NSNotification *)notification {
  1250. NSLog(@"keyboard hide");
  1251. self.showKeyboard = NO;
  1252. }
  1253. /**键盘显示*/
  1254. - (void)keyboardWillShow:(NSNotification *)notification {
  1255. // NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1256. // CGRect begin = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
  1257. // CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  1258. //
  1259. // if (duration == 0) {
  1260. // duration = 0.25;
  1261. // }
  1262. NSLog(@"keyboard show");
  1263. self.showKeyboard = YES;
  1264. }
  1265. /**在使用过程中切换键盘*/
  1266. - (void)keyboardChangeFrame:(NSNotification *)notification {
  1267. NSLog(@"keyboard change frame");
  1268. NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1269. // CGRect begin = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
  1270. CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  1271. if (duration == 0) {
  1272. duration = 0.25;
  1273. }
  1274. NSLayoutConstraint *bottom_constraint = nil;
  1275. for (NSLayoutConstraint *constraint in self.view.constraints) {
  1276. if ([constraint.identifier isEqualToString:@"table_bottom_constraint"]) {
  1277. bottom_constraint = constraint;
  1278. break;
  1279. }
  1280. }
  1281. CGFloat tabBarY = CGRectGetMinY(self.tabBarController.tabBar.frame);
  1282. CGFloat offset = tabBarY - CGRectGetMinY(end);
  1283. if (offset < 0) {
  1284. offset = 0;
  1285. }
  1286. if (bottom_constraint) {
  1287. bottom_constraint.constant = offset;
  1288. [self.view layoutIfNeeded];
  1289. if (self.editingIndexPath) {
  1290. [self.table scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionNone animated:UITableViewRowAnimationNone];
  1291. }
  1292. }
  1293. CGSize contentSize = self.table.contentSize;
  1294. CGPoint contentOffset = self.table.contentOffset;
  1295. offset = contentOffset.y - (contentSize.height - CGRectGetHeight(self.table.bounds));
  1296. if (offset > 0) {
  1297. contentOffset.y -= offset;
  1298. self.table.contentOffset = contentOffset;
  1299. }
  1300. }
  1301. #pragma mark - COMM Head Delegate
  1302. - (void)commHeadCell:(AMCommHeadCell *)cell didChangeCC:(NSString *)cc {
  1303. NSIndexPath *indexPath = [self.table indexPathForCell:cell];
  1304. [self cc:cc changedForIndexPath:indexPath];
  1305. }
  1306. - (void)commHeadCell:(AMCommHeadCell *)cell didBeginEditing:(UITextField *)textField {
  1307. self.editingCell = cell;
  1308. self.editingIndexPath = [self.table indexPathForCell:cell];
  1309. }
  1310. - (void)commHeadCell:(AMCommHeadCell *)cell didEndEditing:(UITextField *)textField {
  1311. self.editingCell = nil;
  1312. self.editingIndexPath = nil;
  1313. }
  1314. - (void)commHeadCell:(AMCommHeadCell *)cell didClickContactButton:(UIButton *)button {
  1315. self.contactSelectIndexPath = [self.table indexPathForCell:cell];
  1316. CNContactPickerViewController *contactVC = [[CNContactPickerViewController alloc] init];
  1317. contactVC.delegate = self;
  1318. [self presentViewController:contactVC animated:YES completion:nil];
  1319. }
  1320. #pragma mark - COMM Content Delegate
  1321. - (void)commContentCell:(AMCommContentCell *)cell sendEmail:(NSString *)email {
  1322. // MFMailComposeViewController *emailVC = [[MFMailComposeViewController alloc] init];
  1323. // if (!emailVC) {
  1324. //
  1325. // return;
  1326. // }
  1327. // [emailVC setMessageBody:[NSString stringWithFormat:@"<a>%@</a>",email] isHTML:YES];
  1328. //
  1329. // [self presentViewController:emailVC animated:YES completion:nil];
  1330. NSURL *url = [NSURL URLWithString:email];
  1331. if ([[UIApplication sharedApplication] canOpenURL:url]) {
  1332. [[UIApplication sharedApplication] openURL:url];
  1333. }
  1334. }
  1335. #pragma mark - COMM Edit Delegate
  1336. - (void)commEditCell:(AMCommEditCell *)cell clickToSendEmail:(NSString *)email {
  1337. // 检查Email内容是否为空
  1338. if (!email || email.length == 0) {
  1339. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"The communication message that will be sent is blank" preferredStyle:UIAlertControllerStyleAlert];
  1340. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1341. }];
  1342. [alert addAction:okAction];
  1343. [self presentViewController:alert animated:YES completion:nil];
  1344. return;
  1345. }
  1346. NSIndexPath *indexPath = [self.table indexPathForCell:cell];
  1347. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  1348. NSString *cc = [segment objectForKey:@"cc"];
  1349. if (cc && cc.length > 0) {
  1350. // 校验邮箱地址格式是否有效
  1351. NSArray *ccArr = [cc componentsSeparatedByString:@";"];
  1352. for (NSString *ccStr in ccArr) {
  1353. if (ccStr.length > 0) {
  1354. BOOL isEmail = [self validateEmail:ccStr];
  1355. if (!isEmail) {
  1356. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"The communication cc is not right" preferredStyle:UIAlertControllerStyleAlert];
  1357. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1358. }];
  1359. [alert addAction:okAction];
  1360. [self presentViewController:alert animated:YES completion:nil];
  1361. return;
  1362. }
  1363. }
  1364. }
  1365. // 校验通过
  1366. }
  1367. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"send email" preferredStyle:UIAlertControllerStyleAlert];
  1368. [self presentViewController:alert animated:YES completion:nil];
  1369. NSString *serialNo = [segment objectForKey:@"serial_no"];
  1370. __weak typeof(self) weakSelf = self;
  1371. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1372. NSDictionary *sendResponse = [RANetwork sendEmail:email CC:cc SerialNo:serialNo];
  1373. dispatch_async(dispatch_get_main_queue(), ^{
  1374. [alert dismissViewControllerAnimated:YES completion:^{
  1375. if (weakSelf) {
  1376. __strong typeof(weakSelf) strongSelf = weakSelf;
  1377. int result = [[sendResponse objectForKey:@"result"] intValue];
  1378. if (result == RESULT_TRUE) {
  1379. } else {
  1380. NSString *msg = [sendResponse objectForKey:@"err_msg"];
  1381. if (msg == nil) {
  1382. msg = @"Sorry,something wrong";
  1383. }
  1384. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
  1385. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1386. }];
  1387. [alert addAction:okAction];
  1388. [strongSelf presentViewController:alert animated:YES completion:nil];
  1389. }
  1390. }
  1391. }];
  1392. });
  1393. });
  1394. }
  1395. - (void)commEditCell:(AMCommEditCell *)cell didChangeEmail:(NSString *)email {
  1396. // 保存数据
  1397. NSIndexPath *indexPath = [self.table indexPathForCell:cell];
  1398. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  1399. if (email && email.length > 0) {
  1400. [segment setValue:email forKey:@"edit_content"];
  1401. } else {
  1402. [segment removeObjectForKey:@"edit_content"];
  1403. }
  1404. NSMutableArray *arr = [self.content.segments mutableCopy];
  1405. [arr replaceObjectAtIndex:indexPath.section withObject:segment];
  1406. self.content.segments = arr;
  1407. // 调用 tableView 的 beginUpdates 和 endUpdates,重新计算 cell 的高度
  1408. [self.table beginUpdates];
  1409. [self.table endUpdates];
  1410. // 防止在输入的时候超出屏幕区域
  1411. CGRect frame = cell.frame;
  1412. if (CGRectGetMaxY(frame) > CGRectGetMaxY(self.table.bounds)) {
  1413. [self.table scrollRectToVisible:frame animated:NO];
  1414. }
  1415. }
  1416. - (void)commEditCell:(AMCommEditCell *)cell didBeginEditing:(UITextView *)textView {
  1417. self.editingCell = cell;
  1418. self.editingIndexPath = [self.table indexPathForCell:cell];
  1419. }
  1420. - (void)commEditCell:(AMCommEditCell *)cell didEndEditing:(UITextView *)textView {
  1421. self.editingCell = nil;
  1422. self.editingIndexPath = nil;
  1423. }
  1424. #pragma mark - Contact Picker Delegate
  1425. - (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
  1426. self.contactSelectIndexPath = nil;
  1427. }
  1428. - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
  1429. [self handleSelectContact:contact];
  1430. self.contactSelectIndexPath = nil;
  1431. }
  1432. - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
  1433. for (CNContact *contact in contacts) {
  1434. [self handleSelectContact:contact];
  1435. }
  1436. self.contactSelectIndexPath = nil;
  1437. }
  1438. - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
  1439. self.contactSelectIndexPath = nil;
  1440. }
  1441. - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperties:(NSArray<CNContactProperty *> *)contactProperties {
  1442. self.contactSelectIndexPath = nil;
  1443. }
  1444. #pragma mark - Utils
  1445. - (BOOL)validateEmail:(NSString *)email {
  1446. NSString *emailRegex =@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  1447. NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  1448. return [emailTest evaluateWithObject:email];
  1449. }
  1450. - (void)handleSelectContact:(CNContact *)contact {
  1451. NSArray *emailArr = [contact emailAddresses];
  1452. for (CNLabeledValue *value in emailArr) {
  1453. if ([value.label isEqualToString:CNLabelWork]) {
  1454. [self appendCC:[NSString stringWithFormat:@"%@;",value.value] forIndexPath:self.contactSelectIndexPath];
  1455. [self.table reloadRowsAtIndexPaths:@[self.contactSelectIndexPath] withRowAnimation:UITableViewRowAnimationNone];
  1456. AMCommHeadCell *cell = [self.table cellForRowAtIndexPath:self.contactSelectIndexPath];
  1457. [cell beginEditing];
  1458. break;
  1459. }
  1460. }
  1461. }
  1462. - (void)appendCC:(NSString *)cc forIndexPath:(NSIndexPath *)indexPath {
  1463. if (indexPath == nil || cc == nil || cc.length == 0) {
  1464. return;
  1465. }
  1466. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  1467. NSString *oldCC = [segment objectForKey:@"cc"];
  1468. if (oldCC == nil || oldCC.length == 0) {
  1469. oldCC = cc;
  1470. } else {
  1471. if ([[oldCC substringFromIndex:oldCC.length - 1] isEqualToString:@";"]) {
  1472. oldCC = [oldCC stringByAppendingString:cc];
  1473. } else {
  1474. oldCC = [oldCC stringByAppendingString:[NSString stringWithFormat:@";%@",cc]];
  1475. }
  1476. }
  1477. [self cc:oldCC changedForIndexPath:indexPath];
  1478. }
  1479. - (void)cc:(NSString *)cc changedForIndexPath:(NSIndexPath *)indexPath {
  1480. if (indexPath == nil) {
  1481. return;
  1482. }
  1483. NSMutableDictionary* segment = [self.content.segments[indexPath.section] mutableCopy];
  1484. if (cc && cc.length > 0) {
  1485. [segment setValue:cc forKey:@"cc"];
  1486. } else {
  1487. [segment removeObjectForKey:@"cc"];
  1488. }
  1489. NSMutableArray *arr = [self.content.segments mutableCopy];
  1490. [arr replaceObjectAtIndex:indexPath.section withObject:segment];
  1491. self.content.segments = arr;
  1492. }
  1493. #pragma mark - ShipMap Delegate
  1494. - (void)shipMap:(AMShipMap *)shipMap tryToZoomIn:(BOOL)zoomIn {
  1495. if (zoomIn) {
  1496. NSArray *constraints = self.view.constraints;
  1497. NSLayoutConstraint *h_ratio_constraint = nil;
  1498. for (NSLayoutConstraint *constraint in constraints) {
  1499. if (constraint.identifier && [constraint.identifier isEqualToString:@"ratio_constraint"]) {
  1500. h_ratio_constraint = constraint;
  1501. }
  1502. }
  1503. if (h_ratio_constraint) {
  1504. [self.view removeConstraint:h_ratio_constraint];
  1505. }
  1506. NSLayoutConstraint *table_h_constraint = [NSLayoutConstraint constraintWithItem:self.table
  1507. attribute:NSLayoutAttributeHeight
  1508. relatedBy:NSLayoutRelationEqual
  1509. toItem:nil
  1510. attribute:NSLayoutAttributeNotAnAttribute
  1511. multiplier:0
  1512. constant:0];
  1513. table_h_constraint.identifier = @"table_height";
  1514. [self.view addConstraint:table_h_constraint];
  1515. } else {
  1516. NSArray *constraints = self.view.constraints;
  1517. NSLayoutConstraint *h_constraint = nil;
  1518. for (NSLayoutConstraint *constraint in constraints) {
  1519. if (constraint.identifier && [constraint.identifier isEqualToString:@"table_height"]) {
  1520. h_constraint = constraint;
  1521. }
  1522. }
  1523. if (h_constraint) {
  1524. [self.view removeConstraint:h_constraint];
  1525. }
  1526. float h_ratio = 0.5;
  1527. NSLayoutConstraint *h_ratio_constraint = [NSLayoutConstraint constraintWithItem:shipMap
  1528. attribute:NSLayoutAttributeHeight
  1529. relatedBy:NSLayoutRelationEqual
  1530. toItem:self.table
  1531. attribute:NSLayoutAttributeHeight
  1532. multiplier:h_ratio
  1533. constant:0];
  1534. h_ratio_constraint.identifier = @"ratio_constraint";
  1535. [self.view addConstraint:h_ratio_constraint];
  1536. }
  1537. [self.view layoutIfNeeded];
  1538. }
  1539. @end