//
//  ChooseLocationView.m
//  ChooseLocation
//
//  Created by Sekorm on 16/8/22.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "ChooseLocationView.h"
#import "AddressView.h"
#import "UIView+frameAdjust.h"
#import "AddressTableViewCell.h"
#import "AddressItem.h"
#import "CitiesDataTool.h"

#import "ProvinceModel.h"
#import "CTAPIBaseManager.h"

#define HYScreenW [UIScreen mainScreen].bounds.size.width

static  CGFloat  const  kHYTopViewHeight = 40; //顶部视图的高度
static  CGFloat  const  kHYTopTabbarHeight = 30; //地址标签栏的高度

@interface ChooseLocationView ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,weak) AddressView * topTabbar;
@property (nonatomic,weak) UIScrollView * contentView;
@property (nonatomic,weak) UIView * underLine;

@property (nonatomic,strong) NSMutableArray * tableViews;
@property (nonatomic,strong) NSMutableArray * topTabbarItems;
@property (nonatomic,weak) UIButton * selectedBtn;
@end

@implementation ChooseLocationView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

#pragma mark - setUp UI

- (void)setUp{
    
    UIView * topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, kHYTopViewHeight)];
    [self addSubview:topView];
    UILabel * titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"所在地区";
    [titleLabel sizeToFit];
    [topView addSubview:titleLabel];
    titleLabel.centerY = topView.height * 0.5;
    titleLabel.centerX = topView.width * 0.5;
    UIView * separateLine = [self separateLine];
    [topView addSubview: separateLine];
    separateLine.minY = topView.height - separateLine.height;
    topView.backgroundColor = [UIColor whiteColor];

    
    AddressView * topTabbar = [[AddressView alloc]initWithFrame:CGRectMake(0, topView.height, self.frame.size.width, kHYTopViewHeight)];
    [self addSubview:topTabbar];
    _topTabbar = topTabbar;
    [self addTopBarItem];
    UIView * separateLine1 = [self separateLine];
    [topTabbar addSubview: separateLine1];
    separateLine1.minY = topTabbar.height - separateLine.height;
    [_topTabbar layoutIfNeeded];
    topTabbar.backgroundColor = [UIColor whiteColor];
    
    UIView * underLine = [[UIView alloc] initWithFrame:CGRectZero];
    [topTabbar addSubview:underLine];
    _underLine = underLine;
    underLine.height = 2.0f;
    UIButton * btn = self.topTabbarItems.lastObject;
    [self changeUnderLineFrame:btn];
    underLine.minY = separateLine1.minY - underLine.height;
    
    _underLine.backgroundColor = [UIColor orangeColor];
    UIScrollView * contentView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(topTabbar.frame), self.frame.size.width, self.height - kHYTopViewHeight - kHYTopTabbarHeight)];
    contentView.contentSize = CGSizeMake(HYScreenW, 0);
    [self addSubview:contentView];
    _contentView = contentView;
    _contentView.pagingEnabled = YES;
    _contentView.backgroundColor = [UIColor whiteColor];
    [self addTableView];
    _contentView.delegate = self;
}


- (void)addTableView{

    UITableView * tabbleView = [[UITableView alloc]initWithFrame:CGRectMake(self.tableViews.count * HYScreenW, 0, HYScreenW, _contentView.height)];
    [_contentView addSubview:tabbleView];
    [self.tableViews addObject:tabbleView];
    tabbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tabbleView.delegate = self;
    tabbleView.dataSource = self;
    tabbleView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    [tabbleView registerNib:[UINib nibWithNibName:@"AddressTableViewCell" bundle:nil] forCellReuseIdentifier:@"AddressTableViewCell"];
}

