RAOrderEditViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //
  2. // RAOrderEditViewController.m
  3. // Apex And Drivers
  4. //
  5. // Created by Jack on 2018/6/4.
  6. // Copyright © 2018年 USAI. All rights reserved.
  7. //
  8. #import "RAOrderEditViewController.h"
  9. #import "RAEditInputModel.h"
  10. #import "RAEditMultInputModel.h"
  11. #import "RAEditLabelModel.h"
  12. #import "RAEditPhotoModel.h"
  13. #import "RAProgressHUD.h"
  14. #import "ZipArchive.h"
  15. #import "AppDelegate.h"
  16. #import <MapKit/MapKit.h>
  17. @interface RAEditSectionModel : NSObject
  18. @property (nonatomic,strong) NSArray <RAEditBaseModel *> *items;
  19. @property (nonatomic,copy) NSString *title;
  20. @end
  21. @implementation RAEditSectionModel
  22. - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
  23. }
  24. - (void)setItems:(NSArray<RAEditBaseModel *> *)items {
  25. NSArray *tmpItems = items;
  26. NSMutableArray *itemArr = [NSMutableArray arrayWithCapacity:items.count];
  27. for (int i = 0; i < tmpItems.count; i++) {
  28. NSDictionary *item = [tmpItems objectAtIndex:i];
  29. RAEditType type = [[item objectForKey:@"type"] intValue];
  30. switch (type) {
  31. case RAEditTypeLabel: {
  32. RAEditLabelModel *model = [RAEditLabelModel new];
  33. [model setValuesForKeysWithDictionary:item];
  34. [itemArr addObject:model];
  35. }
  36. break;
  37. case RAEditTypeInput: {
  38. RAEditInputModel *model = [RAEditInputModel new];
  39. [model setValuesForKeysWithDictionary:item];
  40. [itemArr addObject:model];
  41. }
  42. break;
  43. case RAEditTypeMultInput: {
  44. RAEditMultInputModel *model = [RAEditMultInputModel new];
  45. [model setValuesForKeysWithDictionary:item];
  46. [itemArr addObject:model];
  47. }
  48. break;
  49. case RAEditTypePhoto: {
  50. RAEditPhotoModel *model = [RAEditPhotoModel new];
  51. [model setValuesForKeysWithDictionary:item];
  52. [itemArr addObject:model];
  53. }
  54. break;
  55. default:
  56. break;
  57. }
  58. }
  59. _items = itemArr;
  60. }
  61. - (NSInteger)itemCount {
  62. return self.items.count;
  63. }
  64. - (RAEditBaseModel *)itemModelForIndex:(NSInteger)index {
  65. return [self.items objectAtIndex:index];
  66. }
  67. @end
  68. #pragma mark - View Controller
  69. @interface RAOrderEditViewController () <CLLocationManagerDelegate>
  70. @property (nonatomic,strong) IBOutlet UITableView *orderEditTableView;
  71. @property (nonatomic,strong) NSMutableArray *sectionArray;
  72. @property (nonatomic,strong) CLLocationManager *locationManager;
  73. @property (nonatomic,strong) CLLocation *currentLocation;
  74. @end
  75. @implementation RAOrderEditViewController
  76. + (instancetype)viewControllerFromStoryboard {
  77. RAOrderEditViewController *editVC = [[UIStoryboard storyboardWithName:@"Edit" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  78. return editVC;
  79. }
  80. - (void)viewDidLoad {
  81. [super viewDidLoad];
  82. // Do any additional setup after loading the view.
  83. [self configureTable];
  84. [self configureNavigationBar];
  85. [self loadData];
  86. }
  87. - (void)viewWillAppear:(BOOL)animated {
  88. [super viewWillAppear:animated];
  89. [self startLocation];
  90. [self registKeyboardListener];
  91. }
  92. - (void)viewWillDisappear:(BOOL)animated {
  93. [super viewWillDisappear:animated];
  94. [self stopLocation];
  95. [self unregistKeyboardListener];
  96. }
  97. - (void)didReceiveMemoryWarning {
  98. [super didReceiveMemoryWarning];
  99. // Dispose of any resources that can be recreated.
  100. }
  101. #pragma mark - Configure
  102. - (void)startLocation {
  103. self.locationManager = [[CLLocationManager alloc] init];
  104. self.locationManager.delegate = self;
  105. [self.locationManager requestWhenInUseAuthorization];
  106. [self.locationManager startUpdatingLocation];
  107. self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//设置定位精度
  108. self.locationManager.distanceFilter = 10;
  109. }
  110. - (void)stopLocation {
  111. [self.locationManager stopUpdatingLocation];
  112. }
  113. - (void)configureTable {
  114. self.orderEditTableView.tableFooterView = [UIView new];
  115. self.orderEditTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
  116. }
  117. - (void)configureNavigationBar {
  118. UIBarButtonItem *updateItem = [[UIBarButtonItem alloc] initWithTitle:@"Update" style:UIBarButtonItemStylePlain target:self action:@selector(updateBtnClick:)];
  119. self.navigationItem.rightBarButtonItem = updateItem;
  120. }
  121. - (void)registKeyboardListener {
  122. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
  123. }
  124. - (void)unregistKeyboardListener {
  125. [[NSNotificationCenter defaultCenter] removeObserver:self];
  126. }
  127. #pragma mark Getter
  128. - (NSMutableArray *)sectionArray {
  129. if (!_sectionArray) {
  130. _sectionArray = [NSMutableArray array];
  131. }
  132. return _sectionArray;
  133. }
  134. - (NSUInteger)editSectionCount {
  135. return self.sectionArray.count;
  136. }
  137. - (NSInteger)itemCountForSection:(NSInteger)section {
  138. return [[self.sectionArray objectAtIndex:section] itemCount];
  139. }
  140. - (RAEditBaseModel *)modelForIndexPath:(NSIndexPath *)indexPath {
  141. return [[self.sectionArray objectAtIndex:indexPath.section] itemModelForIndex:indexPath.row];
  142. }
  143. - (NSString *)titleForSection:(NSInteger)section {
  144. return [[self.sectionArray objectAtIndex:section] title];
  145. }
  146. - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell {
  147. return [self.orderEditTableView indexPathForCell:cell];
  148. }
  149. #pragma mark - Data
  150. - (void)loadData {
  151. // show progress
  152. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  153. NSString *orderID = self.orderID;
  154. NSInteger actionID = self.actionID;
  155. __weak typeof(self) weakSelf = self;
  156. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  157. NSDictionary *json = [RADataProvider requestUpdateOrder:orderID driverAction:actionID];
  158. dispatch_async(dispatch_get_main_queue(), ^{
  159. // dismiss progress
  160. [hud dismiss];
  161. if (weakSelf) {
  162. __strong typeof(weakSelf) strongSelf = weakSelf;
  163. int result = [[json objectForKey:@"result"] intValue];
  164. if (result == RESULT_TRUE) {
  165. NSArray *sectionArray = [json objectForKey:@"sections"];
  166. [strongSelf.sectionArray removeAllObjects];
  167. for (int i = 0; i < sectionArray.count; i++) {
  168. NSDictionary *section = [sectionArray objectAtIndex:i];
  169. RAEditSectionModel *model = [RAEditSectionModel new];
  170. [model setValuesForKeysWithDictionary:section];
  171. [strongSelf.sectionArray addObject:model];
  172. }
  173. [strongSelf.orderEditTableView reloadData];
  174. } else {
  175. // process error
  176. }
  177. }
  178. });
  179. });
  180. }
  181. #pragma mark - Tap Action
  182. - (IBAction)tapToResignFirstResponder:(UITapGestureRecognizer *)sender {
  183. [self.view endEditing:YES];
  184. }
  185. - (void)updateBtnClick:(UIBarButtonItem *)sender {
  186. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  187. NSMutableDictionary *task = [self preparePackage];
  188. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  189. [appDelegate.uploadManager addTask:task];
  190. __weak typeof(self) weakSelf = self;
  191. [hud dismiss:^{
  192. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Message" message:@"you can find the update progress in upload list" preferredStyle:UIAlertControllerStyleAlert];
  193. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  194. [weakSelf.navigationController popToRootViewControllerAnimated:YES];
  195. }];
  196. [alertVC addAction:okAction];
  197. [weakSelf presentViewController:alertVC animated:YES completion:nil];
  198. }];
  199. }
  200. #pragma mark - Keyboard Listener
  201. - (void)keyboardWillChangeFrame:(NSNotification *)notification {
  202. CGRect end = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  203. CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
  204. CGFloat keyboardHeight = screenHeight - CGRectGetMinY(end);
  205. UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0);
  206. self.orderEditTableView.contentInset = insets;
  207. if (self.editingIndexPath) {
  208. [self.orderEditTableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  209. }
  210. }
  211. #pragma mark - LocationManager Delegate
  212. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
  213. if (locations.count) {
  214. self.currentLocation = [locations lastObject];
  215. }
  216. }
  217. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  218. if (status == kCLAuthorizationStatusDenied) {
  219. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:@"app need location,would you like to open it" preferredStyle:UIAlertControllerStyleAlert];
  220. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  221. NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  222. if ([[UIApplication sharedApplication]canOpenURL:url]) {
  223. [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
  224. }
  225. [self.navigationController popViewControllerAnimated:NO];
  226. }];
  227. UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  228. }];
  229. [alertVC addAction:noAction];
  230. [alertVC addAction:okAction];
  231. [self presentViewController:alertVC animated:YES completion:nil];
  232. }
  233. }
  234. #pragma mark - Package Update Data
  235. - (NSString *)createPhotoDir {
  236. NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  237. NSString *photoDir = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld_%@",self.orderID,self.actionID,[NSUUID UUID].UUIDString]];
  238. NSError *error;
  239. // BOOL dirExist = YES;
  240. // for (int i = 0; i < INT_MAX; i++) {
  241. // if (i != 0) {
  242. // photoDir = [photoDir stringByAppendingString:[NSString stringWithFormat:@"(%d)",i]];
  243. // }
  244. // if (![[NSFileManager defaultManager] fileExistsAtPath:photoDir]) {
  245. // dirExist = NO;
  246. // break;
  247. // }
  248. // }
  249. [[NSFileManager defaultManager] createDirectoryAtPath:photoDir withIntermediateDirectories:YES attributes:nil error:&error];
  250. if (error) {
  251. NSLog(@"create dir %@ failed %@",photoDir,error.localizedDescription);
  252. return nil;
  253. }
  254. return photoDir;
  255. }
  256. - (NSMutableDictionary *)preparePackage {
  257. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  258. NSString *photoDir = [self createPhotoDir];
  259. [params setObject:self.orderID forKey:@"orderID"];
  260. [params setObject:@(self.actionID) forKey:@"actionID"];
  261. NSString* encryptu=[AESCrypt AES128Encrypt:[RASingleton sharedInstance].user key:@"usai"];
  262. NSString* encryptp=[AESCrypt AES128Encrypt:[RASingleton sharedInstance].password key:@"usai"];
  263. [params setObject:encryptu forKey:@"user"];
  264. [params setObject:encryptp forKey:@"password"];
  265. [params setObject:@"iOS" forKey:@"platform"];
  266. if (self.currentLocation) {
  267. [params setObject:[NSString stringWithFormat:@"%f,%f",self.currentLocation.coordinate.latitude,self.currentLocation.coordinate.longitude] forKey:@"location"];
  268. }
  269. NSInteger photoCount = 0;
  270. for (RAEditSectionModel *section in self.sectionArray) {
  271. for (int i = 0; i < [section itemCount]; i++) {
  272. RAEditBaseModel *model = [section itemModelForIndex:i];
  273. switch (model.type) {
  274. case RAEditTypeLabel: {
  275. }
  276. break;
  277. case RAEditTypeInput: {
  278. RAEditInputModel *inputModel = (RAEditInputModel *)model;
  279. if (inputModel.key && inputModel.value.length > 0) {
  280. [params setObject:inputModel.value forKey:inputModel.key];
  281. }
  282. }
  283. break;
  284. case RAEditTypeMultInput: {
  285. RAEditMultInputModel *multInputModel = (RAEditMultInputModel *)model;
  286. if (multInputModel.key && multInputModel.value.length > 0) {
  287. [params setObject:multInputModel.value forKey:multInputModel.key];
  288. }
  289. }
  290. break;
  291. case RAEditTypePhoto: {
  292. if (photoDir) {
  293. RAEditPhotoModel *photoModel = (RAEditPhotoModel *)model;
  294. if (photoModel.photo) {
  295. NSString *photoPath = [photoDir stringByAppendingPathComponent:photoModel.photoName];
  296. NSData *imgData = UIImageJPEGRepresentation(photoModel.photo, 1.0f);
  297. if (imgData) {
  298. [imgData writeToFile:photoPath atomically:NO];
  299. [params setObject:photoModel.photoName forKey:photoModel.key];
  300. photoCount++;
  301. }
  302. }
  303. }
  304. }
  305. break;
  306. default:
  307. break;
  308. }
  309. }
  310. }
  311. NSMutableDictionary *task = [@{
  312. @"order" : self.orderID,
  313. @"action" : self.actionTitle,
  314. @"url" : URL_HOST,
  315. @"noFile" : @(YES)
  316. } mutableCopy];
  317. if (photoCount > 0) {
  318. // 压缩文件
  319. NSString *zipPath = [photoDir stringByAppendingPathExtension:@".zip"];
  320. ZipArchive *zip = [[ZipArchive alloc] init];
  321. [zip CreateZipFile2:zipPath];
  322. NSArray *subPaths = [[NSFileManager defaultManager] subpathsAtPath:photoDir];
  323. for (NSString *subPath in subPaths) {
  324. NSString *fullPath = [photoDir stringByAppendingPathComponent:subPath];
  325. BOOL isDir;
  326. if([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir]) {
  327. if (!isDir) {
  328. [zip addFileToZip:fullPath newname:subPath];
  329. }
  330. }
  331. }
  332. [zip CloseZipFile2];
  333. [[NSFileManager defaultManager] removeItemAtPath:photoDir error:nil];
  334. NSString *md5 = [RAUtils md5WithFile:zipPath];
  335. [params setObject:md5 forKey:@"md5"];
  336. [task setObject:@"file" forKey:zipPath.lastPathComponent];
  337. }
  338. [task setObject:params forKey:@"params"];
  339. return task;
  340. }
  341. @end