RAOrderEditViewController.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. //
  2. // RAOrderEditViewController.m
  3. // Apex And Drivers
  4. //
  5. // Created by Jack on 2018/6/4.
  6. // Copyright © 2018年 USAI. All rights reserved.
  7. //
  8. #import "RAOrderEditViewController.h"
  9. #import "RAEditInputModel.h"
  10. #import "RAEditMultInputModel.h"
  11. #import "RAEditLabelModel.h"
  12. #import "RAEditPhotoModel.h"
  13. #import "RAProgressHUD.h"
  14. #import "ZipArchive.h"
  15. #import "AppDelegate.h"
  16. #import <CoreLocation/CoreLocation.h>
  17. @interface RAEditSectionModel : NSObject
  18. @property (nonatomic,strong) NSArray <RAEditBaseModel *> *items;
  19. @property (nonatomic,copy) NSString *title;
  20. @end
  21. @implementation RAEditSectionModel
  22. - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
  23. }
  24. - (void)setItems:(NSArray<RAEditBaseModel *> *)items {
  25. NSArray *tmpItems = items;
  26. NSMutableArray *itemArr = [NSMutableArray arrayWithCapacity:items.count];
  27. for (int i = 0; i < tmpItems.count; i++) {
  28. NSDictionary *item = [tmpItems objectAtIndex:i];
  29. RAEditType type = [[item objectForKey:@"type"] intValue];
  30. switch (type) {
  31. case RAEditTypeLabel: {
  32. RAEditLabelModel *model = [RAEditLabelModel new];
  33. [model setValuesForKeysWithDictionary:item];
  34. [itemArr addObject:model];
  35. }
  36. break;
  37. case RAEditTypeInput: {
  38. RAEditInputModel *model = [RAEditInputModel new];
  39. [model setValuesForKeysWithDictionary:item];
  40. [itemArr addObject:model];
  41. }
  42. break;
  43. case RAEditTypeMultInput: {
  44. RAEditMultInputModel *model = [RAEditMultInputModel new];
  45. [model setValuesForKeysWithDictionary:item];
  46. [itemArr addObject:model];
  47. }
  48. break;
  49. case RAEditTypePhoto: {
  50. RAEditPhotoModel *model = [RAEditPhotoModel new];
  51. [model setValuesForKeysWithDictionary:item];
  52. [itemArr addObject:model];
  53. }
  54. break;
  55. default:
  56. break;
  57. }
  58. }
  59. _items = itemArr;
  60. }
  61. - (NSInteger)itemCount {
  62. return self.items.count;
  63. }
  64. - (RAEditBaseModel *)itemModelForIndex:(NSInteger)index {
  65. return [self.items objectAtIndex:index];
  66. }
  67. @end
  68. #pragma mark - View Controller
  69. @interface RAOrderEditViewController ()
  70. @property (nonatomic,strong) IBOutlet UITableView *orderEditTableView;
  71. @property (nonatomic,strong) NSMutableArray *sectionArray;
  72. @property (nonatomic,copy) NSString *photoDir;
  73. @property (nonatomic,strong) UIRefreshControl *refreshControl;
  74. @end
  75. @implementation RAOrderEditViewController
  76. + (instancetype)viewControllerFromStoryboard {
  77. RAOrderEditViewController *editVC = [[UIStoryboard storyboardWithName:@"Edit" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  78. return editVC;
  79. }
  80. - (void)viewDidLoad {
  81. [super viewDidLoad];
  82. // Do any additional setup after loading the view.
  83. [RASingleton.sharedInstance saveLogs];
  84. [self configureTable];
  85. [self configureNavigationBar];
  86. [self loadData];
  87. }
  88. - (void)viewWillAppear:(BOOL)animated {
  89. [super viewWillAppear:animated];
  90. [self registKeyboardListener];
  91. }
  92. - (void)viewWillDisappear:(BOOL)animated {
  93. [super viewWillDisappear:animated];
  94. [self unregistKeyboardListener];
  95. }
  96. - (void)didReceiveMemoryWarning {
  97. [super didReceiveMemoryWarning];
  98. // Dispose of any resources that can be recreated.
  99. }
  100. #pragma mark - Configure
  101. - (void)configureTable {
  102. if (@available(iOS 11.0, *)) {
  103. self.orderEditTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  104. } else {
  105. self.automaticallyAdjustsScrollViewInsets = NO;
  106. }
  107. self.orderEditTableView.tableFooterView = [UIView new];
  108. self.orderEditTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
  109. UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
  110. [refresh addTarget:self action:@selector(refreshControlValueChanged:) forControlEvents:UIControlEventValueChanged];
  111. [self.orderEditTableView addSubview:refresh];
  112. self.refreshControl = refresh;
  113. }
  114. - (void)configureNavigationBar {
  115. UIBarButtonItem *updateItem = [[UIBarButtonItem alloc] initWithTitle:@"Update" style:UIBarButtonItemStylePlain target:self action:@selector(updateBtnClick:)];
  116. self.navigationItem.rightBarButtonItem = updateItem;
  117. }
  118. - (void)registKeyboardListener {
  119. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
  120. }
  121. - (void)unregistKeyboardListener {
  122. [[NSNotificationCenter defaultCenter] removeObserver:self];
  123. }
  124. #pragma mark - Action
  125. - (void)refreshControlValueChanged:(UIRefreshControl *)refresh {
  126. [self loadData];
  127. }
  128. #pragma mark - Getter
  129. - (NSMutableArray *)sectionArray {
  130. if (!_sectionArray) {
  131. _sectionArray = [NSMutableArray array];
  132. }
  133. return _sectionArray;
  134. }
  135. - (NSUInteger)editSectionCount {
  136. return self.sectionArray.count;
  137. }
  138. - (NSInteger)itemCountForSection:(NSInteger)section {
  139. return [[self.sectionArray objectAtIndex:section] itemCount];
  140. }
  141. - (RAEditBaseModel *)modelForIndexPath:(NSIndexPath *)indexPath {
  142. return [[self.sectionArray objectAtIndex:indexPath.section] itemModelForIndex:indexPath.row];
  143. }
  144. - (NSString *)titleForSection:(NSInteger)section {
  145. return [[self.sectionArray objectAtIndex:section] title];
  146. }
  147. - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell {
  148. return [self.orderEditTableView indexPathForCell:cell];
  149. }
  150. #pragma mark - Data
  151. - (void)loadData {
  152. if (self.loading) {
  153. return;
  154. }
  155. self.loading = YES;
  156. // show progress
  157. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  158. NSString *orderID = self.orderID;
  159. NSInteger actionID = self.actionID;
  160. __weak typeof(self) weakSelf = self;
  161. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  162. NSDictionary *json = [RADataProvider requestUpdateOrder:orderID driverAction:actionID];
  163. dispatch_async(dispatch_get_main_queue(), ^{
  164. // dismiss progress
  165. [hud dismiss];
  166. if (weakSelf.refreshControl.isRefreshing) {
  167. [weakSelf.refreshControl endRefreshing];
  168. }
  169. if (weakSelf) {
  170. __strong typeof(weakSelf) strongSelf = weakSelf;
  171. int result = [[json objectForKey:@"result"] intValue];
  172. if (result == RESULT_TRUE) {
  173. NSArray *sectionArray = [json objectForKey:@"sections"];
  174. [strongSelf.sectionArray removeAllObjects];
  175. for (int i = 0; i < sectionArray.count; i++) {
  176. NSDictionary *section = [sectionArray objectAtIndex:i];
  177. RAEditSectionModel *model = [RAEditSectionModel new];
  178. [model setValuesForKeysWithDictionary:section];
  179. [strongSelf.sectionArray addObject:model];
  180. }
  181. [strongSelf.orderEditTableView reloadData];
  182. } else {
  183. [strongSelf.sectionArray removeAllObjects];
  184. strongSelf.orderEditTableView.contentOffset = CGPointZero;
  185. [strongSelf.orderEditTableView reloadData];
  186. // process error
  187. NSString *msg = [json objectForKey:@"err_msg"];
  188. // [strongSelf showAlert:msg];
  189. [strongSelf showAlertTilte:@"Warning" message:msg];
  190. }
  191. }
  192. self.loading = NO;
  193. });
  194. });
  195. }
  196. #pragma mark - Tap Action
  197. - (IBAction)tapToResignFirstResponder:(UITapGestureRecognizer *)sender {
  198. [self.view endEditing:YES];
  199. }
  200. - (void)updateBtnClick:(UIBarButtonItem *)sender {
  201. // show progress
  202. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  203. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  204. if (self.orderType2) {
  205. [params setObject:self.orderType2 forKey:@"orderType2"];
  206. }
  207. if (RASingleton.sharedInstance.requiredLocation) {
  208. CLLocation *location = RASingleton.sharedInstance.currentLocation;
  209. NSString *latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
  210. [params setObject:latLon forKey:@"location"];
  211. }
  212. NSMutableArray <RAEditPhotoModel *> *photoArr = [self prepareParams:params];
  213. __weak typeof(self) weakSelf = self;
  214. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  215. NSDictionary *json = [RADataProvider submitEditOrder:params];
  216. if (weakSelf) {
  217. __strong typeof(weakSelf) strongSelf = weakSelf;
  218. int result = [[json objectForKey:@"result"] intValue];
  219. if (result == RESULT_TRUE) {
  220. BOOL requiredLocation = [[json objectForKey:@"requiredLocation"] boolValue];
  221. [RASingleton sharedInstance].requiredLocation = requiredLocation;
  222. dispatch_async(dispatch_get_main_queue(), ^{
  223. if (photoArr.count > 0) {
  224. [strongSelf syncUploadPhotos:photoArr Json:json HUD:hud];
  225. } else {
  226. [self gobackHome];
  227. }
  228. });
  229. } else {
  230. // process error
  231. dispatch_async(dispatch_get_main_queue(), ^{
  232. // dismiss progress
  233. [hud dismiss:^{
  234. NSString *msg = [json objectForKey:@"err_msg"];
  235. [strongSelf showAlertTilte:@"Warning" message:msg];
  236. }];
  237. });
  238. }
  239. }
  240. });
  241. }
  242. - (void)backgroundUploadPhoto:(NSArray *)photos Json:(NSDictionary *)json {
  243. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  244. NSDate *date = [NSDate date];
  245. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  246. formatter.dateFormat = @"MM/dd/YYYY HH:mm";
  247. NSString *time = [formatter stringFromDate:date];
  248. for (RAEditPhotoModel *model in photos) {
  249. NSString *serial = [json objectForKey:model.key];
  250. if (serial.length) {
  251. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  252. [params setObject:serial forKey:@"serial"];
  253. if (self.orderType2) {
  254. [params setObject:self.orderType2 forKey:@"orderType2"];
  255. }
  256. [params setObject:[RASingleton.sharedInstance encryptUser] forKey:@"name"];
  257. [params setObject:[RASingleton.sharedInstance encryptPassword] forKey:@"password"];
  258. [params setObject:@"iOS" forKey:@"platform"];
  259. NSString *photoPath = [self.photoDir.lastPathComponent stringByAppendingPathComponent:model.photoName];
  260. NSMutableDictionary *task = [@{
  261. @"order" : self.orderID,
  262. @"action" : self.actionTitle,
  263. @"name" : model.title,
  264. @"time" : time,
  265. @"url" : URL_UPLOAD,
  266. @"file" : photoPath,
  267. @"params" : params
  268. } mutableCopy];
  269. [appDelegate.uploadManager addTask:task];
  270. }
  271. }
  272. }
  273. - (void)syncUploadPhotos:(NSMutableArray *)photoArr Json:(NSDictionary *)json HUD:(RAProgressHUD *)hud {
  274. dispatch_async(dispatch_get_main_queue(), ^{
  275. RAProgressHUD *innerHUD = hud;
  276. if (!innerHUD) {
  277. innerHUD = [RAProgressHUD showHUDOnView:self.view]; // main queue
  278. }
  279. dispatch_async(dispatch_get_global_queue(0, 0), ^{ // network
  280. int retryCount = 0;
  281. NSMutableArray *completArr = [NSMutableArray array];
  282. // 同步上传照片
  283. for (int i = 0; i < photoArr.count; i++) {
  284. RAEditPhotoModel *model = [photoArr objectAtIndex:i];
  285. NSString *serial = [json objectForKey:model.key];
  286. if (serial.length) {
  287. NSMutableDictionary *fileParams = [NSMutableDictionary dictionary];
  288. [fileParams setObject:serial forKey:@"serial"];
  289. if (self.orderType2) {
  290. [fileParams setObject:self.orderType2 forKey:@"orderType2"];
  291. }
  292. NSString *photoPath = [self.photoDir stringByAppendingPathComponent:model.photoName];
  293. NSDictionary *uploadJson = [RADataProvider uploadFile:photoPath parameters:fileParams];
  294. int uploadResult = [[uploadJson objectForKey:@"result"] intValue];
  295. if (uploadResult != RESULT_TRUE) { // 失败重试
  296. i--;
  297. retryCount++;
  298. if (retryCount >= 3) {
  299. break;
  300. }
  301. } else {
  302. [completArr addObject:model];
  303. retryCount = 0;
  304. // 删除文件
  305. if ([[NSFileManager defaultManager] fileExistsAtPath:photoPath]) {
  306. [[NSFileManager defaultManager] removeItemAtPath:photoPath error:nil];
  307. }
  308. }
  309. } // serial
  310. } // for
  311. // 将完成的model移除
  312. [photoArr removeObjectsInArray:completArr];
  313. __weak typeof(self) weakSelf = self;
  314. dispatch_async(dispatch_get_main_queue(), ^{
  315. [innerHUD dismiss:^{
  316. if (photoArr.count > 0) {
  317. // 上传失败,询问是否丢到后台线程上传,否则重启上传
  318. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:@"upload the photos failed,would you like to retry or do it background?" preferredStyle:UIAlertControllerStyleAlert];
  319. UIAlertAction *backgroundAction = [UIAlertAction actionWithTitle:@"Background" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  320. // 开启后台上传
  321. [weakSelf backgroundUploadPhoto:photoArr Json:json];
  322. // 返回首页
  323. [weakSelf gobackHome];
  324. }];
  325. UIAlertAction *retryAction = [UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  326. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  327. [weakSelf syncUploadPhotos:photoArr Json:json HUD:nil];
  328. });
  329. }];
  330. [alertVC addAction:backgroundAction];
  331. [alertVC addAction:retryAction];
  332. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  333. } else {
  334. // 上传完成,返回到首页
  335. [weakSelf gobackHome];
  336. }
  337. }];
  338. });
  339. });
  340. });
  341. }
  342. - (void)gobackHome {
  343. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationReloadHome object:nil];
  344. [self.navigationController popToRootViewControllerAnimated:YES];
  345. }
  346. #pragma mark - Keyboard Listener
  347. - (void)keyboardWillChangeFrame:(NSNotification *)notification {
  348. CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  349. CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
  350. CGFloat keyboardHeight = screenHeight - CGRectGetMinY(end);
  351. UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
  352. self.orderEditTableView.contentInset = insets;
  353. if (self.editingIndexPath) {
  354. [self.orderEditTableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  355. }
  356. }
  357. #pragma mark - Package Update Data
  358. - (NSString *)photoDir {
  359. if (!_photoDir) {
  360. NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  361. NSString *photoDir = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld_%@",self.orderID,(long)self.actionID,[NSUUID UUID].UUIDString]];
  362. NSError *error;
  363. // BOOL dirExist = YES;
  364. // for (int i = 0; i < INT_MAX; i++) {
  365. // if (i != 0) {
  366. // photoDir = [photoDir stringByAppendingString:[NSString stringWithFormat:@"(%d)",i]];
  367. // }
  368. // if (![[NSFileManager defaultManager] fileExistsAtPath:photoDir]) {
  369. // dirExist = NO;
  370. // break;
  371. // }
  372. // }
  373. [[NSFileManager defaultManager] createDirectoryAtPath:photoDir withIntermediateDirectories:YES attributes:nil error:&error];
  374. if (error) {
  375. NSLog(@"create dir %@ failed %@",photoDir,error.localizedDescription);
  376. return nil;
  377. }
  378. _photoDir = photoDir;
  379. }
  380. return _photoDir;
  381. }
  382. - (NSMutableArray <RAEditPhotoModel *> *)prepareParams:(NSMutableDictionary *)params {
  383. if (params == nil) {
  384. return nil;
  385. }
  386. NSMutableArray <RAEditPhotoModel *> *photoArr = [NSMutableArray array];
  387. NSString *photoDir = [self photoDir];
  388. [params setObject:self.orderID forKey:@"orderID"];
  389. [params setObject:@(self.actionID) forKey:@"actionID"];
  390. NSString* encryptu = [RASingleton sharedInstance].encryptUser;
  391. NSString* encryptp = [RASingleton sharedInstance].encryptPassword;
  392. [params setObject:encryptu forKey:@"name"];
  393. [params setObject:encryptp forKey:@"password"];
  394. [params setObject:@"iOS" forKey:@"platform"];
  395. if ([RASingleton sharedInstance].currentLocation) {
  396. [params setObject:[NSString stringWithFormat:@"%f,%f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude] forKey:@"location"];
  397. }
  398. for (RAEditSectionModel *section in self.sectionArray) {
  399. for (int i = 0; i < [section itemCount]; i++) {
  400. RAEditBaseModel *model = [section itemModelForIndex:i];
  401. switch (model.type) {
  402. case RAEditTypeLabel: {
  403. }
  404. break;
  405. case RAEditTypeInput: {
  406. RAEditInputModel *inputModel = (RAEditInputModel *)model;
  407. if (inputModel.key && inputModel.value.length > 0) {
  408. [params setObject:inputModel.value forKey:inputModel.key];
  409. }
  410. }
  411. break;
  412. case RAEditTypeMultInput: {
  413. RAEditMultInputModel *multInputModel = (RAEditMultInputModel *)model;
  414. if (multInputModel.key && multInputModel.value.length > 0) {
  415. [params setObject:multInputModel.value forKey:multInputModel.key];
  416. }
  417. }
  418. break;
  419. case RAEditTypePhoto: {
  420. if (photoDir) {
  421. RAEditPhotoModel *photoModel = (RAEditPhotoModel *)model;
  422. if (photoModel.photo) {
  423. NSString *photoPath = [photoDir stringByAppendingPathComponent:photoModel.photoName];
  424. NSData *imgData = UIImageJPEGRepresentation(photoModel.photo, 1.0f);
  425. if (imgData) {
  426. [imgData writeToFile:photoPath atomically:NO];
  427. [params setObject:photoModel.photoName forKey:photoModel.key];
  428. [photoArr addObject:photoModel];
  429. }
  430. }
  431. }
  432. }
  433. break;
  434. default:
  435. break;
  436. }
  437. }
  438. }
  439. return photoArr;
  440. }
  441. - (NSMutableDictionary *)preparePackage {
  442. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  443. NSInteger photoCount = [self prepareParams:params].count;
  444. NSString *photoDir = [self photoDir];
  445. NSMutableDictionary *task = [@{
  446. @"order" : self.orderID,
  447. @"action" : self.actionTitle,
  448. @"url" : URL_HOST,
  449. @"noFile" : @(YES)
  450. } mutableCopy];
  451. if (photoCount > 0) {
  452. // 压缩文件
  453. NSString *zipPath = [photoDir stringByAppendingPathExtension:@".zip"];
  454. ZipArchive *zip = [[ZipArchive alloc] init];
  455. [zip CreateZipFile2:zipPath];
  456. NSArray *subPaths = [[NSFileManager defaultManager] subpathsAtPath:photoDir];
  457. for (NSString *subPath in subPaths) {
  458. NSString *fullPath = [photoDir stringByAppendingPathComponent:subPath];
  459. BOOL isDir;
  460. if([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir]) {
  461. if (!isDir) {
  462. [zip addFileToZip:fullPath newname:subPath];
  463. }
  464. }
  465. }
  466. [zip CloseZipFile2];
  467. [[NSFileManager defaultManager] removeItemAtPath:photoDir error:nil];
  468. NSString *md5 = [RAUtils md5WithFile:zipPath];
  469. [params setObject:md5 forKey:@"md5"];
  470. [task setObject:@"file" forKey:zipPath.lastPathComponent];
  471. }
  472. [task setObject:params forKey:@"params"];
  473. return task;
  474. }
  475. @end