- (void)addTopBarItem{
    
    UIButton * topBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    [topBarItem setTitle:@"请选择" forState:UIControlStateNormal];
    [topBarItem setTitleColor:[UIColor colorWithRed:43/255.0 green:43/255.0 blue:43/255.0 alpha:1] forState:UIControlStateNormal];
    [topBarItem setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [topBarItem sizeToFit];
     topBarItem.centerY = _topTabbar.height * 0.5;
    [self.topTabbarItems addObject:topBarItem];
    [_topTabbar addSubview:topBarItem];
    [topBarItem addTarget:self action:@selector(topBarItemClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - loadDataAPi
- (void)getCitysWithProvinceModel:(ProvinceModel *)model block:(void(^)(BOOL))returnBack
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/city"];
    
    
    NSString *str1 = [NSString stringWithFormat:@"province_id=%@&province_name=%@&KkweInfo",[EnercryTool encryptUseDES:model.provice_id  key:@"KkweFace95271124"],[EnercryTool encryptUseDES:model.provice_name key:@"KkweFace95271124"]];
    
     str1 =  [MyMD5 md5:str1];
    
    NSDictionary *params = @{
                             @"province_name":[EnercryTool encryptUseDES:model.provice_name key:@"KkweFace95271124"],
                             @"province_id":[EnercryTool encryptUseDES:model.provice_id key:@"KkweFace95271124"],
                             @"flag":@2,
                             @"sign":str1
                             };
    
    NSLog(@"收货地址城市api:%@",url);
    NSLog(@"params:%@",params);
    
    
    [KKLoadingAnimationView show];
    WeakSelf
    
    [NetworkRequest SBAuthPost:url Params:params Success:^(id _Nonnull responseObject) {
        
        [KKLoadingAnimationView dismiss];
        
        if (responseObject) {
            
            if ([responseObject[@"code"] isKindOfClass:[NSNumber class]]) {
                 NSNumber *code = responseObject[@"code"];
                
                if (code.integerValue == 0) {
                    if ( [responseObject[@"result"] isKindOfClass:[NSArray class]]) {
                        
//                        NSArray *array = responseObject[@"result"];
                        
                        weakSelf.cityDataSouce = [CModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
                        
                        returnBack(YES);
                        
                    }
                        
                
                    
                }else{
                    [SVProgressHUD showInfoWithStatus:@"请求失败"];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器异常"];
            }
            
           
            
            NSLog(@"请求结束responseObject:%@",responseObject);
        }
        
    } Failure:^(NSError * _Nonnull error) {
        
        [KKLoadingAnimationView dismiss];
        
        if (error) {
            
            NSLog(@"请求失败error:%@",error);
            [SVProgressHUD showInfoWithStatus:@"请求失败"];
            return ;
        }
        
    }];
}

//请求区县列表
- (void)getCountiesWithCityModel:(CModel *)model block:(void(^)(BOOL))returnBack
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/county"];
    
    
    NSString *str1 = [NSString stringWithFormat:@"city_id=%@&city_name=%@&KkweInfo",[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",model.city_id]  key:@"KkweFace95271124"],[EnercryTool encryptUseDES:model.city_name key:@"KkweFace95271124"]];
    
    str1 =  [MyMD5 md5:str1];
    
    NSDictionary *params = @{
                             @"city_name":[EnercryTool encryptUseDES:model.city_name key:@"KkweFace95271124"],
                             @"city_id":[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",model.city_id] key:@"KkweFace95271124"],
                             @"flag":@2,
                             @"sign":str1
                             };
    
    NSLog(@"社保卡采集地址区县api:%@",url);
    NSLog(@"社保卡采集地址区县params:%@",params);
    
    NSLog(@"请求开始:");
    
    [KKLoadingAnimationView show];
    
    [NetworkRequest SBAuthPost:url Params:params Success:^(id _Nonnull responseObject) {
        
        [KKLoadingAnimationView dismiss];
        
        if (responseObject) {
            
            if ([responseObject[@"code"] isKindOfClass:[NSNumber class]]) {
                NSNumber *code = responseObject[@"code"];

                if (code.integerValue == 0) {
                    if ( [responseObject[@"result"] isKindOfClass:[NSArray class]]) {
                        self.districtDataSouce = [CountyModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
                        returnBack(YES);
                    }else{
                        self.districtDataSouce = nil;
                    }

                }else{
                    [SVProgressHUD showInfoWithStatus:@"请求失败"];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器异常"];
            }
            
            
            
            NSLog(@"请求结束responseObject:%@",responseObject);
        }
        
    } Failure:^(NSError * _Nonnull error) {
        
        [KKLoadingAnimationView dismiss];
        
        if (error) {
            
            NSLog(@"请求失败error:%@",error);
            [SVProgressHUD showInfoWithStatus:@"请求失败"];
            return ;
        }
        
    }];
}


#pragma mark - TableViewDatasouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if([self.tableViews indexOfObject:tableView] == 0){
        return self.dataSouce.count;
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        return self.cityDataSouce.count;
    }else if ([self.tableViews indexOfObject:tableView] == 2){
        return self.districtDataSouce.count;
    }
    return self.dataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    AddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AddressTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    AddressItem * item;
    
    
    //省级别
    if([self.tableViews indexOfObject:tableView] == 0){
        ProvinceModel*mode = self.dataSouce[indexPath.row];
       // item = self.dataSouce[indexPath.row];
        cell.provinceModel = mode;
        return cell;
    //市级别
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        
        CModel *cmodel = self.cityDataSouce[indexPath.row];
        //item = self.cityDataSouce[indexPath.row];
        cell.cityModel = cmodel;
        return cell;
    //县级别
    }else if ([self.tableViews indexOfObject:tableView] == 2){
       // item = self.districtDataSouce[indexPath.row];
        CountyModel *cmodel = self.districtDataSouce[indexPath.row];
        cell.countyModel = cmodel;
        return cell;
    }
    cell.item = item;
    return cell;
}

#pragma mark - TableViewDelegate
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if([self.tableViews indexOfObject:tableView] == 0){
        

       
        
        return indexPath;
        
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        
        CModel *model = self.cityDataSouce[indexPath.row];
        NSIndexPath * indexPath0 = [tableView indexPathForSelectedRow];
                      
        [self selectCity:model indexPath:indexPath tableView:tableView selectedIndexPath:indexPath0];
        
        return indexPath;
        
    }else if ([self.tableViews indexOfObject:tableView] == 2){
        
        //AddressItem * item = self.districtDataSouce[indexPath.row];
        CountyModel *model = self.districtDataSouce[indexPath.row];
        
        [self setUpAddress:model.county_name];
    }
    return indexPath;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddressItem * item;
    if([self.tableViews indexOfObject:tableView] == 0){
        ProvinceModel *model = self.dataSouce[indexPath.row];
        
        [self selectProvince:model indexPath:indexPath tableView:tableView];
        
        model.isSelected = YES;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        return;
        
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        CModel *model = self.cityDataSouce[indexPath.row];
//        NSIndexPath * indexPath0 = [tableView indexPathForSelectedRow];
        
        model.isSelected = YES;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        return;
    }else if ([self.tableViews indexOfObject:tableView] == 2){
        CountyModel *model = self.districtDataSouce[indexPath.row];
        model.isSelected = YES;
        
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        return;
        
    }
    item.isSelected = YES;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddressItem * item;
    if([self.tableViews indexOfObject:tableView] == 0){
        ProvinceModel* model = self.dataSouce[indexPath.row];
        model.isSelected = NO;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        return;
        
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        CModel* model = self.cityDataSouce[indexPath.row];
        model.isSelected = NO;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        return;
        
    }else if ([self.tableViews indexOfObject:tableView] == 2){
        CountyModel *model = self.districtDataSouce[indexPath.row];
        model.isSelected = NO;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        return;
    }
    item.isSelected = NO;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}

- (void)selectProvince:(ProvinceModel *)model indexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    [self getCitysWithProvinceModel:model block:^(BOOL success) {
        if (success) {
            
            
            if(self.cityDataSouce.count == 0){
                for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1; i++) {
                    [self removeLastItem];
                }
                [self setUpAddress:model.provice_name];
            }else{
                
                
                
                //1.1 判断是否是第一次选择,不是,则重新选择省,切换省.
                       NSIndexPath * indexPath0 = [tableView indexPathForSelectedRow];

                       if ([indexPath0 compare:indexPath] != NSOrderedSame && indexPath0) {
                           
                           for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1; i++) {
                               [self removeLastItem];
                           }
                           [self addTopBarItem];
                           [self addTableView];
                           [self scrollToNextItem:model.provice_name];
                          
                           
                       }else if ([indexPath0 compare:indexPath] == NSOrderedSame && indexPath0){
                           
                           for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1 ; i++) {
                               [self removeLastItem];
                           }
                           [self addTopBarItem];
                           [self addTableView];
                           [self scrollToNextItem:model.provice_name];
                          
                       }else{
                           //之前未选中省，第一次选择省
                            [self addTopBarItem];
                            [self addTableView];
                            AddressItem * item = self.dataSouce[indexPath.row];
                            [self scrollToNextItem:item.name ];
                       }

                     
            }
            
            
            
            
        }
    }];
    
}
- (void)selectCity:(CModel *)model indexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView selectedIndexPath:(NSIndexPath *)selectedIndexPath
{
    WeakSelf
    [self getCountiesWithCityModel:model block:^(BOOL success) {
        if (success) {
            
            if ([selectedIndexPath compare:indexPath] != NSOrderedSame && selectedIndexPath) {
                          
                          for (int i = 0; i < self.tableViews.count - 1; i++) {
                              [self removeLastItem];
                          }
                          [weakSelf addTopBarItem];
                          [weakSelf addTableView];
                          [weakSelf scrollToNextItem:model.city_name];
                         

                }else if ([selectedIndexPath compare:indexPath] == NSOrderedSame && selectedIndexPath){
                
                    [weakSelf scrollToNextItem:model.city_name];
                  
                }else{
                    [weakSelf addTopBarItem];
                    [weakSelf addTableView];
                    [weakSelf scrollToNextItem:model.city_name];
                }
            
            
            
        }
    }];
           
}



#pragma mark - private 

//点击按钮,滚动到对应位置
- (void)topBarItemClick:(UIButton *)btn{
    
    NSInteger index = [self.topTabbarItems indexOfObject:btn];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.contentView.contentOffset = CGPointMake(index * HYScreenW, 0);
        [self changeUnderLineFrame:btn];
    }];
}

