RAOrderEditViewController.m 32 KB

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