//
//  HXProvincialCitiesCountiesPickerview.m
//  HXProvincialCitiesCountiesPickerview
//  github:https://github.com/huangxuan518 博客：blog.libuqing.com
//  Created by 黄轩 on 16/7/8.
//  Copyright © 2016年 黄轩. All rights reserved.
//

#import "HXProvincialCitiesCountiesPickerview.h"
#import "HXAddressManager.h"
//调整屏幕具体宽度
#define SHAddressPickerViewHeight 445
#define SHAddressPickerView 320
//调整字体大小
#define SIZEFONT 25

static NSString  *number;
//static NSInteger *tagChangeFOrNumber;

@interface HXProvincialCitiesCountiesPickerview () <UIPickerViewDataSource,UIPickerViewDelegate>
{


}
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,strong) UIView *headView;
@property (strong, nonatomic) UIPickerView *pickView;
@property (strong,nonatomic) NSMutableArray *firstAry;//一级数据源
@property (strong,nonatomic) NSArray *secondAry;//二级数据源
@property (strong,nonatomic) NSArray *thirdAry;//三级数据源
@property (nonatomic,assign) NSInteger firstCurrentIndex;//第一行当前位置
@property (nonatomic,assign) NSInteger secondCurrentIndex;//第二行当前位置
@property (nonatomic,assign) NSInteger thirdCurrentIndex;//第三行当前位置
@property(nonatomic,strong)	 NSString * NumberTag;//
@property(nonatomic)NSInteger intTage;
@end

@implementation HXProvincialCitiesCountiesPickerview

-(NSMutableArray *)firstAry
{
    if (!_firstAry) {
        _firstAry =[NSMutableArray array];
    }
    return _firstAry;
}


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

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self internalConfig];
    }
    return self;
}

- (void)internalConfig {
    //一开始为no

    
    _backView = [[UIView alloc] initWithFrame:self.frame];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.6;
    [self addSubview:_backView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [_backView addGestureRecognizer:tap];
    
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.pickView];
    
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, self.pickView.frame.origin.y - 43.5, self.frame.size.width, 43.5)];

    
    _headView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(5, 0, 43.5, 43.5);
    button.backgroundColor = [UIColor clearColor];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:[UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(cancleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:button];
    
    if (self.intTage == 100) {
        button.selected =NO;
    }else{
        button.selected =YES;
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(self.frame.size.width - 35, 0, 32, 43.5);
    button.backgroundColor = [UIColor clearColor];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:[UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(completionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:button];
    
    [self addSubview:_headView];
    }
}

- (void)showPickerWithProvinceName:(NSString *)provinceName cityName:(NSString *)cityName countyName:(NSString *)countyName index:(NSInteger)index
{
    
    switch (index) {
        case 1:
              _firstAry = kAddressManager.provinceDicAry;
            _intTage =0;
            break;
            
       case 2:
            [self method1];
           
            break;
            
            case 3:
            [self method2];
            break;
            
        default:
            break;
    }
//    if (provinceName.length > 0) {
//        [_firstAry enumerateObjectsUsingBlock:^(NSDictionary *provinceDic, NSUInteger idx, BOOL * _Nonnull stop) {
//   
//                _firstCurrentIndex = idx+1;
//            
//            
//        }];
//    }
   
    [self.pickView reloadComponent:0];
    [self.pickView selectRow:_firstCurrentIndex inComponent:0 animated:NO];
    
   
    [self show];
}
-(void)method1
{
 [_firstAry removeAllObjects];
    NSUserDefaults *userDefaults =  [NSUserDefaults standardUserDefaults];
//    _firstAry =[userDefaults objectForKey:];
  _firstAry =  [NSMutableArray arrayWithArray:[userDefaults objectForKey:@"myCityModel"]];
    
    NSUserDefaults *userDefatlutk = [NSUserDefaults standardUserDefaults];
    [userDefatlutk removeObjectForKey:@"myCityModel"];
    [userDefatlutk synchronize];
   _intTage = 1;

}
-(void)method2
{
    [_firstAry removeAllObjects];
    NSUserDefaults *userDefaults =  [NSUserDefaults standardUserDefaults];
  _firstAry =  [NSMutableArray arrayWithArray:[userDefaults objectForKey:@"myCityModel"]];
        NSUserDefaults *userDefault =  [NSUserDefaults standardUserDefaults];
    [userDefault removeObjectForKey:@"myCityModel"];
    [userDefault synchronize];
    _intTage =1;

}



- (void)show {
    self.hidden = NO;
    number =0;
    _backView.alpha = 0.6;
    [UIView animateWithDuration:0 animations:^{
        if ([UIScreen mainScreen].bounds.size.height == 480) {
                    self.pickView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - SHAddressPickerView, self.frame.size.width, SHAddressPickerView);
        }else{
                   self.pickView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - SHAddressPickerViewHeight, self.frame.size.width, SHAddressPickerViewHeight);
        }
        

        
        
        
        _headView.frame = CGRectMake(0, self.pickView.frame.origin.y - 43.5, self.frame.size.width, 43.5);
        
//        [self.pickView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo([UIScreen mainScreen].bounds.size.height - SHAddressPickerViewHeight);
//            make.size.mas_equalTo(CGSizeMake( [UIScreen mainScreen].bounds.size.width, 400));
//        }];
//        [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.pickView.mas_top).mas_equalTo(-43.5);
//            make.size.mas_equalTo(CGSizeMake( [UIScreen mainScreen].bounds.size.width, 43.5));
//        }];
//        
        
        
        
    }];
}