//调整指示条位置
- (void)changeUnderLineFrame:(UIButton  *)btn{
    
    _selectedBtn.selected = NO;
    btn.selected = YES;
    _selectedBtn = btn;
    _underLine.x = btn.x;
    _underLine.width = btn.width;
}

//完成地址选择,执行chooseFinish代码块
- (void)setUpAddress:(NSString *)address{

    NSInteger index = self.contentView.contentOffset.x / HYScreenW;
    UIButton * btn = self.topTabbarItems[index];
    [btn setTitle:address forState:UIControlStateNormal];
    [btn sizeToFit];
    [_topTabbar layoutIfNeeded];
    [self changeUnderLineFrame:btn];
    NSMutableString * addressStr = [[NSMutableString alloc] init];
    for (UIButton * btn  in self.topTabbarItems) {
//        if ([btn.currentTitle isEqualToString:@"县"] || [btn.currentTitle isEqualToString:@"市辖区"] ) {
//            continue;
//        }
        [addressStr appendString:btn.currentTitle];
        [addressStr appendString:@""];
    }
    
    if (self.topTabbarItems.count == 3) {
        UIButton* btn1 = self.topTabbarItems[0];
        UIButton* btn2 = self.topTabbarItems[1];
        UIButton* btn3 = self.topTabbarItems[2];
        self.province = btn1.currentTitle;
        self.city = btn2.currentTitle;
        self.county = btn3.currentTitle;
    }
    
    self.address = addressStr;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.hidden = YES;
        if (self.chooseFinish) {
            self.chooseFinish();
        }
    });
}

