RAOrderEditViewController.m 22 KB

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