RAOrderEditViewController.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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. if (/*RASingleton.sharedInstance.requiredBackgroundLocation*/true)
  319. {
  320. CLLocation *location = RASingleton.sharedInstance.currentLocation;
  321. NSString *latLon = nil;
  322. if (location) {
  323. latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
  324. } else {
  325. latLon = @"-999,-999";
  326. }
  327. [params setObject:latLon forKey:@"location"];
  328. }
  329. NSMutableArray *emptyArr = [NSMutableArray array];
  330. NSMutableArray <RAEditImageBaseModel *> *photoArr = [self prepareParams:params checkRequired:emptyArr];
  331. if (emptyArr.count > 0) {
  332. RAEditRequiredAlert *alertVC = [RAEditRequiredAlert alertWithTile:NSLocalizedString(@"Warning", nil) message:[NSString localizedStringWithFormat:NSLocalizedString(@"please complete missing field:\n%@", nil),[emptyArr componentsJoinedByString:@"\n"]]];
  333. [self presentViewController:alertVC animated:YES completion:nil];
  334. self.updateItem.enabled = YES;
  335. return;
  336. }
  337. [params setValue:@(photoArr.count) forKey:@"photoCount"];
  338. // show progress
  339. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  340. __weak typeof(self) weakSelf = self;
  341. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  342. if (RASingleton.sharedInstance.offline) { // 离线
  343. NSDictionary *json = [weakSelf offlineUpdate:params photos:photoArr];
  344. dispatch_async(dispatch_get_main_queue(), ^{
  345. [hud dismiss:^{
  346. int result = [[json objectForKey:@"result"] intValue];
  347. NSString *msg = NSLocalizedString(@"sorry", nil);
  348. if (result == RESULT_TRUE) {
  349. msg = NSLocalizedString(@"offline_update_success", nil);
  350. [weakSelf submitSuccessWithMsg:msg];
  351. } else {
  352. msg = [json objectForKey:@"err_msg"];
  353. if (msg == nil) {
  354. msg = NSLocalizedString(@"sorry", nil);
  355. }
  356. [weakSelf showAlert:msg];
  357. weakSelf.updateItem.enabled = YES;
  358. }
  359. }];
  360. });
  361. }
  362. else { // 在线
  363. NSDictionary *json = [RADataProvider submitEditOrder:weakSelf.orderID actionIndex:weakSelf.actionIdx withParams:params];
  364. if (weakSelf) {
  365. __strong typeof(weakSelf) strongSelf = weakSelf;
  366. int result = [[json objectForKey:@"result"] intValue];
  367. if (result == RESULT_TRUE) {
  368. BOOL requiredLocation = [[json objectForKey:@"requiredLocation"] boolValue];
  369. [RASingleton sharedInstance].requiredBackgroundLocation = requiredLocation;
  370. dispatch_async(dispatch_get_main_queue(), ^{
  371. // if (photoArr.count > 0) {
  372. // [strongSelf syncUploadPhotos:photoArr Json:json HUD:hud];
  373. // } else {
  374. // [strongSelf gobackHome];
  375. // }
  376. // 全部转为后台上传
  377. if (photoArr.count > 0) {
  378. [strongSelf backgroundUploadPhoto:photoArr Json:json];
  379. }
  380. [hud dismiss:^{
  381. [strongSelf submitSuccessWithPhoto:photoArr.count > 0];
  382. }];
  383. });
  384. } else {
  385. // process error
  386. dispatch_async(dispatch_get_main_queue(), ^{
  387. // dismiss progress
  388. [hud dismiss:^{
  389. NSString *msg = [json objectForKey:@"err_msg"];
  390. [strongSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg];
  391. strongSelf.updateItem.enabled = YES;
  392. }];
  393. });
  394. }
  395. }
  396. }
  397. });
  398. }
  399. - (void)backgroundUploadPhoto:(NSArray<RAEditImageBaseModel *> *)photos Json:(NSDictionary *)json {
  400. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  401. NSDate *date = [NSDate date];
  402. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  403. formatter.dateFormat = @"MM/dd/YYYY HH:mm";
  404. NSString *time = [formatter stringFromDate:date];
  405. NSString *serial = [json objectForKey:@"serial"];
  406. for (RAEditImageBaseModel *model in photos) {
  407. if (serial.length) {
  408. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  409. [params setObject:serial forKey:@"serial"];
  410. if (self.orderType2) {
  411. [params setObject:self.orderType2 forKey:@"orderType2"];
  412. }
  413. if (model.key) {
  414. [params setObject:model.key forKey:@"key"];
  415. }
  416. [params setObject:@(model.type) forKey:@"type"];
  417. [params setObject:[RASingleton.sharedInstance encryptUser] forKey:@"name"];
  418. [params setObject:[RASingleton.sharedInstance encryptPassword] forKey:@"password"];
  419. [params setObject:@"iOS" forKey:@"platform"];
  420. NSString *photoPath = [self.photoDir.lastPathComponent stringByAppendingPathComponent:model.imageName];
  421. NSMutableDictionary *task = [@{
  422. @"order" : self.orderID,
  423. @"action" : self.actionTitle,
  424. @"name" : model.title,
  425. @"time" : time,
  426. @"url" : URL_UPLOAD,
  427. @"file" : photoPath,
  428. @"params" : params
  429. } mutableCopy];
  430. [appDelegate.uploadManager addTask:task];
  431. }
  432. }
  433. }
  434. - (void)syncUploadPhotos:(NSMutableArray<RAEditImageBaseModel *> *)photoArr Json:(NSDictionary *)json HUD:(RAProgressHUD *)hud {
  435. dispatch_async(dispatch_get_main_queue(), ^{
  436. RAProgressHUD *innerHUD = hud;
  437. if (!innerHUD) {
  438. innerHUD = [RAProgressHUD showHUDOnView:self.view]; // main queue
  439. }
  440. dispatch_async(dispatch_get_global_queue(0, 0), ^{ // network
  441. int retryCount = 0;
  442. NSMutableArray *completArr = [NSMutableArray array];
  443. NSString *serial = [json objectForKey:@"serial"];
  444. // 同步上传照片
  445. for (int i = 0; i < photoArr.count; i++) {
  446. RAEditImageBaseModel *model = [photoArr objectAtIndex:i];
  447. if (serial.length) {
  448. NSMutableDictionary *fileParams = [NSMutableDictionary dictionary];
  449. [fileParams setObject:serial forKey:@"serial"];
  450. if (self.orderType2) {
  451. [fileParams setObject:self.orderType2 forKey:@"orderType2"];
  452. }
  453. if (model.key) {
  454. [fileParams setObject:model.key forKey:@"key"];
  455. }
  456. [fileParams setObject:@(model.type) forKey:@"type"];
  457. NSString *photoPath = [self.photoDir stringByAppendingPathComponent:model.imageName];
  458. NSDictionary *uploadJson = [RADataProvider uploadFile:photoPath parameters:fileParams];
  459. int uploadResult = [[uploadJson objectForKey:@"result"] intValue];
  460. if (uploadResult != RESULT_TRUE) { // 失败重试
  461. i--;
  462. retryCount++;
  463. if (retryCount >= 3) {
  464. break;
  465. }
  466. } else {
  467. [completArr addObject:model];
  468. retryCount = 0;
  469. // 删除文件
  470. if ([[NSFileManager defaultManager] fileExistsAtPath:photoPath]) {
  471. [[NSFileManager defaultManager] removeItemAtPath:photoPath error:nil];
  472. }
  473. }
  474. } // serial
  475. } // for
  476. // 将完成的model移除
  477. [photoArr removeObjectsInArray:completArr];
  478. __weak typeof(self) weakSelf = self;
  479. dispatch_async(dispatch_get_main_queue(), ^{
  480. [innerHUD dismiss:^{
  481. if (photoArr.count > 0) {
  482. // 上传失败,询问是否丢到后台线程上传,否则重启上传
  483. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"update_upload_failed_tips", nil) preferredStyle:UIAlertControllerStyleAlert];
  484. UIAlertAction *backgroundAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Background", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  485. // 开启后台上传
  486. [weakSelf backgroundUploadPhoto:photoArr Json:json];
  487. // 返回首页
  488. [weakSelf gobackHome];
  489. }];
  490. UIAlertAction *retryAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Retry", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  491. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  492. [weakSelf syncUploadPhotos:photoArr Json:json HUD:nil];
  493. });
  494. }];
  495. [alertVC addAction:backgroundAction];
  496. [alertVC addAction:retryAction];
  497. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  498. } else {
  499. // 上传完成,返回到首页
  500. [weakSelf gobackHome];
  501. }
  502. }];
  503. });
  504. });
  505. });
  506. }
  507. - (void)gobackHome {
  508. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationReloadHome object:nil];
  509. [self.navigationController popToRootViewControllerAnimated:YES];
  510. }
  511. #pragma mark - Keyboard Listener
  512. - (void)keyboardWillChangeFrame:(NSNotification *)notification {
  513. CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  514. CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
  515. CGFloat keyboardHeight = screenHeight - CGRectGetMinY(end);
  516. UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
  517. self.orderEditTableView.contentInset = insets;
  518. if (self.editingIndexPath) {
  519. [self.orderEditTableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  520. }
  521. }
  522. #pragma mark - Package Update Data
  523. - (NSString *)photoDir {
  524. if (!_photoDir) {
  525. NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  526. NSString *photoDir = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld_%@",self.orderID,(long)self.actionID,[NSUUID UUID].UUIDString]];
  527. NSError *error;
  528. // BOOL dirExist = YES;
  529. // for (int i = 0; i < INT_MAX; i++) {
  530. // if (i != 0) {
  531. // photoDir = [photoDir stringByAppendingString:[NSString stringWithFormat:@"(%d)",i]];
  532. // }
  533. // if (![[NSFileManager defaultManager] fileExistsAtPath:photoDir]) {
  534. // dirExist = NO;
  535. // break;
  536. // }
  537. // }
  538. [[NSFileManager defaultManager] createDirectoryAtPath:photoDir withIntermediateDirectories:YES attributes:nil error:&error];
  539. if (error) {
  540. NSLog(@"create dir %@ failed %@",photoDir,error.localizedDescription);
  541. return nil;
  542. }
  543. _photoDir = photoDir;
  544. }
  545. return _photoDir;
  546. }
  547. - (NSMutableArray <RAEditImageBaseModel *> *)prepareParams:(NSMutableDictionary *)params checkRequired:(NSMutableArray *)emptyArr {
  548. if (params == nil) {
  549. return nil;;
  550. }
  551. NSMutableArray <RAEditImageBaseModel *> *photoArr = [NSMutableArray array];
  552. NSString *photoDir = [self photoDir];
  553. [params setObject:self.orderID forKey:@"orderID"];
  554. [params setObject:@(self.actionID) forKey:@"actionID"];
  555. NSString* encryptu = [RASingleton sharedInstance].encryptUser;
  556. NSString* encryptp = [RASingleton sharedInstance].encryptPassword;
  557. [params setObject:encryptu forKey:@"name"];
  558. [params setObject:encryptp forKey:@"password"];
  559. [params setObject:@"iOS" forKey:@"platform"];
  560. for (RAEditSectionModel *section in self.sectionArray) {
  561. for (int i = 0; i < [section itemCount]; i++) {
  562. RAEditBaseModel *model = [section itemModelForIndex:i];
  563. switch (model.type) {
  564. case RAEditTypeLabel: {
  565. }
  566. break;
  567. case RAEditTypeInput: {
  568. RAEditInputModel *inputModel = (RAEditInputModel *)model;
  569. if (model.required && inputModel.value.length == 0) {
  570. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  571. continue;
  572. }
  573. if (inputModel.key && inputModel.value.length > 0) {
  574. [params setObject:inputModel.value forKey:inputModel.key];
  575. }
  576. }
  577. break;
  578. case RAEditTypeMultInput: {
  579. RAEditMultInputModel *multInputModel = (RAEditMultInputModel *)model;
  580. if (model.required && multInputModel.value.length == 0) {
  581. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  582. continue;
  583. }
  584. if (multInputModel.key && multInputModel.value.length > 0) {
  585. [params setObject:multInputModel.value forKey:multInputModel.key];
  586. }
  587. }
  588. break;
  589. case RAEditTypePhoto:
  590. case RAEditTypeSignature: {
  591. if (photoDir) {
  592. RAEditImageBaseModel *imageModel = (RAEditImageBaseModel *)model;
  593. if (model.required && imageModel.image == nil) {
  594. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  595. continue;
  596. }
  597. if (imageModel.image) {
  598. NSString *photoPath = [photoDir stringByAppendingPathComponent:imageModel.imageName];
  599. NSData *imgData = UIImageJPEGRepresentation(imageModel.image, 1.0f);
  600. if (imgData) {
  601. [imgData writeToFile:photoPath atomically:NO];
  602. [params setObject:imageModel.imageName forKey:imageModel.key];
  603. [photoArr addObject:imageModel];
  604. }
  605. }
  606. }
  607. }
  608. break;
  609. case RAEditTypeDate: {
  610. RAEditDateModel *dateModel = (RAEditDateModel *)model;
  611. if (model.required && dateModel.value.length == 0) {
  612. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  613. continue;
  614. }
  615. if (model.key && dateModel.value) {
  616. [params setObject:dateModel.value forKey:model.key];
  617. }
  618. }
  619. break;
  620. case RAEditTypeMultPhoto: {
  621. if (photoDir) {
  622. RAEditMultPhotoModel *photoModel = (RAEditMultPhotoModel *)model;
  623. NSUInteger count = photoModel.photoCount;
  624. if (photoModel.required && count == 0) {
  625. [emptyArr addObject:[NSString stringWithFormat:@"%ld.%@",emptyArr.count + 1,model.title]];
  626. continue;
  627. }
  628. for (int i = 0; i < count; i++) {
  629. UIImage *img = [photoModel photoForIndex:i];
  630. if (img) {
  631. // 临时创建PhotoModel,用于上传
  632. RAEditPhotoModel *tmpPhotoModel = [RAEditPhotoModel new];
  633. tmpPhotoModel.type = RAEditTypePhoto;
  634. tmpPhotoModel.title = [NSString stringWithFormat:@"%@_%d",photoModel.title,i];
  635. tmpPhotoModel.key = [NSString stringWithFormat:@"%@_%d",photoModel.key,i];
  636. tmpPhotoModel.photo = img;
  637. NSString *photoPath = [photoDir stringByAppendingPathComponent:tmpPhotoModel.imageName];
  638. NSData *imgData = UIImageJPEGRepresentation(tmpPhotoModel.photo, 1.0f);
  639. if (imgData) {
  640. [imgData writeToFile:photoPath atomically:NO];
  641. [params setObject:tmpPhotoModel.imageName forKey:tmpPhotoModel.key];
  642. [photoArr addObject:tmpPhotoModel];
  643. }
  644. }
  645. }
  646. }
  647. }
  648. break;
  649. default:
  650. break;
  651. }
  652. }
  653. }
  654. return photoArr;
  655. }
  656. #pragma mark - Offline
  657. - (NSDictionary *)offlineUpdate:(NSDictionary *)params photos:(NSArray *)photos {
  658. return [RADataProvider offlineSubmitOrder:self.orderID action:self.actionID title:self.actionTitle index:self.actionIdx withParams:params photos:photos cacheDir:self.photoDir];
  659. }
  660. @end