//当重新选择省或者市的时候，需要将下级视图移除。
- (void)removeLastItem{

    [self.tableViews.lastObject performSelector:@selector(removeFromSuperview) withObject:nil withObject:nil];
    [self.tableViews removeLastObject];
    
    [self.topTabbarItems.lastObject performSelector:@selector(removeFromSuperview) withObject:nil withObject:nil];
    [self.topTabbarItems removeLastObject];
}

//滚动到下级界面,并重新设置顶部按钮条上对应按钮的title
- (void)scrollToNextItem:(NSString *)preTitle{
    
    NSInteger index = self.contentView.contentOffset.x / HYScreenW;
    UIButton * btn = self.topTabbarItems[index];
    [btn setTitle:preTitle forState:UIControlStateNormal];
    [btn sizeToFit];
    [_topTabbar layoutIfNeeded];
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.contentSize = (CGSize){self.tableViews.count * HYScreenW,0};
        CGPoint offset = self.contentView.contentOffset;
        self.contentView.contentOffset = CGPointMake(offset.x + HYScreenW, offset.y);
        [self changeUnderLineFrame: [self.topTabbar.subviews lastObject]];
    }];
}


#pragma mark - <UIScrollView>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView != self.contentView) return;
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        NSInteger index = scrollView.contentOffset.x / HYScreenW;
        UIButton * btn = weakSelf.topTabbarItems[index];
        [weakSelf changeUnderLineFrame:btn];
    }];
}

#pragma mark - 开始就有地址时.

