RAHomeViewController.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. //
  2. // RAHomeViewController.m
  3. // Apex And Drivers
  4. //
  5. // Created by Jack on 2018/6/1.
  6. // Copyright © 2018年 USAI. All rights reserved.
  7. //
  8. #import "RAHomeViewController.h"
  9. #import "RAOrderDetailViewController.h"
  10. #import "RAProgressHUD.h"
  11. #import "ApexDriverUploadListVC.h"
  12. #import "RAHomeMoreViewController.h"
  13. #import <UserNotifications/UserNotifications.h>
  14. #import "UIScrollView+Empty.h"
  15. #import "RAEmptyView.h"
  16. #import "RAHomeHeaderView.h"
  17. #import "RAMessageViewController.h"
  18. #import "RASettingViewController.h"
  19. #import <CoreLocation/CoreLocation.h>
  20. @implementation RAHomeSectionModel
  21. - (instancetype)init {
  22. if (self = [super init]) {
  23. }
  24. return self;
  25. }
  26. - (void)setOrders:(NSArray *)orders {
  27. NSMutableArray *orderArr = [NSMutableArray array];
  28. for (int i = 0; i < orders.count; i++) {
  29. NSDictionary *order = [orders objectAtIndex:i];
  30. RAHomeOrderModel *orderModel = [RAHomeOrderModel new];
  31. [orderModel setValuesForKeysWithDictionary:order];
  32. [orderArr addObject:orderModel];
  33. }
  34. _orders = orderArr;
  35. }
  36. - (void)setBackendFlagCount:(NSInteger)backendFlagCount {
  37. _backendFlagCount = backendFlagCount;
  38. if (self.delegate && [self.delegate respondsToSelector:@selector(refreshUI)]) {
  39. [self.delegate refreshUI];
  40. }
  41. }
  42. - (RAHomeOrderModel *)orderModelForIndex:(NSInteger)index {
  43. return [self.orders objectAtIndex:index];
  44. }
  45. - (NSInteger)ordersCount {
  46. return self.orders.count;
  47. }
  48. - (NSInteger)orderModelIndexForID:(NSString *)orderID {
  49. __block NSInteger curIndex = -1;;
  50. [self.orders enumerateObjectsUsingBlock:^(RAHomeOrderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  51. if ([obj.orderID isEqualToString:orderID]) {
  52. curIndex = idx;
  53. return ;
  54. }
  55. }];
  56. return curIndex;
  57. }
  58. - (BOOL)hasMoreOrder {
  59. return self.totalCount > self.ordersCount;
  60. }
  61. @end
  62. #pragma mark - View Controller
  63. @interface RAHomeViewController () <RAHomeHeaderDelegate>
  64. @property (nonatomic,strong) NSMutableArray <RAHomeSectionModel *> *sectionArray;
  65. @property (nonatomic,strong) NSIndexPath *currentIndexPath;
  66. @property (nonatomic,strong) UIRefreshControl *refreshControl;
  67. @end
  68. @implementation RAHomeViewController
  69. + (instancetype)viewControllerFromStoryboard {
  70. RAHomeViewController *homeVC = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  71. return homeVC;
  72. }
  73. - (void)viewDidLoad {
  74. [super viewDidLoad];
  75. // Do any additional setup after loading the view.
  76. [self checkPermission];
  77. [self configureNavigationBar];
  78. [self configureTable];
  79. [self registNotification];
  80. [self loadData];
  81. }
  82. - (void)viewWillAppear:(BOOL)animated {
  83. [super viewWillAppear:animated];
  84. }
  85. - (void)viewDidAppear:(BOOL)animated {
  86. [super viewDidAppear:animated];
  87. if (self.reloadFlag) {
  88. [self loadData];
  89. self.reloadFlag = !self.reloadFlag;
  90. }
  91. }
  92. - (void)dealloc {
  93. [[NSNotificationCenter defaultCenter] removeObserver:self];
  94. }
  95. - (void)didReceiveMemoryWarning {
  96. [super didReceiveMemoryWarning];
  97. // Dispose of any resources that can be recreated.
  98. }
  99. #pragma mark - Configure
  100. - (void)configureTable {
  101. if (@available(iOS 11, *)) {
  102. self.homeOrderTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  103. } else {
  104. self.automaticallyAdjustsScrollViewInsets = NO;
  105. }
  106. self.homeOrderTableView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
  107. self.homeOrderTableView.tableFooterView = [UIView new];
  108. self.homeOrderTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
  109. UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
  110. [refresh addTarget:self action:@selector(refreshControlValueChanged:) forControlEvents:UIControlEventValueChanged];
  111. [self.homeOrderTableView addSubview:refresh];
  112. self.refreshControl = refresh;
  113. // empty
  114. __weak typeof(self) weakSelf = self;
  115. self.homeOrderTableView.emptyView = [RAEmptyView emptyViewWithTapBlk:^(id sender) {
  116. [weakSelf loadData];
  117. }];
  118. // Header
  119. self.headerView = [RAHomeHeaderView homeHeader];
  120. self.headerView.delegate = self;
  121. self.homeOrderTableView.tableHeaderView = self.headerView;
  122. }
  123. - (void)configureNavigationBar {
  124. UIImage *logo = [[UIImage imageNamed:@"apex_logo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  125. // UIImage *logo = [[UIImage imageNamed:@"apexlogo-2"] imageWithRenderingMode:UIImageRenderingModeAutomatic];
  126. UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:logo landscapeImagePhone:logo style:UIBarButtonItemStylePlain target:nil action:nil];
  127. // logoItem.enabled = NO;
  128. self.navigationItem.leftBarButtonItem = logoItem;
  129. UIBarButtonItem *uploadListItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"upload_list"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  130. style:UIBarButtonItemStylePlain
  131. target:self
  132. action:@selector(uploadListItemClick:)];
  133. self.navigationItem.rightBarButtonItems = @[uploadListItem];
  134. // UIBarButtonItem *logoutItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"logout"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
  135. // style:UIBarButtonItemStylePlain
  136. // target:self
  137. // action:@selector(logoutItemClick:)];
  138. //
  139. // self.navigationItem.rightBarButtonItems = @[logoutItem,uploadListItem];
  140. self.title = [NSString stringWithFormat:@"%@ %@",RASingleton.sharedInstance.user,RASingleton.sharedInstance.firstName];
  141. }
  142. - (void)registNotification {
  143. // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"%s",__func__]];
  144. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNewOrderNotification:) name:RANotificationHandleOrder object:nil];
  145. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveReloadNotification:) name:RANotificationReloadHome object:nil];
  146. }
  147. - (void)checkPermission {
  148. CLAuthorizationStatus locationAuthoriztionAstatus = [CLLocationManager authorizationStatus];
  149. [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
  150. UNAuthorizationStatus notificationAuthorizationStatus = settings.authorizationStatus;
  151. BOOL enableLocation = locationAuthoriztionAstatus != kCLAuthorizationStatusRestricted && locationAuthoriztionAstatus != kCLAuthorizationStatusDenied;
  152. BOOL enableRemoteNotification = notificationAuthorizationStatus != UNAuthorizationStatusDenied;
  153. if (!enableLocation | !enableRemoteNotification) {
  154. NSMutableString *msg = [NSMutableString stringWithString:NSLocalizedString(@"you should open", nil)];
  155. if (!enableLocation) {
  156. [msg appendString:NSLocalizedString(@" location permissions", nil)];
  157. }
  158. if (!enableRemoteNotification) {
  159. if (!enableLocation) {
  160. [msg appendString:NSLocalizedString(@" and notification permissions", nil)];
  161. } else {
  162. [msg appendString:NSLocalizedString(@" notification permissions", nil)];
  163. }
  164. }
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:msg preferredStyle:UIAlertControllerStyleAlert];
  167. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ok", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  168. NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  169. if ([[UIApplication sharedApplication] canOpenURL:url]) {
  170. [[UIApplication sharedApplication] openURL:url];
  171. }
  172. }];
  173. [alertVC addAction:okAction];
  174. [self presentViewController:alertVC animated:YES completion:nil];
  175. });
  176. }
  177. }];
  178. }
  179. #pragma mark - Action
  180. - (void)uploadListItemClick:(UIBarButtonItem *)sender {
  181. ApexDriverUploadListVC *vc = [ApexDriverUploadListVC viewControllerFromStoryboard];
  182. [self.navigationController pushViewController:vc animated:YES];
  183. }
  184. - (void)logoutItemClick:(UIBarButtonItem *)sender {
  185. // show progress
  186. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  187. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  188. [RADataProvider logout];
  189. dispatch_async(dispatch_get_main_queue(), ^{
  190. // dismiss progress
  191. [hud dismiss];
  192. [RASingleton.sharedInstance logout];
  193. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationLogout object:nil];
  194. });
  195. });
  196. }
  197. - (void)refreshControlValueChanged:(UIRefreshControl *)refresh {
  198. self.currentIndexPath = nil;
  199. [self loadData];
  200. }
  201. #pragma mark - Setter
  202. - (void)setHeaderView:(RAHomeHeaderView *)headerView {
  203. _headerView = headerView;
  204. }
  205. #pragma mark - Getter
  206. - (NSMutableArray *)sectionArray {
  207. if (!_sectionArray) {
  208. _sectionArray = [NSMutableArray array];
  209. }
  210. return _sectionArray;
  211. }
  212. - (RAHomeSectionModel *)modelForSection:(NSInteger)section {
  213. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  214. return sectionModel;
  215. }
  216. - (NSUInteger)orderSectionCount {
  217. return self.sectionArray.count;
  218. }
  219. - (NSUInteger)orderCountForSection:(NSInteger)section {
  220. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  221. return [sectionModel ordersCount];
  222. }
  223. - (RAHomeOrderModel *)orderModelForIndexPath:(NSIndexPath *)indexPath {
  224. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:indexPath.section];
  225. return [sectionModel orderModelForIndex:indexPath.row];
  226. }
  227. - (NSString *)titleForSection:(NSInteger)section {
  228. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  229. return sectionModel.title;
  230. }
  231. - (BOOL)hasMoreOrderForSection:(NSInteger)section {
  232. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  233. return [sectionModel hasMoreOrder];
  234. }
  235. - (NSInteger)backendCountForSection:(NSInteger)section {
  236. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  237. return sectionModel.backendFlagCount;
  238. }
  239. #pragma mark - Set/Update
  240. - (void)setBackendFlagCount:(NSInteger)count forSection:(NSInteger)section {
  241. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  242. sectionModel.backendFlagCount = count;
  243. }
  244. - (void)decreaseBackendFlagCountForSection:(NSInteger)section {
  245. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  246. NSInteger count = sectionModel.backendFlagCount;
  247. sectionModel.backendFlagCount = --count;
  248. }
  249. - (void)setHeaderDelegate:(id<RAHomeSectionModelDelegate>)delegate forSection:(NSInteger)section {
  250. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  251. sectionModel.delegate = delegate;
  252. }
  253. #pragma mark - Data
  254. - (void)loadData {
  255. if (self.loading) {
  256. return;
  257. }
  258. self.loading = YES;
  259. [self.homeOrderTableView hideEmpty];
  260. // show progress
  261. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  262. __weak typeof(self) weakSelf = self;
  263. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  264. NSDictionary *json = [RADataProvider requestOrderList];
  265. dispatch_async(dispatch_get_main_queue(), ^{
  266. // dismiss progress
  267. [hud dismiss];
  268. if (weakSelf.refreshControl.isRefreshing) {
  269. [weakSelf.refreshControl endRefreshing];
  270. }
  271. if (weakSelf) {
  272. __strong typeof(weakSelf) strongSelf = weakSelf;
  273. // header
  274. BOOL driverAvailable = [[json objectForKey:@"driver_available"] boolValue];
  275. strongSelf.headerView.availabel = driverAvailable;
  276. NSInteger newCount = [[json objectForKey:@"new_count"] integerValue];
  277. NSInteger processingCount = [[json objectForKey:@"processing_count"] integerValue];
  278. NSInteger finishCount = [[json objectForKey:@"finish_count"] integerValue];
  279. NSInteger messageCount = [[json objectForKey:@"message_count"] integerValue];
  280. strongSelf.headerView.NewOrderCount = newCount;
  281. strongSelf.headerView.ProcessingOrderCount = processingCount;
  282. strongSelf.headerView.FinishOrderCount = finishCount;
  283. strongSelf.headerView.existNewMessage = messageCount > 0;
  284. int result = [[json objectForKey:@"result"] intValue];
  285. if (result == RESULT_TRUE) {
  286. BOOL requiredLocation = [[json objectForKey:@"requiredLocation"] boolValue];
  287. [RASingleton sharedInstance].requiredLocation = requiredLocation;
  288. NSArray *sectionArray = [json objectForKey:@"sections"];
  289. NSMutableArray *tmpSectionArr = [NSMutableArray array];
  290. strongSelf.currentIndexPath = nil;
  291. for (int i = 0; i < sectionArray.count; i++) {
  292. NSDictionary *section = [sectionArray objectAtIndex:i];
  293. RAHomeSectionModel *sectionModel = [RAHomeSectionModel new];
  294. sectionModel.section = i;
  295. [sectionModel setValuesForKeysWithDictionary:section];
  296. [tmpSectionArr addObject:sectionModel];
  297. if (strongSelf.currentOrderID.length > 0) {
  298. NSInteger idx = [sectionModel orderModelIndexForID:self.currentOrderID];
  299. if (idx > -1) {
  300. strongSelf.currentIndexPath = [NSIndexPath indexPathForRow:idx inSection:i];
  301. }
  302. }
  303. }
  304. strongSelf.sectionArray = tmpSectionArr;
  305. [strongSelf.homeOrderTableView reloadData];
  306. if (strongSelf.currentIndexPath) {
  307. // [strongSelf.homeOrderTableView scrollToRowAtIndexPath:self.currentIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
  308. [strongSelf.homeOrderTableView selectRowAtIndexPath:strongSelf.currentIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
  309. } else {
  310. }
  311. } else {
  312. [strongSelf.sectionArray removeAllObjects];
  313. strongSelf.homeOrderTableView.contentOffset = CGPointZero;
  314. [strongSelf.homeOrderTableView reloadData];
  315. // process error
  316. NSString *msg = [json objectForKey:@"err_msg"];
  317. // [strongSelf showAlert:msg];
  318. [strongSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg];
  319. }
  320. }
  321. weakSelf.loading = NO;
  322. if (weakSelf.orderSectionCount == 0) {
  323. [weakSelf.homeOrderTableView showEmpty];
  324. } else {
  325. [weakSelf.homeOrderTableView hideEmpty];
  326. }
  327. });
  328. });
  329. }
  330. - (void)updateDriverAvailable:(BOOL)available {
  331. // show progress
  332. RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view];
  333. __weak typeof(self) weakSelf = self;
  334. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  335. NSDictionary *json = [RADataProvider updateDriverAvailable:available];
  336. dispatch_async(dispatch_get_main_queue(), ^{
  337. [hud dismiss];
  338. int result = [[json objectForKey:@"result"] intValue];
  339. if (result == RESULT_TRUE) {
  340. weakSelf.headerView.availabel = available;
  341. } else {
  342. NSString *msg = [json objectForKey:@"err_msg"];
  343. [weakSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg];
  344. }
  345. });
  346. });
  347. }
  348. #pragma mark - Controller Action
  349. - (void)pushDetailViewControllerForModel:(RAHomeOrderModel *)model {
  350. [self pushDetailViewControllerForOrderID:model.orderID type:model.status type2:model.order_type2 statusNo:model.status_no];
  351. }
  352. - (void)pushDetailViewControllerForOrderID:(NSString *)orderID type:(NSInteger)type type2:(NSString *)type2 statusNo:(NSString *)statusNo {
  353. if (!orderID) {
  354. return;
  355. }
  356. RAOrderDetailViewController *detailVC = [RAOrderDetailViewController viewControllerFromStoryboard];
  357. detailVC.orderID = orderID;
  358. detailVC.orderType = type;
  359. detailVC.orderType2 = type2;
  360. detailVC.status_no = statusNo;
  361. [self.navigationController pushViewController:detailVC animated:YES];
  362. }
  363. - (void)showMoreControllerWithTitle:(NSString *)title Type:(RAOrderStatus)type {
  364. RAHomeMoreViewController *homeMoreVC = [RAHomeMoreViewController viewControllerFromStoryboard];
  365. homeMoreVC.title = title;
  366. homeMoreVC.type = type;
  367. __weak typeof(self) weakSelf = self;
  368. homeMoreVC.backendFlagOrderClickBlk = ^{
  369. weakSelf.reloadFlag = YES;
  370. };
  371. [self.navigationController pushViewController:homeMoreVC animated:YES];
  372. }
  373. - (void)showMoreOrderForSection:(NSInteger)section {
  374. RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section];
  375. [self showMoreControllerWithTitle:sectionModel.title Type:sectionModel.type];
  376. }
  377. #pragma mark - Nofitication Selector
  378. - (void)receiveNewOrderNotification:(NSNotification *)notification {
  379. [self loadData];
  380. }
  381. - (void)receiveReloadNotification:(NSNotification *)notification {
  382. [self loadData];
  383. }
  384. #pragma mark - Header Delegate
  385. - (void)signoutClick:(UIButton *)sender {
  386. [self logoutItemClick:nil];
  387. }
  388. - (void)settingClick:(UIButton *)sender {
  389. dispatch_async(dispatch_get_main_queue(), ^{
  390. RASettingViewController *settingVC = [RASettingViewController viewControllerFromStoryboard];
  391. [self.navigationController pushViewController:settingVC animated:YES];
  392. });
  393. }
  394. - (void)availableClick:(UIButton *)sender {
  395. NSString *msg = [NSString localizedStringWithFormat:NSLocalizedString(@"are you sure to change status to %@", nil),self.headerView.availabel ? NSLocalizedString(@"Unavailable", nil) : NSLocalizedString(@"Available", nil)];
  396. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:msg preferredStyle:UIAlertControllerStyleAlert];
  397. UIAlertAction *yesAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"YES", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  398. [self updateDriverAvailable:!self.headerView.availabel];
  399. }];
  400. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  401. }];
  402. [alertVC addAction:cancelAction];
  403. [alertVC addAction:yesAction];
  404. [self presentViewController:alertVC animated:YES completion:nil];
  405. }
  406. - (void)messageClick:(UIButton *)sender {
  407. RAMessageViewController *messageVC = [RAMessageViewController viewControllerFromStoryboard];
  408. [self.navigationController pushViewController:messageVC animated:YES];
  409. }
  410. - (void)newOrderClick:(id)sender {
  411. [self showMoreControllerWithTitle:NSLocalizedString(@"New Order", nil) Type:RAOrderStatusNew];
  412. }
  413. - (void)processingOrderClick:(id)sender {
  414. [self showMoreControllerWithTitle:NSLocalizedString(@"Processing Order", nil) Type:RAOrderStatusProcessing];
  415. }
  416. - (void)finishedOrderClick:(id)sender {
  417. [self showMoreControllerWithTitle:NSLocalizedString(@"Finished Order", nil) Type:RAOrderStatusFinish];
  418. }
  419. @end