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