- (void)setAreaCode:(NSString *)areaCode{
    
    _areaCode = areaCode;
    //2.1 添加市级别,地区级别列表
    [self addTableView];
    [self addTableView];

    self.cityDataSouce = [[CitiesDataTool sharedManager] queryAllRecordWithShengID:[self.areaCode substringWithRange:(NSRange){0,2}]];
    self.districtDataSouce = [[CitiesDataTool sharedManager] queryAllRecordWithShengID:[self.areaCode substringWithRange:(NSRange){0,2}] cityID:[self.areaCode substringWithRange:(NSRange){2,2}]];//
  
    //2.3 添加底部对应按钮
    [self addTopBarItem];
    [self addTopBarItem];
    
    NSString * code = [self.areaCode stringByReplacingCharactersInRange:(NSRange){2,4} withString:@"0000"];
    NSString * provinceName = [[CitiesDataTool sharedManager] queryAllRecordWithAreaCode:code];
    UIButton * firstBtn = self.topTabbarItems.firstObject;
    [firstBtn setTitle:provinceName forState:UIControlStateNormal];
    
    NSString * cityName = [[CitiesDataTool sharedManager] queryAllRecordWithAreaCode:[self.areaCode stringByReplacingCharactersInRange:(NSRange){4,2} withString:@"00"]];
    UIButton * midBtn = self.topTabbarItems[1];
    [midBtn setTitle:cityName forState:UIControlStateNormal];
    
     NSString * districtName = [[CitiesDataTool sharedManager] queryAllRecordWithAreaCode:self.areaCode];
    UIButton * lastBtn = self.topTabbarItems.lastObject;
    [lastBtn setTitle:districtName forState:UIControlStateNormal];
    [self.topTabbarItems makeObjectsPerformSelector:@selector(sizeToFit)];
    [_topTabbar layoutIfNeeded];
    
    
    [self changeUnderLineFrame:lastBtn];
    
    //2.4 设置偏移量
    self.contentView.contentSize = (CGSize){self.tableViews.count * HYScreenW,0};
    CGPoint offset = self.contentView.contentOffset;
    self.contentView.contentOffset = CGPointMake((self.tableViews.count - 1) * HYScreenW, offset.y);

    [self setSelectedProvince:provinceName andCity:cityName andDistrict:districtName];
}

//初始化选中状态
- (void)setSelectedProvince:(NSString *)provinceName andCity:(NSString *)cityName andDistrict:(NSString *)districtName {
    
    for (AddressItem * item in self.dataSouce) {
        if ([item.name isEqualToString:provinceName]) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[self.dataSouce indexOfObject:item] inSection:0];
            UITableView * tableView  = self.tableViews.firstObject;
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
            [self tableView:tableView didSelectRowAtIndexPath:indexPath];
            break;
        }
    }
    
    for (int i = 0; i < self.cityDataSouce.count; i++) {
        AddressItem * item = self.cityDataSouce[i];
        
        if ([item.name isEqualToString:cityName]) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            UITableView * tableView  = self.tableViews[1];
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
            [self tableView:tableView didSelectRowAtIndexPath:indexPath];
            break;
        }
    }
    
    for (int i = 0; i <self.districtDataSouce.count; i++) {
        AddressItem * item = self.districtDataSouce[i];
        if ([item.name isEqualToString:districtName]) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            UITableView * tableView  = self.tableViews[2];
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
            [self tableView:tableView didSelectRowAtIndexPath:indexPath];
            break;
        }
    }
}

#pragma mark - getter 方法

//分割线
- (UIView *)separateLine{
    
    UIView * separateLine = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 1 / [UIScreen mainScreen].scale)];
    separateLine.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1];
    return separateLine;
}

- (NSMutableArray *)tableViews{
    
    if (_tableViews == nil) {
        _tableViews = [NSMutableArray array];
    }
    return _tableViews;
}

- (NSMutableArray *)topTabbarItems{
    if (_topTabbarItems == nil) {
        _topTabbarItems = [NSMutableArray array];
    }
    return _topTabbarItems;
}


//省级别数据源
- (NSArray *)dataSouce{
    
    if (_dataSouce == nil) {
       
        //_dataSouce = [[CitiesDataTool sharedManager] queryAllProvince];
        
        _dataSouce = [CitiesDataTool sharedManager].provinceArray;
    }
    return _dataSouce;
}
@end
