CityListViewController.m 7.83 KB
//
//  CityListViewController.m
//  IM_ios_client
//
//  Created by zsq on 2018/11/13.
//  Copyright © 2018 xiniu. All rights reserved.
//

#import "CityListViewController.h"

#import "CitySearchRequest.h"
#import "CitySearchResponse.h"
#import "City.h"

@interface CityListViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *tab_city;
    
    NSMutableArray *arr_index;
    NSMutableArray *arr_city;
    NSMutableArray *arr_showCity;
}

@end

@implementation CityListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = [NSString stringWithFormat:@"当前选择-%@",self.name];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss:)];
    self.navigationItem.leftBarButtonItem.tintColor = COLOR_S_BLACK;
    
    tab_city = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tab_city.delegate = self;
    tab_city.dataSource = self;
    tab_city.estimatedSectionFooterHeight = 0;
    tab_city.estimatedRowHeight = 0;
    tab_city.estimatedSectionHeaderHeight = 0;
    tab_city.sectionIndexColor = UIColorFromRGB(0xea281a, 1.0);
    tab_city.sectionIndexBackgroundColor = [UIColor clearColor];
    [self.mainLayout addSubview:tab_city];
    [tab_city mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.mainLayout);
    }];
    arr_city = [[NSMutableArray alloc]init];
    
    __weak __typeof(self) weakSelf = self;
    if ([SharedDataManager sharedInstance].muArr_city.count<1) {
        CitySearchRequest *req_CitySearch = [[CitySearchRequest alloc]init];
        [req_CitySearch.baseRequest setMethod:req_CitySearch.apimethodName];
        [req_CitySearch setPageSize:0];
        [[SharedDataManager sharedInstance].NIM_Client_AF f_sendRequest:req_CitySearch.baseRequest isPost:YES completion:^(NSDictionary *_dict) {
            BaseResponse *_res_base = (BaseResponse *)[_dict objectForKey:kResponseNotiKey_baseResponse];
            NSString *_str_error = [_dict objectForKey:kResponseNotiKey_error];
            if (![_str_error isEqualToString:kNoError]) {
                [[AlertHandler sharedInstance] showToastHUD:self.mainLayout message:_str_error sleepTime:Toast_Sleep];
            }else{
                CitySearchResponse *res_CitySearch = [[CitySearchResponse alloc]init];
                res_CitySearch.baseResponse = _res_base;
                [self->arr_city removeAllObjects];
                if (res_CitySearch.result.count) {
                    for (res_CitySearch.city_cursor = 0; res_CitySearch.city_cursor < res_CitySearch.result.count; res_CitySearch.city_cursor++) {
                        City *city = res_CitySearch.city;
                        [self->arr_city addObject:city];
                        [[SharedDataManager sharedInstance].muArr_city addObject:city];
                    }
                }
                [weakSelf setUpTableSection:self->arr_city];
            }
        }];
    }else{
        
        [self setUpTableSection:[SharedDataManager sharedInstance].muArr_city];
    }
    
    
    
    
}

- (NSString *)getFirstNameWithChineseName:(NSString *)name{
    NSMutableString * muName = [NSMutableString stringWithFormat:@"%@",name];
    CFStringTransform((CFMutableStringRef)muName, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)muName, NULL, kCFStringTransformStripDiacritics, NO);
    return [muName substringToIndex:1];
}

- (void)setUpTableSection:(NSMutableArray *)array
{
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    //create a temp sectionArray
    NSUInteger numberOfSections = [[collation sectionTitles] count];
    NSMutableArray *newSectionArray =  [[NSMutableArray alloc]init];
    for (NSUInteger index = 0; index < numberOfSections; index++) {
        [newSectionArray addObject:[[NSMutableArray alloc]init]];
    }
    
    // insert Persons info into newSectionArray
    for (City *city in array) {
        if (!city.pinyin) {
            city.pinyin = [self getFirstNameWithChineseName:city.name];
        }
            NSUInteger sectionIndex = [collation sectionForObject:city collationStringSelector:@selector(pinyin)];
            [newSectionArray[sectionIndex] addObject:city];
    }
    
    
    NSMutableArray *temp = [NSMutableArray new];
    arr_index = [[NSMutableArray alloc]init];
    
    [newSectionArray enumerateObjectsUsingBlock:^(NSArray *arr, NSUInteger idx, BOOL *stop) {
        if (arr.count == 0) {
            [temp addObject:arr];
        } else {
            [self->arr_index addObject:[collation sectionTitles][idx]];
        }
    }];
    [newSectionArray removeObjectsInArray:temp];
    arr_showCity = [newSectionArray mutableCopy];
    
    [tab_city reloadData];
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return arr_index;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    [tableView
     scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]
     atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    return index;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = COLOR_C_fafafa;
    UILabel *lbl_head = [[UILabel alloc]init];
    [view addSubview:lbl_head];
    lbl_head.text = [arr_index objectAtIndex:section];
    lbl_head.font = FONT_S_14;
    lbl_head.textColor = COLOR_C_333333;
    [lbl_head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view.mas_centerY);
        make.height.equalTo(@20);
        make.left.equalTo(view.mas_left).offset(MARGIN_15);
    }];
    return view;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return arr_index.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [(NSMutableArray *)arr_showCity[section] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = [NSString stringWithFormat:@"CELL%ld",(long)indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    City *city = arr_showCity[indexPath.section][indexPath.row];
    cell.textLabel.text = city.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    City *city = arr_showCity[indexPath.section][indexPath.row];
    
    if (self.finshBlock) {
        self.finshBlock(@{@"name":city.name,@"cityCode":[NSString stringWithFormat:@"%lld",city.uuid]});
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dismiss:(id)sender{
    if (self.navigationController.presentingViewController) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
    
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end