// // RAHomeViewController.m // Apex And Drivers // // Created by Jack on 2018/6/1. // Copyright © 2018年 USAI. All rights reserved. // #import "RAHomeViewController.h" #import "RAOrderDetailViewController.h" #import "RAProgressHUD.h" #import "ApexDriverUploadListVC.h" #import "RAHomeMoreViewController.h" #import #import "UIScrollView+Empty.h" #import "RAEmptyView.h" #import "RAHomeHeaderView.h" #import "RAMessageViewController.h" #import "RASettingViewController.h" #import @implementation RAHomeSectionModel - (instancetype)init { if (self = [super init]) { } return self; } - (void)setOrders:(NSArray *)orders { NSMutableArray *orderArr = [NSMutableArray array]; for (int i = 0; i < orders.count; i++) { NSDictionary *order = [orders objectAtIndex:i]; RAHomeOrderModel *orderModel = [RAHomeOrderModel new]; [orderModel setValuesForKeysWithDictionary:order]; [orderArr addObject:orderModel]; } _orders = orderArr; } - (void)setBackendFlagCount:(NSInteger)backendFlagCount { _backendFlagCount = backendFlagCount; if (self.delegate && [self.delegate respondsToSelector:@selector(refreshUI)]) { [self.delegate refreshUI]; } } - (RAHomeOrderModel *)orderModelForIndex:(NSInteger)index { return [self.orders objectAtIndex:index]; } - (NSInteger)ordersCount { return self.orders.count; } - (NSInteger)orderModelIndexForID:(NSString *)orderID { __block NSInteger curIndex = -1;; [self.orders enumerateObjectsUsingBlock:^(RAHomeOrderModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([obj.orderID isEqualToString:orderID]) { curIndex = idx; return ; } }]; return curIndex; } - (BOOL)hasMoreOrder { return self.totalCount > self.ordersCount; } @end #pragma mark - View Controller @interface RAHomeViewController () @property (nonatomic,strong) NSMutableArray *sectionArray; @property (nonatomic,strong) NSIndexPath *currentIndexPath; @property (nonatomic,strong) UIRefreshControl *refreshControl; @end @implementation RAHomeViewController + (instancetype)viewControllerFromStoryboard { RAHomeViewController *homeVC = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]]; return homeVC; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self checkPermission]; [self configureNavigationBar]; [self configureTable]; [self registNotification]; [self loadData]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if (self.reloadFlag) { [self loadData]; self.reloadFlag = !self.reloadFlag; } } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Configure - (void)configureTable { if (@available(iOS 11, *)) { self.homeOrderTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; } else { self.automaticallyAdjustsScrollViewInsets = NO; } self.homeOrderTableView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1]; self.homeOrderTableView.tableFooterView = [UIView new]; self.homeOrderTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0); UIRefreshControl *refresh = [[UIRefreshControl alloc] init]; [refresh addTarget:self action:@selector(refreshControlValueChanged:) forControlEvents:UIControlEventValueChanged]; [self.homeOrderTableView addSubview:refresh]; self.refreshControl = refresh; // empty __weak typeof(self) weakSelf = self; self.homeOrderTableView.emptyView = [RAEmptyView emptyViewWithTapBlk:^(id sender) { [weakSelf loadData]; }]; // Header self.headerView = [RAHomeHeaderView homeHeader]; self.headerView.delegate = self; self.homeOrderTableView.tableHeaderView = self.headerView; } - (void)configureNavigationBar { UIImage *logo = [[UIImage imageNamed:@"apex_logo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; // UIImage *logo = [[UIImage imageNamed:@"apexlogo-2"] imageWithRenderingMode:UIImageRenderingModeAutomatic]; UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:logo landscapeImagePhone:logo style:UIBarButtonItemStylePlain target:nil action:nil]; // logoItem.enabled = NO; self.navigationItem.leftBarButtonItem = logoItem; UIBarButtonItem *uploadListItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"upload_list"] imageWithRenderingMode:UIImageRenderingModeAutomatic] style:UIBarButtonItemStylePlain target:self action:@selector(uploadListItemClick:)]; self.navigationItem.rightBarButtonItems = @[uploadListItem]; // UIBarButtonItem *logoutItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"logout"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] // style:UIBarButtonItemStylePlain // target:self // action:@selector(logoutItemClick:)]; // // self.navigationItem.rightBarButtonItems = @[logoutItem,uploadListItem]; self.title = [NSString stringWithFormat:@"%@ %@",RASingleton.sharedInstance.user,RASingleton.sharedInstance.firstName]; } - (void)registNotification { // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"%s",__func__]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNewOrderNotification:) name:RANotificationHandleOrder object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveReloadNotification:) name:RANotificationReloadHome object:nil]; } - (void)checkPermission { CLAuthorizationStatus locationAuthoriztionAstatus = [CLLocationManager authorizationStatus]; [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { UNAuthorizationStatus notificationAuthorizationStatus = settings.authorizationStatus; BOOL enableLocation = locationAuthoriztionAstatus != kCLAuthorizationStatusRestricted && locationAuthoriztionAstatus != kCLAuthorizationStatusDenied; BOOL enableRemoteNotification = notificationAuthorizationStatus != UNAuthorizationStatusDenied; if (!enableLocation | !enableRemoteNotification) { NSMutableString *msg = [NSMutableString stringWithString:NSLocalizedString(@"you should open", nil)]; if (!enableLocation) { [msg appendString:NSLocalizedString(@" location permissions", nil)]; } if (!enableRemoteNotification) { if (!enableLocation) { [msg appendString:NSLocalizedString(@" and notification permissions", nil)]; } else { [msg appendString:NSLocalizedString(@" notification permissions", nil)]; } } dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:msg preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ok", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url]; } }]; [alertVC addAction:okAction]; [self presentViewController:alertVC animated:YES completion:nil]; }); } }]; } #pragma mark - Action - (void)uploadListItemClick:(UIBarButtonItem *)sender { ApexDriverUploadListVC *vc = [ApexDriverUploadListVC viewControllerFromStoryboard]; [self.navigationController pushViewController:vc animated:YES]; } - (void)logoutItemClick:(UIBarButtonItem *)sender { // show progress RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view]; dispatch_async(dispatch_get_global_queue(0, 0), ^{ [RADataProvider logout]; dispatch_async(dispatch_get_main_queue(), ^{ // dismiss progress [hud dismiss]; [RASingleton.sharedInstance logout]; [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationLogout object:nil]; }); }); } - (void)refreshControlValueChanged:(UIRefreshControl *)refresh { self.currentIndexPath = nil; [self loadData]; } #pragma mark - Setter - (void)setHeaderView:(RAHomeHeaderView *)headerView { _headerView = headerView; } #pragma mark - Getter - (NSMutableArray *)sectionArray { if (!_sectionArray) { _sectionArray = [NSMutableArray array]; } return _sectionArray; } - (RAHomeSectionModel *)modelForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; return sectionModel; } - (NSUInteger)orderSectionCount { return self.sectionArray.count; } - (NSUInteger)orderCountForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; return [sectionModel ordersCount]; } - (RAHomeOrderModel *)orderModelForIndexPath:(NSIndexPath *)indexPath { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:indexPath.section]; return [sectionModel orderModelForIndex:indexPath.row]; } - (NSString *)titleForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; return sectionModel.title; } - (BOOL)hasMoreOrderForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; return [sectionModel hasMoreOrder]; } - (NSInteger)backendCountForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; return sectionModel.backendFlagCount; } #pragma mark - Set/Update - (void)setBackendFlagCount:(NSInteger)count forSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; sectionModel.backendFlagCount = count; } - (void)decreaseBackendFlagCountForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; NSInteger count = sectionModel.backendFlagCount; sectionModel.backendFlagCount = --count; } - (void)setHeaderDelegate:(id)delegate forSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; sectionModel.delegate = delegate; } #pragma mark - Data - (void)loadData { if (self.loading) { return; } self.loading = YES; [self.homeOrderTableView hideEmpty]; // show progress RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view]; __weak typeof(self) weakSelf = self; dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSDictionary *json = [RADataProvider requestOrderList]; dispatch_async(dispatch_get_main_queue(), ^{ // dismiss progress [hud dismiss]; if (weakSelf.refreshControl.isRefreshing) { [weakSelf.refreshControl endRefreshing]; } if (weakSelf) { __strong typeof(weakSelf) strongSelf = weakSelf; // header BOOL driverAvailable = [[json objectForKey:@"driver_available"] boolValue]; strongSelf.headerView.availabel = driverAvailable; NSInteger newCount = [[json objectForKey:@"new_count"] integerValue]; NSInteger processingCount = [[json objectForKey:@"processing_count"] integerValue]; NSInteger finishCount = [[json objectForKey:@"finish_count"] integerValue]; NSInteger messageCount = [[json objectForKey:@"message_count"] integerValue]; strongSelf.headerView.NewOrderCount = newCount; strongSelf.headerView.ProcessingOrderCount = processingCount; strongSelf.headerView.FinishOrderCount = finishCount; strongSelf.headerView.existNewMessage = messageCount > 0; int result = [[json objectForKey:@"result"] intValue]; if (result == RESULT_TRUE) { BOOL requiredLocation = [[json objectForKey:@"requiredLocation"] boolValue]; [RASingleton sharedInstance].requiredLocation = requiredLocation; NSArray *sectionArray = [json objectForKey:@"sections"]; NSMutableArray *tmpSectionArr = [NSMutableArray array]; strongSelf.currentIndexPath = nil; for (int i = 0; i < sectionArray.count; i++) { NSDictionary *section = [sectionArray objectAtIndex:i]; RAHomeSectionModel *sectionModel = [RAHomeSectionModel new]; sectionModel.section = i; [sectionModel setValuesForKeysWithDictionary:section]; [tmpSectionArr addObject:sectionModel]; if (strongSelf.currentOrderID.length > 0) { NSInteger idx = [sectionModel orderModelIndexForID:self.currentOrderID]; if (idx > -1) { strongSelf.currentIndexPath = [NSIndexPath indexPathForRow:idx inSection:i]; } } } strongSelf.sectionArray = tmpSectionArr; [strongSelf.homeOrderTableView reloadData]; if (strongSelf.currentIndexPath) { // [strongSelf.homeOrderTableView scrollToRowAtIndexPath:self.currentIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO]; [strongSelf.homeOrderTableView selectRowAtIndexPath:strongSelf.currentIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; } else { } } else { [strongSelf.sectionArray removeAllObjects]; strongSelf.homeOrderTableView.contentOffset = CGPointZero; [strongSelf.homeOrderTableView reloadData]; // process error NSString *msg = [json objectForKey:@"err_msg"]; // [strongSelf showAlert:msg]; [strongSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg]; } } weakSelf.loading = NO; if (weakSelf.orderSectionCount == 0) { [weakSelf.homeOrderTableView showEmpty]; } else { [weakSelf.homeOrderTableView hideEmpty]; } }); }); } - (void)updateDriverAvailable:(BOOL)available { // show progress RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.view]; __weak typeof(self) weakSelf = self; dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSDictionary *json = [RADataProvider updateDriverAvailable:available]; dispatch_async(dispatch_get_main_queue(), ^{ [hud dismiss]; int result = [[json objectForKey:@"result"] intValue]; if (result == RESULT_TRUE) { weakSelf.headerView.availabel = available; } else { NSString *msg = [json objectForKey:@"err_msg"]; [weakSelf showAlertTilte:NSLocalizedString(@"Warning", nil) message:msg]; } }); }); } #pragma mark - Controller Action - (void)pushDetailViewControllerForModel:(RAHomeOrderModel *)model { [self pushDetailViewControllerForOrderID:model.orderID type:model.status type2:model.order_type2 statusNo:model.status_no]; } - (void)pushDetailViewControllerForOrderID:(NSString *)orderID type:(NSInteger)type type2:(NSString *)type2 statusNo:(NSString *)statusNo { if (!orderID) { return; } RAOrderDetailViewController *detailVC = [RAOrderDetailViewController viewControllerFromStoryboard]; detailVC.orderID = orderID; detailVC.orderType = type; detailVC.orderType2 = type2; detailVC.status_no = statusNo; [self.navigationController pushViewController:detailVC animated:YES]; } - (void)showMoreControllerWithTitle:(NSString *)title Type:(RAOrderStatus)type { RAHomeMoreViewController *homeMoreVC = [RAHomeMoreViewController viewControllerFromStoryboard]; homeMoreVC.title = title; homeMoreVC.type = type; __weak typeof(self) weakSelf = self; homeMoreVC.backendFlagOrderClickBlk = ^{ weakSelf.reloadFlag = YES; }; [self.navigationController pushViewController:homeMoreVC animated:YES]; } - (void)showMoreOrderForSection:(NSInteger)section { RAHomeSectionModel *sectionModel = [self.sectionArray objectAtIndex:section]; [self showMoreControllerWithTitle:sectionModel.title Type:sectionModel.type]; } #pragma mark - Nofitication Selector - (void)receiveNewOrderNotification:(NSNotification *)notification { [self loadData]; } - (void)receiveReloadNotification:(NSNotification *)notification { [self loadData]; } #pragma mark - Header Delegate - (void)signoutClick:(UIButton *)sender { [self logoutItemClick:nil]; } - (void)settingClick:(UIButton *)sender { dispatch_async(dispatch_get_main_queue(), ^{ RASettingViewController *settingVC = [RASettingViewController viewControllerFromStoryboard]; [self.navigationController pushViewController:settingVC animated:YES]; }); } - (void)availableClick:(UIButton *)sender { NSString *msg = [NSString localizedStringWithFormat:NSLocalizedString(@"are you sure to change status to %@", nil),self.headerView.availabel ? NSLocalizedString(@"Unavailable", nil) : NSLocalizedString(@"Available", nil)]; UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:msg preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *yesAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"YES", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self updateDriverAvailable:!self.headerView.availabel]; }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }]; [alertVC addAction:cancelAction]; [alertVC addAction:yesAction]; [self presentViewController:alertVC animated:YES completion:nil]; } - (void)messageClick:(UIButton *)sender { RAMessageViewController *messageVC = [RAMessageViewController viewControllerFromStoryboard]; [self.navigationController pushViewController:messageVC animated:YES]; } - (void)newOrderClick:(id)sender { [self showMoreControllerWithTitle:NSLocalizedString(@"New Order", nil) Type:RAOrderStatusNew]; } - (void)processingOrderClick:(id)sender { [self showMoreControllerWithTitle:NSLocalizedString(@"Processing Order", nil) Type:RAOrderStatusProcessing]; } - (void)finishedOrderClick:(id)sender { [self showMoreControllerWithTitle:NSLocalizedString(@"Finished Order", nil) Type:RAOrderStatusFinish]; } @end