RAOrderEditViewController.m 33 KB

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