- (void)hide {
    _backView.alpha = 0;
    [UIView animateWithDuration:0 animations:^{

        if ([UIScreen mainScreen].bounds.size.height == 480) {
        self.pickView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height+44, self.frame.size.width, SHAddressPickerView);
        }else{
        self.pickView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height+44, self.frame.size.width, SHAddressPickerViewHeight);
        }
        _headView.frame = CGRectMake(0, self.pickView.frame.origin.y, self.frame.size.width, 43.5);
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
  
}

#pragma mark - UIPickerViewDataSource,UIPickerViewDelegate

//选项默认值
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated {
//    animated =NO;
    return ;

    
}
//设置列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
    return 1;
    
  
}

//返回数组总数
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {

        return _firstAry.count+1;
    
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

//
//    if (component  == 0) {
//
//        if () {
//            
//        }
        
        

    
        if (row > 0) {
            if (row - 1 < _firstAry.count)
            {
    return _firstAry[row - 1];
            }
        }
     return @"请选择";
  }

//}
//触发事件

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
     [self.pickView reloadAllComponents];
    
    self.isgettingSelect =YES;
    
    if (component == 0) {
        if (row == 0) {
            _firstCurrentIndex = 0;
        }else
     
        if(row > 0){

        _firstCurrentIndex = row-1;
        if ( _intTage == 0) {
            NSUserDefaults *userDefaults =  [NSUserDefaults standardUserDefaults];
               NSMutableArray *mutableArr =  [NSMutableArray arrayWithArray:[userDefaults objectForKey:@"myPrivinceModel"]];
             if (mutableArr.count >0 && row <= mutableArr.count ){
                if (mutableArr.count > 1) {
                    NSString *city =  [NSKeyedUnarchiver unarchiveObjectWithData:mutableArr[row-1]];
                    NSLog(@"监听到的城市名是:%@", city);
                    number =city;
                }else{
                    NSString *city =  [NSKeyedUnarchiver unarchiveObjectWithData:mutableArr[row]];
                    NSLog(@"监听到的城市名是:%@", city);
                    number =city;
                }
                
            
            }else
            {
                number = 0;
            }
        
            
        }else if(_intTage == 1)
        {
            
     
            
           
                NSUserDefaults *userDefaults =  [NSUserDefaults standardUserDefaults];
                NSMutableArray *mutableArr =  [NSMutableArray arrayWithArray:[userDefaults objectForKey:@"myCityModelID"]];
            if (mutableArr.count >0 && row <= mutableArr.count ){
                NSString *city =  [NSKeyedUnarchiver unarchiveObjectWithData:mutableArr[row-1]];
                NSLog(@"监听到的城市名是:%@", city);
                number =city;
            }else
            {
                number = 0;
            }
            
            if (row == 0) {
                
            }
            
            
            
            [userDefaults removeObjectForKey:@"myCityModel"];
         

   }
        }
      
}
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:SIZEFONT]];
    }
    // Fill the label text here

    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)completionButtonAction:(UIButton *)sender {
    
    NSString *provinceName = @"";

    
    if (_firstAry.count > 0 ) {
        if (_firstCurrentIndex > 0) {
            if (_firstCurrentIndex-1 < _firstAry.count  && self.isgettingSelect == YES ) {
                //获取省
                provinceName = _firstAry[_firstCurrentIndex ];
                self.isgettingSelect =NO;
            }else
            {
                provinceName = _firstAry[0];
                self.isgettingSelect =NO;
           
                
                
            }
        }else{
          provinceName = _firstAry[0];
            self.isgettingSelect =NO;
         
        }
    }

  
         if(number ==0 && _firstAry.count == 0){
            self.NumberTag = 0;
         //   [SVProgressHUD showErrorWithStatus:@"网络状态不佳"];
        }else if(_firstAry.count >0 && number >0){
        self.NumberTag =number;
        }else if(_firstAry.count > 0 && number ==0 ){
                NSUserDefaults *userDefaults =  [NSUserDefaults standardUserDefaults];
                NSMutableArray *mutableArr =  [NSMutableArray arrayWithArray:[userDefaults objectForKey:@"myCityModelID"]];
            if (mutableArr.count >0 &&  self.isgettingSelect == NO) {
                    NSString *city =  [NSKeyedUnarchiver unarchiveObjectWithData:mutableArr[0]];
                    NSLog(@"监听到的城市名是:%@", city);
                    self.NumberTag =city;
            }
            
        }

    if (_completion ) {
  
        
        _completion(provinceName,self.NumberTag,nil);
        
       
       
    }else if ( _completion_int){
         _completion_int(provinceName);
    }
    
    //雷俊博
//    if (![provinceName isEqualToString:@"请选择"] && provinceName) {
//         [getPeopleID getprovinceNightSix:provinceName];
//    }
    
    
    [self hide];

}

- (void)cancleButtonAction:(UIButton *)sender {
    self.isgettingSelect =NO;
    [self hide];
}

#pragma mark - 懒加载

- (UIPickerView*)pickView {
    if (!_pickView) {

        if ([UIScreen mainScreen].bounds.size.height == 480) {
                  _pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44, self.frame.size.width, SHAddressPickerView)];
        }else{
                   _pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44, self.frame.size.width, SHAddressPickerViewHeight)];
        }
        
        _pickView.delegate = self;
        _pickView.dataSource = self;
        _pickView.backgroundColor = [UIColor whiteColor];
        [_pickView selectRow:0 inComponent:0 animated:NO];
    }
    return _pickView;
}

@end
