RAOrderEditViewController.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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 "RAEditImageBaseModel.h"
  13. #import "RAEditPhotoModel.h"
  14. #import "RAEditSignatureModel.h"
  15. #import "RAEditDateModel.h"
  16. #import "RAEditMultPhotoModel.h"
  17. #import "RAProgressHUD.h"
  18. #import "AppDelegate.h"
  19. #import "UIScrollView+Empty.h"
  20. #import "RAEmptyView.h"
  21. #import "RAEditRequiredAlert.h"
  22. #import <CoreLocation/CoreLocation.h>
  23. #import "RAPhotoCell.h"
  24. @interface RAEditSectionModel : NSObject
  25. @property (nonatomic,strong) NSArray <RAEditBaseModel *> *items;
  26. @property (nonatomic,copy) NSString *title;
  27. @end
  28. @implementation RAEditSectionModel
  29. - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
  30. }
  31. - (void)setItems:(NSArray<RAEditBaseModel *> *)items {
  32. NSMutableArray *tmpItems = [items mutableCopy];
  33. // [tmpItems addObject:@{
  34. // @"type" : @6,
  35. // @"title" : @"Container Photo",
  36. // @"required" : @(YES),
  37. // @"photos" : @[@{@"placeHolder":@"btn_add_photo"},@{@"placeHolder":@"btn_add_photo"},@{@"placeHolder":@"btn_add_photo"},@{@"placeHolder":@"btn_add_photo"},@{@"placeHolder":@"btn_add_photo"},@{@"placeHolder":@"btn_add_photo"}],
  38. // @"key" : @"test_photo"
  39. // }];
  40. NSMutableArray *itemArr = [NSMutableArray arrayWithCapacity:items.count];
  41. for (int i = 0; i < tmpItems.count; i++) {
  42. NSDictionary *item = [tmpItems objectAtIndex:i];
  43. RAEditBaseModel *model = [self createModelWithJsonItem:item];
  44. if (model) {
  45. [itemArr addObject:model];
  46. // expand 直接放出来
  47. if (model.expand && [model.expand isKindOfClass:[NSDictionary class]]) {
  48. RAEditBaseModel *expand = [self createModelWithJsonItem:model.expand];
  49. if (expand) {
  50. model.expand = expand;
  51. [itemArr addObject:expand];
  52. }
  53. }
  54. }
  55. }
  56. _items = itemArr;
  57. }
  58. - (NSInteger)itemCount {
  59. return self.items.count;
  60. }
  61. - (RAEditBaseModel *)itemModelForIndex:(NSInteger)index {
  62. return [self.items objectAtIndex:index];
  63. }
  64. - (RAEditBaseModel *)createModelWithJsonItem:(NSDictionary *)item {
  65. RAEditType type = [[item objectForKey:@"type"] intValue];
  66. RAEditBaseModel *model;
  67. switch (type) {
  68. case RAEditTypeLabel: {
  69. model = [RAEditLabelModel new];
  70. }
  71. break;
  72. case RAEditTypeInput: {
  73. model = [RAEditInputModel new];
  74. }
  75. break;
  76. case RAEditTypeMultInput: {
  77. model = [RAEditMultInputModel new];
  78. }
  79. break;
  80. case RAEditTypePhoto: {
  81. model = [RAEditPhotoModel new];
  82. }
  83. break;
  84. case RAEditTypeSignature: {
  85. model = [RAEditSignatureModel new];
  86. }
  87. break;
  88. case RAEditTypeDate: {
  89. model = [RAEditDateModel new];
  90. }
  91. break;
  92. case RAEditTypeMultPhoto: {
  93. RAEditMultPhotoModel *photoModel = [RAEditMultPhotoModel new];
  94. photoModel.width = [UIScreen mainScreen].bounds.size.width;
  95. model = photoModel;
  96. }
  97. break;
  98. default: {
  99. model = nil;
  100. }
  101. break;
  102. }
  103. [model setValuesForKeysWithDictionary:item];
  104. return model;
  105. }
  106. - (RAEditBaseModel *)addModelAtIndex:(NSUInteger)idx withJsonItem:(NSDictionary *)item {
  107. RAEditBaseModel *model = [self createModelWithJsonItem:item];
  108. if (model) {
  109. NSMutableArray *arr = [self.items mutableCopy];
  110. [arr insertObject:model atIndex:idx];
  111. _items = arr;
  112. }
  113. return model;
  114. }
  115. @end
  116. #pragma mark - View Controller
  117. @interface RAOrderEditViewController ()
  118. @property (nonatomic,strong) IBOutlet UITableView *orderEditTableView;
  119. @property (nonatomic,strong) NSMutableArray *sectionArray;
  120. @property (nonatomic,copy) NSString *photoDir;
  121. @property (nonatomic,strong) UIRefreshControl *refreshControl;
  122. @property (nonatomic,strong) UIBarButtonItem *updateItem;
  123. @end
  124. @implementation RAOrderEditViewController
  125. + (instancetype)viewControllerFromStoryboard {
  126. RAOrderEditViewController *editVC = [[UIStoryboard storyboardWithName:@"Edit" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  127. return editVC;
  128. }
  129. - (void)viewDidLoad {
  130. [super viewDidLoad];
  131. // Do any additional setup after loading the view.
  132. self.label_cache.text = NSLocalizedString(@"cache content", nil);
  133. [self.label_cache sizeToFit];
  134. self.label_cache.layer.borderColor=ApexDriverGrayColor.CGColor;
  135. self.label_cache.layer.borderWidth = 1.0f;
  136. self.label_cache.layer.cornerRadius = 5.0f;
  137. self.label_cache.layer.masksToBounds = YES;
  138. [self configureTable];
  139. [self configureNavigationBar];
  140. [self loadData];
  141. }
  142. - (void)viewWillAppear:(BOOL)animated {
  143. [super viewWillAppear:animated];
  144. [self registKeyboardListener];
  145. }
  146. - (void)viewWillDisappear:(BOOL)animated {
  147. [super viewWillDisappear:animated];
  148. [self unregistKeyboardListener];
  149. }
  150. - (void)didReceiveMemoryWarning {
  151. [super didReceiveMemoryWarning];
  152. // Dispose of any resources that can be recreated.
  153. }
  154. #pragma mark - Configure
  155. - (void)configureTable {
  156. if (@available(iOS 11.0, *)) {
  157. self.orderEditTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  158. }
  159. // else {
  160. // self.automaticallyAdjustsScrollViewInsets = NO;
  161. // }
  162. self.orderEditTableView.tableFooterView = [UIView new];
  163. self.orderEditTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
  164. UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
  165. [refresh addTarget:self action:@selector(refreshControlValueChanged:) forControlEvents:UIControlEventValueChanged];
  166. [self.orderEditTableView addSubview:refresh];
  167. self.refreshControl = refresh;
  168. // empty
  169. __weak typeof(self) weakSelf = self;
  170. self.orderEditTableView.emptyView = [RAEmptyView emptyViewWithTapBlk:^(id sender) {
  171. [weakSelf loadData];
  172. }];
  173. [RAPhotoCell regist2TableView:self.orderEditTableView];
  174. }
  175. - (void)configureNavigationBar {
  176. UIBarButtonItem *updateItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Update", nil) style:UIBarButtonItemStylePlain target:self action:@selector(updateBtnClick:)];
  177. self.updateItem = updateItem;
  178. }
  179. - (void)registKeyboardListener {
  180. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
  181. }
  182. - (void)unregistKeyboardListener {
  183. [[NSNotificationCenter defaultCenter] removeObserver:self];
  184. }
  185. #pragma mark - Action
  186. - (void)refreshControlValueChanged:(UIRefreshControl *)refresh {
  187. self.label_cache.hidden=true;
  188. [self loadData];
  189. }
  190. #pragma mark - Getter
  191. - (UITableView *)tableView {
  192. return self.orderEditTableView;
  193. }
  194. - (NSMutableArray *)sectionArray {
  195. if (!_sectionArray) {
  196. _sectionArray = [NSMutableArray array];
  197. }
  198. return _sectionArray;
  199. }
  200. - (NSUInteger)editSectionCount {
  201. return self.sectionArray.count;
  202. }
  203. - (NSInteger)itemCountForSection:(NSInteger)section {
  204. return [[self.sectionArray objectAtIndex:section] itemCount];
  205. }
  206. - (RAEditBaseModel *)modelForIndexPath:(NSIndexPath *)indexPath {
  207. return [[self.sectionArray objectAtIndex:indexPath.section] itemModelForIndex:indexPath.row];
  208. }
  209. - (NSString *)titleForSection:(NSInteger)section {
  210. return [[self.sectionArray objectAtIndex:section] title];
  211. }
  212. - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell {
  213. return [self.orderEditTableView indexPathForCell:cell];
  214. }
  215. #pragma mark - Setter
  216. - (void)setUpdateItem:(UIBarButtonItem *)updateItem {
  217. _updateItem = updateItem;
  218. self.navigationItem.rightBarButtonItem = updateItem;
  219. }
  220. - (void)addModelAtIndex:(NSIndexPath *)indexPath withJsonItem:(NSDictionary *)item {
  221. RAEditSectionModel *section = [self.sectionArray objectAtIndex:indexPath.section];
  222. [section addModelAtIndex:indexPath.row withJsonItem:item];
  223. [self.orderEditTableView reloadData];
  224. }
  225. - (void)expandIndexPath:(NSIndexPath *)indexPath withJsonItem:(NSDictionary *)item {
  226. RAEditSectionModel *section = [self.sectionArray objectAtIndex:indexPath.section];
  227. RAEditBaseModel *curM = [self modelForIndexPath:indexPath];
  228. RAEditBaseModel *expand = [section addModelAtIndex:(indexPath.row + 1) withJsonItem:item];
  229. curM.expand = expand;
  230. [self.orderEditTableView reloadData];
  231. }
  232. #pragma mark - Data
  233. - (void)loadData {
  234. if (self.loading) {
  235. return;
  236. }
  237. self.loading = YES;
  238. [self.orderEditTableView hideEmpty];
  239. // show progress
  240. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  241. NSString *orderID = self.orderID;
  242. NSInteger actionID = self.actionID;
  243. NSInteger actionIdx = self.actionIdx;
  244. __weak typeof(self) weakSelf = self;
  245. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  246. NSDictionary *json = [RADataProvider requestUpdateOrder:orderID driverAction:actionID index:actionIdx];
  247. dispatch_async(dispatch_get_main_queue(), ^{
  248. // dismiss progress
  249. [hud dismiss];
  250. if (weakSelf.refreshControl.isRefreshing) {
  251. [weakSelf.refreshControl endRefreshing];
  252. }
  253. if (weakSelf) {
  254. __strong typeof(weakSelf) strongSelf = weakSelf;
  255. int result = [[json objectForKey:@"result"] intValue];
  256. if (result == RESULT_TRUE) {
  257. NSArray *sectionArray = [json objectForKey:@"sections"];
  258. [strongSelf.sectionArray removeAllObjects];
  259. for (int i = 0; i < sectionArray.count; i++) {
  260. NSDictionary *section = [sectionArray objectAtIndex:i];
  261. RAEditSectionModel *model = [RAEditSectionModel new];
  262. [model setValuesForKeysWithDictionary:section];
  263. [strongSelf.sectionArray addObject:model];
  264. }
  265. if([json[@"iscache"] boolValue]==true)
  266. {
  267. self.label_cache.hidden=false;
  268. }
  269. [strongSelf.orderEditTableView reloadData];
  270. } else {
  271. [strongSelf.sectionArray removeAllObjects];
  272. strongSelf.orderEditTableView.contentOffset = CGPointZero;
  273. [strongSelf.orderEditTableView reloadData];
  274. // process error
  275. NSString *msg = [json objectForKey:@"err_msg"];
  276. // [strongSelf showAlert:msg];
  277. [strongSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg];
  278. }
  279. }
  280. weakSelf.loading = NO;
  281. if (weakSelf.editSectionCount == 0) {
  282. [weakSelf.orderEditTableView showEmpty];
  283. } else {
  284. [weakSelf.orderEditTableView hideEmpty];
  285. }
  286. });
  287. });
  288. }
  289. #pragma mark - Private
  290. - (void)submitSuccessWithMsg:(NSString *)msg {
  291. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
  292. __weak typeof(self) weakSelf = self;
  293. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ok", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  294. if (weakSelf) {
  295. __strong typeof(weakSelf) strongSelf = weakSelf;
  296. [strongSelf gobackHome];
  297. }
  298. }];
  299. [alertVC addAction:okAction];
  300. [self presentViewController:alertVC animated:YES completion:nil];
  301. }
  302. - (void)submitSuccessWithPhoto:(BOOL)photo {
  303. NSString *msg = NSLocalizedString(@"update_success", nil);
  304. if (photo) {
  305. msg = NSLocalizedString(@"update_photo_success", nil);
  306. }
  307. [self submitSuccessWithMsg:msg];
  308. }
  309. #pragma mark - Tap Action
  310. - (IBAction)tapToResignFirstResponder:(UITapGestureRecognizer *)sender {
  311. [self.view endEditing:YES];
  312. }
  313. - (void)updateBtnClick:(UIBarButtonItem *)sender {
  314. self.updateItem.enabled = NO; // 失败返回时重新开启enable
  315. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  316. if (self.orderType2) {
  317. [params setObject:self.orderType2 forKey:@"orderType2"];
  318. }
  319. CLAuthorizationStatus locationAuthoriztionAstatus = [CLLocationManager authorizationStatus];
  320. if (/*RASingleton.sharedInstance.requiredBackgroundLocation*/locationAuthoriztionAstatus != kCLAuthorizationStatusDenied)
  321. {
  322. CLLocation *location = RASingleton.sharedInstance.currentLocation;
  323. NSString *latLon = nil;
  324. if (location) {
  325. latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
  326. [params setObject:@(location.speed) forKey:@"speed"];
  327. [params setObject:@([location.timestamp timeIntervalSince1970]) forKey:@"timestamp"];
  328. } else {
  329. latLon = @"-999,-999";
  330. }
  331. [params setObject:latLon forKey:@"location"];
  332. [params setObject:@false forKey:@"user_reject"];
  333. }
  334. else
  335. {
  336. [params setObject:@true forKey:@"user_reject"];
  337. [params setObject:@"Location Denied by app setting" forKey:@"reason"];
  338. }
  339. NSMutableArray *emptyArr = [NSMutableArray array];
  340. NSMutableArray <RAEditImageBaseModel *> *photoArr = [self prepareParams:params checkRequired:emptyArr];
  341. if (emptyArr.count > 0) {
  342. RAEditRequiredAlert *alertVC = [RAEditRequiredAlert alertWithTile:NSLocalizedString(@"Warning", nil) message:[NSString localizedStringWithFormat:NSLocalizedString(@"please complete missing field:\n%@", nil),[emptyArr componentsJoinedByString:@"\n"]]];
  343. [self presentViewController:alertVC animated:YES completion:nil];
  344. self.updateItem.enabled = YES;
  345. return;
  346. }
  347. [params setValue:@(photoArr.count) forKey:@"photoCount"];
  348. // show progress
  349. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  350. __weak typeof(self) weakSelf = self;
  351. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  352. if (RASingleton.sharedInstance.offline) { // 离线
  353. NSDictionary *json = [weakSelf offlineUpdate:params photos:photoArr];
  354. dispatch_async(dispatch_get_main_queue(), ^{
  355. [hud dismiss:^{
  356. int result = [[json objectForKey:@"result"] intValue];
  357. NSString *msg = NSLocalizedString(@"sorry", nil);
  358. if (result == RESULT_TRUE) {
  359. msg = NSLocalizedString(@"offline_update_success", nil);
  360. [weakSelf submitSuccessWithMsg:msg];
  361. } else {
  362. msg = [json objectForKey:@"err_msg"];
  363. if (msg == nil) {
  364. msg = NSLocalizedString(@"sorry", nil);
  365. }
  366. [weakSelf showAlert:msg];
  367. weakSelf.updateItem.enabled = YES;
  368. }
  369. }];
  370. });
  371. }
  372. else { // 在线
  373. NSDictionary *json = [RADataProvider submitEditOrder:weakSelf.orderID actionIndex:weakSelf.actionIdx withParams:params];
  374. if (weakSelf) {
  375. __strong typeof(weakSelf) strongSelf = weakSelf;
  376. int result = [[json objectForKey:@"result"] intValue];
  377. if (result == RESULT_TRUE) {
  378. BOOL requiredLocation = [[json objectForKey:@"requiredLocation"] boolValue];
  379. [RASingleton sharedInstance].requiredBackgroundLocation = requiredLocation;
  380. dispatch_async(dispatch_get_main_queue(), ^{
  381. // if (photoArr.count > 0) {
  382. // [strongSelf syncUploadPhotos:photoArr Json:json HUD:hud];
  383. // } else {
  384. // [strongSelf gobackHome];
  385. // }
  386. // 全部转为后台上传
  387. if (photoArr.count > 0) {
  388. [strongSelf backgroundUploadPhoto:photoArr Json:json];
  389. }
  390. [hud dismiss:^{
  391. [strongSelf submitSuccessWithPhoto:photoArr.count > 0];
  392. }];
  393. });
  394. } else {
  395. // process error
  396. dispatch_async(dispatch_get_main_queue(), ^{
  397. // dismiss progress
  398. [hud dismiss:^{
  399. NSString *msg = [json objectForKey:@"err_msg"];
  400. [strongSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg];
  401. strongSelf.updateItem.enabled = YES;
  402. }];
  403. });
  404. }
  405. }
  406. }
  407. });
  408. }
  409. - (void)backgroundUploadPhoto:(NSArray<RAEditImageBaseModel *> *)photos Json:(NSDictionary *)json {
  410. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  411. NSDate *date = [NSDate date];
  412. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  413. formatter.dateFormat = @"MM/dd/YYYY HH:mm";
  414. NSString *time = [formatter stringFromDate:date];
  415. NSString *serial = [json objectForKey:@"serial"];
  416. for (RAEditImageBaseModel *model in photos) {
  417. if (serial.length) {
  418. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  419. [params setObject:serial forKey:@"serial"];
  420. if (self.orderType2) {
  421. [params setObject:self.orderType2 forKey:@"orderType2"];
  422. }
  423. if (model.key) {
  424. [params setObject:model.key forKey:@"key"];
  425. }
  426. [params setObject:@(model.type) forKey:@"type"];
  427. [params setObject:[RASingleton.sharedInstance encryptUser] forKey:@"name"];
  428. [params setObject:[RASingleton.sharedInstance encryptPassword] forKey:@"password"];
  429. [params setObject:@"iOS" forKey:@"platform"];
  430. NSString *photoPath = [self.photoDir.lastPathComponent stringByAppendingPathComponent:model.imageName];
  431. NSMutableDictionary *task = [@{
  432. @"order" : self.orderID,
  433. @"action" : self.actionTitle,
  434. @"name" : model.title,
  435. @"time" : time,
  436. @"url" : URL_UPLOAD,
  437. @"file" : photoPath,
  438. @"params" : params
  439. } mutableCopy];
  440. [appDelegate.uploadManager addTask:task];
  441. }
  442. }
  443. }
  444. - (void)syncUploadPhotos:(NSMutableArray<RAEditImageBaseModel *> *)photoArr Json:(NSDictionary *)json HUD:(RAProgressHUD *)hud {
  445. dispatch_async(dispatch_get_main_queue(), ^{
  446. RAProgressHUD *innerHUD = hud;
  447. if (!innerHUD) {
  448. innerHUD = [RAProgressHUD showHUDOnView:self.view]; // main queue
  449. }
  450. dispatch_async(dispatch_get_global_queue(0, 0), ^{ // network
  451. int retryCount = 0;
  452. NSMutableArray *completArr = [NSMutableArray array];
  453. NSString *serial = [json objectForKey:@"serial"];
  454. // 同步上传照片
  455. for (int i = 0; i < photoArr.count; i++) {
  456. RAEditImageBaseModel *model = [photoArr objectAtIndex:i];
  457. if (serial.length) {
  458. NSMutableDictionary *fileParams = [NSMutableDictionary dictionary];
  459. [fileParams setObject:serial forKey:@"serial"];
  460. if (self.orderType2) {
  461. [fileParams setObject:self.orderType2 forKey:@"orderType2"];
  462. }
  463. if (model.key) {
  464. [fileParams setObject:model.key forKey:@"key"];
  465. }
  466. [fileParams setObject:@(model.type) forKey:@"type"];
  467. NSString *photoPath = [self.photoDir stringByAppendingPathComponent:model.imageName];
  468. NSDictionary *uploadJson = [RADataProvider uploadFile:photoPath parameters:fileParams];
  469. int uploadResult = [[uploadJson objectForKey:@"result"] intValue];
  470. if (uploadResult != RESULT_TRUE) { // 失败重试
  471. i--;
  472. retryCount++;
  473. if (retryCount >= 3) {
  474. break;
  475. }
  476. } else {
  477. [completArr addObject:model];
  478. retryCount = 0;
  479. // 删除文件
  480. if ([[NSFileManager defaultManager] fileExistsAtPath:photoPath]) {
  481. [[NSFileManager defaultManager] removeItemAtPath:photoPath error:nil];
  482. }
  483. }
  484. } // serial
  485. } // for
  486. // 将完成的model移除
  487. [photoArr removeObjectsInArray:completArr];
  488. __weak typeof(self) weakSelf = self;
  489. dispatch_async(dispatch_get_main_queue(), ^{
  490. [innerHUD dismiss:^{
  491. if (photoArr.count > 0) {
  492. // 上传失败,询问是否丢到后台线程上传,否则重启上传
  493. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"update_upload_failed_tips", nil) preferredStyle:UIAlertControllerStyleAlert];
  494. UIAlertAction *backgroundAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Background", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  495. // 开启后台上传
  496. [weakSelf backgroundUploadPhoto:photoArr Json:json];
  497. // 返回首页
  498. [weakSelf gobackHome];
  499. }];
  500. UIAlertAction *retryAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Retry", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  501. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  502. [weakSelf syncUploadPhotos:photoArr Json:json HUD:nil];
  503. });
  504. }];
  505. [alertVC addAction:backgroundAction];
  506. [alertVC addAction:retryAction];
  507. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  508. } else {
  509. // 上传完成,返回到首页
  510. [weakSelf gobackHome];
  511. }
  512. }];
  513. });
  514. });
  515. });
  516. }
  517. - (void)gobackHome {
  518. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationReloadHome object:nil];
  519. [self.navigationController popToRootViewControllerAnimated:YES];
  520. }
  521. #pragma mark - Keyboard Listener
  522. - (void)keyboardWillChangeFrame:(NSNotification *)notification {
  523. CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  524. CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
  525. CGFloat keyboardHeight = screenHeight - CGRectGetMinY(end);
  526. UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
  527. self.orderEditTableView.contentInset = insets;
  528. if (self.editingIndexPath) {
  529. [self.orderEditTableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  530. }
  531. }
  532. #pragma mark - Package Update Data
  533. - (NSString *)photoDir {
  534. if (!_photoDir) {
  535. NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  536. NSString *photoDir = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld_%@",self.orderID,(long)self.actionID,[NSUUID UUID].UUIDString]];
  537. NSError *error;
  538. // BOOL dirExist = YES;
  539. // for (int i = 0; i < INT_MAX; i++) {
  540. // if (i != 0) {
  541. // photoDir = [photoDir stringByAppendingString:[NSString stringWithFormat:@"(%d)",i]];
  542. // }
  543. // if (![[NSFileManager defaultManager] fileExistsAtPath:photoDir]) {
  544. // dirExist = NO;
  545. // break;
  546. // }
  547. // }
  548. [[NSFileManager defaultManager] createDirectoryAtPath:photoDir withIntermediateDirectories:YES attributes:nil error:&error];
  549. if (error) {
  550. NSLog(@"create dir %@ failed %@",photoDir,error.localizedDescription);
  551. return nil;
  552. }
  553. _photoDir = photoDir;
  554. }
  555. return _photoDir;
  556. }
  557. - (NSMutableArray <RAEditImageBaseModel *> *)prepareParams:(NSMutableDictionary *)params checkRequired:(NSMutableArray *)emptyArr {
  558. if (params == nil) {
  559. return nil;;
  560. }
  561. NSMutableArray <RAEditImageBaseModel *> *photoArr = [NSMutableArray array];
  562. NSString *photoDir = [self photoDir];
  563. [params setObject:self.orderID forKey:@"orderID"];
  564. [params setObject:@(self.actionID) forKey:@"actionID"];
  565. NSString* encryptu = [RASingleton sharedInstance].encryptUser;
  566. NSString* encryptp = [RASingleton sharedInstance].encryptPassword;
  567. [params setObject:encryptu forKey:@"name"];
  568. [params setObject:encryptp forKey:@"password"];
  569. [params setObject:@"iOS" forKey:@"platform"];
  570. for (RAEditSectionModel *section in self.sectionArray) {
  571. for (int i = 0; i < [section itemCount]; i++) {
  572. RAEditBaseModel *model = [section itemModelForIndex:i];
  573. switch (model.type) {
  574. case RAEditTypeLabel: {
  575. }
  576. break;
  577. case RAEditTypeInput: {
  578. RAEditInputModel *inputModel = (RAEditInputModel *)model;
  579. if (model.required && inputModel.value.length == 0) {
  580. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  581. continue;
  582. }
  583. if (inputModel.key && inputModel.value.length > 0) {
  584. [params setObject:inputModel.value forKey:inputModel.key];
  585. }
  586. }
  587. break;
  588. case RAEditTypeMultInput: {
  589. RAEditMultInputModel *multInputModel = (RAEditMultInputModel *)model;
  590. if (model.required && multInputModel.value.length == 0) {
  591. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  592. continue;
  593. }
  594. if (multInputModel.key && multInputModel.value.length > 0) {
  595. [params setObject:multInputModel.value forKey:multInputModel.key];
  596. }
  597. }
  598. break;
  599. case RAEditTypePhoto:
  600. case RAEditTypeSignature: {
  601. if (photoDir) {
  602. RAEditImageBaseModel *imageModel = (RAEditImageBaseModel *)model;
  603. if (model.required && imageModel.image == nil) {
  604. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  605. continue;
  606. }
  607. if (imageModel.image) {
  608. NSString *photoPath = [photoDir stringByAppendingPathComponent:imageModel.imageName];
  609. NSData *imgData = UIImageJPEGRepresentation(imageModel.image, 1.0f);
  610. if (imgData) {
  611. [imgData writeToFile:photoPath atomically:NO];
  612. [params setObject:imageModel.imageName forKey:imageModel.key];
  613. [photoArr addObject:imageModel];
  614. }
  615. }
  616. }
  617. }
  618. break;
  619. case RAEditTypeDate: {
  620. RAEditDateModel *dateModel = (RAEditDateModel *)model;
  621. if (model.required && dateModel.value.length == 0) {
  622. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  623. continue;
  624. }
  625. if (model.key && dateModel.value) {
  626. [params setObject:dateModel.value forKey:model.key];
  627. }
  628. }
  629. break;
  630. case RAEditTypeMultPhoto: {
  631. if (photoDir) {
  632. RAEditMultPhotoModel *photoModel = (RAEditMultPhotoModel *)model;
  633. NSUInteger count = photoModel.photoCount;
  634. if (photoModel.required && count == 0) {
  635. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  636. continue;
  637. }
  638. for (int i = 0; i < count; i++) {
  639. UIImage *img = [photoModel photoForIndex:i];
  640. if (img) {
  641. // 临时创建PhotoModel,用于上传
  642. RAEditPhotoModel *tmpPhotoModel = [RAEditPhotoModel new];
  643. tmpPhotoModel.type = RAEditTypePhoto;
  644. tmpPhotoModel.title = [NSString stringWithFormat:@"%@_%d",photoModel.title,i];
  645. tmpPhotoModel.key = [NSString stringWithFormat:@"%@_%d",photoModel.key,i];
  646. tmpPhotoModel.photo = img;
  647. NSString *photoPath = [photoDir stringByAppendingPathComponent:tmpPhotoModel.imageName];
  648. NSData *imgData = UIImageJPEGRepresentation(tmpPhotoModel.photo, 1.0f);
  649. if (imgData) {
  650. [imgData writeToFile:photoPath atomically:NO];
  651. [params setObject:tmpPhotoModel.imageName forKey:tmpPhotoModel.key];
  652. [photoArr addObject:tmpPhotoModel];
  653. }
  654. }
  655. }
  656. }
  657. }
  658. break;
  659. default:
  660. break;
  661. }
  662. }
  663. }
  664. return photoArr;
  665. }
  666. #pragma mark - Offline
  667. - (NSDictionary *)offlineUpdate:(NSDictionary *)params photos:(NSArray *)photos {
  668. return [RADataProvider offlineSubmitOrder:self.orderID action:self.actionID title:self.actionTitle index:self.actionIdx withParams:params photos:photos cacheDir:self.photoDir];
  669. }
  670. @end