RAOrderEditViewController.m 22 KB

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