RAOrderEditViewController.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. }
  164. if (weakSelf) {
  165. __strong typeof(weakSelf) strongSelf = weakSelf;
  166. int result = [[json objectForKey:@"result"] intValue];
  167. if (result == RESULT_TRUE) {
  168. NSArray *sectionArray = [json objectForKey:@"sections"];
  169. [strongSelf.sectionArray removeAllObjects];
  170. for (int i = 0; i < sectionArray.count; i++) {
  171. NSDictionary *section = [sectionArray objectAtIndex:i];
  172. RAEditSectionModel *model = [RAEditSectionModel new];
  173. [model setValuesForKeysWithDictionary:section];
  174. [strongSelf.sectionArray addObject:model];
  175. }
  176. [strongSelf.orderEditTableView reloadData];
  177. } else {
  178. // process error
  179. NSString *msg = [json objectForKey:@"err_msg"];
  180. [strongSelf showAlertTilte:@"Warning" message:msg];
  181. }
  182. }
  183. });
  184. });
  185. }
  186. #pragma mark - Tap Action
  187. - (IBAction)tapToResignFirstResponder:(UITapGestureRecognizer *)sender {
  188. [self.view endEditing:YES];
  189. }
  190. - (void)updateBtnClick:(UIBarButtonItem *)sender {
  191. // show progress
  192. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  193. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  194. NSMutableArray <RAEditPhotoModel *> *photoArr = [self prepareParams:params];
  195. __weak typeof(self) weakSelf = self;
  196. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  197. NSDictionary *json = [RADataProvider submitEditOrder:params];
  198. if (weakSelf) {
  199. __strong typeof(weakSelf) strongSelf = weakSelf;
  200. int result = [[json objectForKey:@"result"] intValue];
  201. if (result == RESULT_TRUE) {
  202. dispatch_async(dispatch_get_main_queue(), ^{
  203. BOOL requiredLocation = [[json objectForKey:@"requiredLocation"] boolValue];
  204. [RASingleton sharedInstance].requiredLocation = requiredLocation;
  205. });
  206. if (photoArr.count > 0) {
  207. [strongSelf syncUploadPhotos:photoArr Json:json HUD:hud];
  208. } else {
  209. [self gobackHome];
  210. }
  211. } else {
  212. // process error
  213. dispatch_async(dispatch_get_main_queue(), ^{
  214. // dismiss progress
  215. [hud dismiss:^{
  216. NSString *msg = [json objectForKey:@"err_msg"];
  217. [strongSelf showAlertTilte:@"Warning" message:msg];
  218. }];
  219. });
  220. }
  221. }
  222. });
  223. }
  224. - (void)backgroundUploadPhoto:(NSArray *)photos Json:(NSDictionary *)json {
  225. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  226. NSDate *date = [NSDate date];
  227. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  228. formatter.dateFormat = @"MM/dd/YYYY HH:mm";
  229. NSString *time = [formatter stringFromDate:date];
  230. for (RAEditPhotoModel *model in photos) {
  231. NSString *serial = [json objectForKey:model.key];
  232. if (serial.length) {
  233. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  234. [params setObject:serial forKey:@"serial"];
  235. [params setObject:@"iOS" forKey:@"platform"];
  236. NSString *photoPath = [self.photoDir.lastPathComponent stringByAppendingPathComponent:model.photoName];
  237. NSMutableDictionary *task = [@{
  238. @"order" : self.orderID,
  239. @"action" : self.actionTitle,
  240. @"name" : model.title,
  241. @"time" : time,
  242. @"url" : URL_HOST,
  243. @"file" : photoPath,
  244. @"params" : params
  245. } mutableCopy];
  246. [appDelegate.uploadManager addTask:task];
  247. }
  248. }
  249. }
  250. - (void)syncUploadPhotos:(NSMutableArray *)photoArr Json:(NSDictionary *)json HUD:(RAProgressHUD *)hud {
  251. dispatch_async(dispatch_get_main_queue(), ^{
  252. RAProgressHUD *innerHUD = hud;
  253. if (!innerHUD) {
  254. innerHUD = [RAProgressHUD showHUDOnView:self.view]; // main queue
  255. }
  256. dispatch_async(dispatch_get_global_queue(0, 0), ^{ // network
  257. int retryCount = 0;
  258. NSMutableArray *completArr = [NSMutableArray array];
  259. // 同步上传照片
  260. for (int i = 0; i < photoArr.count; i++) {
  261. RAEditPhotoModel *model = [photoArr objectAtIndex:i];
  262. NSString *serial = [json objectForKey:model.key];
  263. if (serial.length) {
  264. NSMutableDictionary *fileParams = [NSMutableDictionary dictionary];
  265. [fileParams setObject:serial forKey:@"serial"];
  266. NSString *photoPath = [self.photoDir stringByAppendingPathComponent:model.photoName];
  267. NSDictionary *uploadJson = [RADataProvider uploadFile:photoPath parameters:fileParams];
  268. int uploadResult = [[uploadJson objectForKey:@"result"] intValue];
  269. if (uploadResult != RESULT_TRUE) { // 失败重试
  270. i--;
  271. retryCount++;
  272. if (retryCount >= 3) {
  273. break;
  274. }
  275. } else {
  276. [completArr addObject:model];
  277. retryCount = 0;
  278. // 删除文件
  279. if ([[NSFileManager defaultManager] fileExistsAtPath:photoPath]) {
  280. [[NSFileManager defaultManager] removeItemAtPath:photoPath error:nil];
  281. }
  282. }
  283. } // serial
  284. } // for
  285. // 将完成的model移除
  286. [photoArr removeObjectsInArray:completArr];
  287. __weak typeof(self) weakSelf = self;
  288. dispatch_async(dispatch_get_main_queue(), ^{
  289. [innerHUD dismiss:^{
  290. if (photoArr.count > 0) {
  291. // 上传失败,询问是否丢到后台线程上传,否则重启上传
  292. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:@"upload the photos failed,would you like to retry or do it background?" preferredStyle:UIAlertControllerStyleAlert];
  293. UIAlertAction *backgroundAction = [UIAlertAction actionWithTitle:@"Background" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  294. // 开启后台上传
  295. [weakSelf backgroundUploadPhoto:photoArr Json:json];
  296. // 返回首页
  297. [weakSelf gobackHome];
  298. }];
  299. UIAlertAction *retryAction = [UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  300. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  301. [weakSelf syncUploadPhotos:photoArr Json:json HUD:nil];
  302. });
  303. }];
  304. [alertVC addAction:backgroundAction];
  305. [alertVC addAction:retryAction];
  306. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  307. } else {
  308. // 上传完成,返回到首页
  309. [weakSelf gobackHome];
  310. }
  311. }];
  312. });
  313. });
  314. });
  315. }
  316. - (void)gobackHome {
  317. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationReloadHome object:nil];
  318. [self.navigationController popToRootViewControllerAnimated:YES];
  319. }
  320. #pragma mark - Keyboard Listener
  321. - (void)keyboardWillChangeFrame:(NSNotification *)notification {
  322. CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  323. CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
  324. CGFloat keyboardHeight = screenHeight - CGRectGetMinY(end);
  325. UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
  326. self.orderEditTableView.contentInset = insets;
  327. if (self.editingIndexPath) {
  328. [self.orderEditTableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  329. }
  330. }
  331. #pragma mark - Package Update Data
  332. - (NSString *)photoDir {
  333. if (!_photoDir) {
  334. NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  335. NSString *photoDir = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld_%@",self.orderID,(long)self.actionID,[NSUUID UUID].UUIDString]];
  336. NSError *error;
  337. // BOOL dirExist = YES;
  338. // for (int i = 0; i < INT_MAX; i++) {
  339. // if (i != 0) {
  340. // photoDir = [photoDir stringByAppendingString:[NSString stringWithFormat:@"(%d)",i]];
  341. // }
  342. // if (![[NSFileManager defaultManager] fileExistsAtPath:photoDir]) {
  343. // dirExist = NO;
  344. // break;
  345. // }
  346. // }
  347. [[NSFileManager defaultManager] createDirectoryAtPath:photoDir withIntermediateDirectories:YES attributes:nil error:&error];
  348. if (error) {
  349. NSLog(@"create dir %@ failed %@",photoDir,error.localizedDescription);
  350. return nil;
  351. }
  352. _photoDir = photoDir;
  353. }
  354. return _photoDir;
  355. }
  356. - (NSMutableArray <RAEditPhotoModel *> *)prepareParams:(NSMutableDictionary *)params {
  357. if (params == nil) {
  358. return nil;
  359. }
  360. NSMutableArray <RAEditPhotoModel *> *photoArr = [NSMutableArray array];
  361. NSString *photoDir = [self photoDir];
  362. [params setObject:self.orderID forKey:@"orderID"];
  363. [params setObject:@(self.actionID) forKey:@"actionID"];
  364. NSString* encryptu = [RASingleton sharedInstance].encryptUser;
  365. NSString* encryptp = [RASingleton sharedInstance].encryptPassword;
  366. [params setObject:encryptu forKey:@"user"];
  367. [params setObject:encryptp forKey:@"password"];
  368. [params setObject:@"iOS" forKey:@"platform"];
  369. if ([RASingleton sharedInstance].currentLocation) {
  370. [params setObject:[NSString stringWithFormat:@"%f,%f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude] forKey:@"location"];
  371. }
  372. for (RAEditSectionModel *section in self.sectionArray) {
  373. for (int i = 0; i < [section itemCount]; i++) {
  374. RAEditBaseModel *model = [section itemModelForIndex:i];
  375. switch (model.type) {
  376. case RAEditTypeLabel: {
  377. }
  378. break;
  379. case RAEditTypeInput: {
  380. RAEditInputModel *inputModel = (RAEditInputModel *)model;
  381. if (inputModel.key && inputModel.value.length > 0) {
  382. [params setObject:inputModel.value forKey:inputModel.key];
  383. }
  384. }
  385. break;
  386. case RAEditTypeMultInput: {
  387. RAEditMultInputModel *multInputModel = (RAEditMultInputModel *)model;
  388. if (multInputModel.key && multInputModel.value.length > 0) {
  389. [params setObject:multInputModel.value forKey:multInputModel.key];
  390. }
  391. }
  392. break;
  393. case RAEditTypePhoto: {
  394. if (photoDir) {
  395. RAEditPhotoModel *photoModel = (RAEditPhotoModel *)model;
  396. if (photoModel.photo) {
  397. NSString *photoPath = [photoDir stringByAppendingPathComponent:photoModel.photoName];
  398. NSData *imgData = UIImageJPEGRepresentation(photoModel.photo, 1.0f);
  399. if (imgData) {
  400. [imgData writeToFile:photoPath atomically:NO];
  401. [params setObject:photoModel.photoName forKey:photoModel.key];
  402. [photoArr addObject:photoModel];
  403. }
  404. }
  405. }
  406. }
  407. break;
  408. default:
  409. break;
  410. }
  411. }
  412. }
  413. return photoArr;
  414. }
  415. - (NSMutableDictionary *)preparePackage {
  416. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  417. NSInteger photoCount = [self prepareParams:params].count;
  418. NSString *photoDir = [self photoDir];
  419. NSMutableDictionary *task = [@{
  420. @"order" : self.orderID,
  421. @"action" : self.actionTitle,
  422. @"url" : URL_HOST,
  423. @"noFile" : @(YES)
  424. } mutableCopy];
  425. if (photoCount > 0) {
  426. // 压缩文件
  427. NSString *zipPath = [photoDir stringByAppendingPathExtension:@".zip"];
  428. ZipArchive *zip = [[ZipArchive alloc] init];
  429. [zip CreateZipFile2:zipPath];
  430. NSArray *subPaths = [[NSFileManager defaultManager] subpathsAtPath:photoDir];
  431. for (NSString *subPath in subPaths) {
  432. NSString *fullPath = [photoDir stringByAppendingPathComponent:subPath];
  433. BOOL isDir;
  434. if([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir]) {
  435. if (!isDir) {
  436. [zip addFileToZip:fullPath newname:subPath];
  437. }
  438. }
  439. }
  440. [zip CloseZipFile2];
  441. [[NSFileManager defaultManager] removeItemAtPath:photoDir error:nil];
  442. NSString *md5 = [RAUtils md5WithFile:zipPath];
  443. [params setObject:md5 forKey:@"md5"];
  444. [task setObject:@"file" forKey:zipPath.lastPathComponent];
  445. }
  446. [task setObject:params forKey:@"params"];
  447. return task;
  448. }
  449. @end