//
//  SSCardCollectSelectedAddressController.m
//  Open
//
//  Created by 雷俊博 on 2019/11/20.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SSCardCollectSelectedAddressController.h"
#import "UIView+frameAdjust.h"

#import "CYAddressSelectedView.h"

#import "CTAPIBaseManager.h"

@interface SSCardCollectSelectedAddressController ()<UITextFieldDelegate>
{
    NSArray *provinceArr;
    NSArray *cityArr;
    NSArray *countyArr;
    NSArray *townArr;
    NSArray *villageArr;
    
    
    NSInteger selectedProvinceCode;
    NSInteger selectedCityCode;
    NSInteger selectedcountieCode;
    NSInteger selectedTownCode;
    NSInteger selectedVillageCode;
}
@property (weak, nonatomic) IBOutlet UITextField *tf_province;
@property (weak, nonatomic) IBOutlet UITextField *tf_city;
@property (weak, nonatomic) IBOutlet UITextField *tf_county;
@property (weak, nonatomic) IBOutlet UITextField *tf_XZ;
@property (weak, nonatomic) IBOutlet UITextField *tf_cwh;
@property (weak, nonatomic) IBOutlet UITextField *tf_mph;
@property (weak, nonatomic) IBOutlet UITableView *tableView;



@end

@implementation SSCardCollectSelectedAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     [self confirmNavBav];
    
    [self loadProvince];
    

    
   
    
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    if ([keyPath isEqualToString:@"contentOffset"])

    {

        CGPoint offset = [change[NSKeyValueChangeNewKey] CGPointValue];
        
        NSLog(@"偏移量y:%f",offset.y);

    }

}

- (void)dealloc
{
    [self.tableView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    
}

- (void)confirmNavBav
{
    UIButton *btn_back = [UIButton buttonWithType:UIButtonTypeCustom];
    btn_back.frame = CGRectMake(0, 0, 60, 40);
    
    [btn_back setTitle:@"返回" forState:UIControlStateNormal];
    [btn_back setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    btn_back.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn_back setImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    [btn_back addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [btn_back layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btn_back];
    if ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7) {
        UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negativeSpacer.width = -15;
        self.navigationItem.leftBarButtonItems = @[negativeSpacer, backItem];
    }else{
        self.navigationItem.leftBarButtonItem = backItem;
    }
}
#pragma mark - load api

- (void)loadProvince
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/getProvince"];;
    
    
    NSLog(@"url:%@",url);
    [KKLoadingAnimationView show];
//
//       AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
//       manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//
//    [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [KKLoadingAnimationView dismiss];
//
//               if ([responseObject isKindOfClass:[NSData class]]) {
//                  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//
//                   NSLog(@"responseObject%@",dic);
//
//                   NSString *code = [NSString stringWithFormat:@"%@",dic[@"code"]];
//
//                   if ([code isEqualToString:@"0"]) {
//                       if ([dic[@"result"] isKindOfClass:[NSArray class]]) {
//                           self->provinceArr = dic[@"result"];
//                       }
//                   }else{
//                       [SVProgressHUD showInfoWithStatus:@"请求失败"];
//                   }
//               }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [KKLoadingAnimationView dismiss];
//        [SVProgressHUD showInfoWithStatus:@"无网络"];
//               NSLog(@"error:%@",error);
//    }];
    
    
    [NetworkRequest baseGet:url Params:nil Success:^(id _Nonnull responseObject) {
        
                [KKLoadingAnimationView dismiss];
               
                NSLog(@"responseObject%@",responseObject);
                
                NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
                
                if ([code isEqualToString:@"0"]) {
                    if ([responseObject[@"result"] isKindOfClass:[NSArray class]]) {
                        self->provinceArr = responseObject[@"result"];
                    }
                }else{
                    [SVProgressHUD showInfoWithStatus:@"请求失败"];
                }
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
    
    
    
}

//请求城市列表
- (void)loadCityListApi:(NSDictionary *)dic
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/city"];
    
    
    NSString *str1 = [NSString stringWithFormat:@"province_id=%@&province_name=%@&KkweInfo",[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"provice_id"]]  key:@"KkweFace95271124"],[EnercryTool encryptUseDES:dic[@"provice_name"] key:@"KkweFace95271124"]];
    
     str1 =  [MyMD5 md5:str1];
    
    NSDictionary *params = @{
                             @"province_name":[EnercryTool encryptUseDES:dic[@"provice_name"] key:@"KkweFace95271124"],
                             @"province_id":[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"provice_id"]]  key:@"KkweFace95271124"],
                             @"flag":@2,
                             @"sign":str1
                             };
    
    NSLog(@"社保卡采集地址城市api:%@",url);
    NSLog(@"社保卡采集地址城市params:%@",params);
    
    NSLog(@"请求开始:");
    
    [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"];
                        self->cityArr = array;
                        return;
                        
                    }
                
                    
                }else{
                    self->cityArr = nil;
                    
                    [SVProgressHUD showInfoWithStatus:@"请求失败"];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器异常"];
            }
            
           
            
            NSLog(@"请求结束responseObject:%@",responseObject);
        }
        
    } Failure:^(NSError * _Nonnull error) {
        
        [KKLoadingAnimationView dismiss];
        
        if (error) {
            
            NSLog(@"请求失败error:%@",error);
            [SVProgressHUD showInfoWithStatus:@"请求失败"];
            return ;
        }
        
    }];
}

//请求区县列表
- (void)loadCountiesListApi:(NSDictionary *)dic
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/county"];
    
    
    NSString *str1 = [NSString stringWithFormat:@"city_id=%@&city_name=%@&KkweInfo",[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"city_id"]]  key:@"KkweFace95271124"],[EnercryTool encryptUseDES:dic[@"city_name"] key:@"KkweFace95271124"]];
    
    str1 =  [MyMD5 md5:str1];
    
    NSDictionary *params = @{
                             @"city_name":[EnercryTool encryptUseDES:dic[@"city_name"] key:@"KkweFace95271124"],
                             @"city_id":[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"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->countyArr = responseObject[@"result"];
                    }else{
                        self->countyArr = nil;
                    }

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

- (void)loadTownListApi:(NSDictionary *)dic
{
    
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/town"];
    
     NSString *str1 = [NSString stringWithFormat:@"county_id=%@&county_name=%@&KkweInfo",[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"county_id"]]  key:@"KkweFace95271124"],[EnercryTool encryptUseDES:dic[@"county_name"] key:@"KkweFace95271124"]];
    
    str1 =  [MyMD5 md5:str1];
       
    NSDictionary *params = @{
                                @"county_name":[EnercryTool encryptUseDES:dic[@"county_name"] key:@"KkweFace95271124"],
                                @"county_id":[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"county_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->townArr = responseObject[@"result"];
                    }else{
                        self->townArr = nil;
                    }

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


- (void)loadVillageListApi:(NSDictionary *)dic
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/village"];
    
     NSString *str1 = [NSString stringWithFormat:@"town_id=%@&town_name=%@&KkweInfo",[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"town_id"]]  key:@"KkweFace95271124"],[EnercryTool encryptUseDES:dic[@"town_name"] key:@"KkweFace95271124"]];
    
    str1 =  [MyMD5 md5:str1];
       
    NSDictionary *params = @{
                                @"town_name":[EnercryTool encryptUseDES:dic[@"town_name"] key:@"KkweFace95271124"],
                                @"town_id":[EnercryTool encryptUseDES:[NSString stringWithFormat:@"%@",dic[@"town_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->villageArr = responseObject[@"result"];
                    }else{
                        self->villageArr = 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 - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    WeakSelf
    if (textField == self.tf_province) {
        [CYAddressSelectedView showAddressPickerWithTitle:@"请选择省份" data:provinceArr addressType:AddressTypeProvince resultBlock:^(NSDictionary * _Nonnull selectValue) {
                   NSLog(@"采集省份:%@",selectValue);
                   weakSelf.tf_province.text = selectValue[@"provice_name"];
                   weakSelf.tf_city.text = @"";
                   weakSelf.tf_county.text = @"";
                   weakSelf.tf_XZ.text = @"";
                   weakSelf.tf_cwh.text = @"";
                   weakSelf.tf_mph.text = @"";
                   
                   
                   NSString *provice_id = selectValue[@"provice_id"];
                   self->selectedProvinceCode = provice_id.integerValue;
                   
                   [weakSelf loadCityListApi:selectValue];
               }];
    }else if (textField == self.tf_city){
        if (self.tf_province.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:@"请先选择省份"];
            return NO;
        }
        [CYAddressSelectedView showAddressPickerWithTitle:@"请选择城市" data:cityArr addressType:AddressTypeCity resultBlock:^(NSDictionary * _Nonnull selectValue) {
            NSLog(@"采集城市:%@",selectValue);
            weakSelf.tf_city.text = selectValue[@"city_name"];
            weakSelf.tf_county.text = @"";
            weakSelf.tf_XZ.text = @"";
            weakSelf.tf_cwh.text = @"";
            weakSelf.tf_mph.text = @"";
            
            NSString *city_id = selectValue[@"city_id"];
            self->selectedCityCode = city_id.integerValue;
            
            [weakSelf loadCountiesListApi:selectValue];
        }];
    }else if (textField == self.tf_county){
        
            if (self.tf_province.text.length == 0) {
                [SVProgressHUD showInfoWithStatus:@"请先选择省份"];
                return NO;
            }
            
            if (self.tf_city.text.length == 0) {
                [SVProgressHUD showInfoWithStatus:@"请先选择城市"];
                return NO;
            }
            [CYAddressSelectedView showAddressPickerWithTitle:@"请选择区县" data:countyArr addressType:AddressTypeCounties resultBlock:^(NSDictionary * _Nonnull selectValue) {
                 NSLog(@"采集区县:%@",selectValue);
                weakSelf.tf_county.text = selectValue[@"county_name"];
                weakSelf.tf_XZ.text = @"";
                weakSelf.tf_cwh.text = @"";
                weakSelf.tf_mph.text = @"";
                
                NSString *counties_id = selectValue[@"county_id"];
                self->selectedcountieCode = counties_id.integerValue;
                           
                           [weakSelf loadTownListApi:selectValue];
            }];

    }else if (textField == self.tf_XZ){
        if (self.tf_province.text.length == 0)
        {
            [SVProgressHUD showInfoWithStatus:@"请先选择省份"];
            return NO;
        }
                   
        if (self.tf_city.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:@"请先选择城市"];
            return NO;
        }
        if (self.tf_county.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:@"请先选择区县"];
            return NO;
        }
        
        [CYAddressSelectedView showAddressPickerWithTitle:@"请选择乡镇" data:townArr addressType:AddressTypeTown resultBlock:^(NSDictionary * _Nonnull selectValue) {
             NSLog(@"采集区县:%@",selectValue);
            weakSelf.tf_XZ.text = selectValue[@"town_name"];
            weakSelf.tf_cwh.text = @"";
            weakSelf.tf_mph.text = @"";
            
            NSString *town_id = selectValue[@"town_id"];
            self->selectedTownCode = town_id.integerValue;
                       
            [weakSelf loadVillageListApi:selectValue];
        }];
    }else if (textField == self.tf_cwh){
        if (self.tf_province.text.length == 0)
        {
            [SVProgressHUD showInfoWithStatus:@"请先选择省份"];
            return NO;
        }
                   
        if (self.tf_city.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:@"请先选择城市"];
            return NO;
        }
        if (self.tf_county.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:@"请先选择区县"];
            return NO;
        }
        if (self.tf_XZ.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:@"请先选择乡镇"];
            return NO;
        }
        
        [CYAddressSelectedView showAddressPickerWithTitle:@"请选择村委会" data:villageArr addressType:AddressTypeVillage resultBlock:^(NSDictionary * _Nonnull selectValue) {
             NSLog(@"采集区县:%@",selectValue);
            weakSelf.tf_cwh.text = selectValue[@"village_name"];
            weakSelf.tf_mph.text = @"";
            
            NSString *town_id = selectValue[@"village_id"];
            self->selectedVillageCode = town_id.integerValue;
                       
            //[weakSelf loadVillageListApi:selectValue];
        }];
        
    }
    
    if (textField == self.tf_mph) {
        return YES;
    }
    
    return NO;
}










#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)btnClick:(UIButton *)sender {
    
    if (self.tf_province.text.length == 0)
    {
        [SVProgressHUD showInfoWithStatus:@"请先选择省份"];
        return ;
    }
               
    if (self.tf_city.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请先选择城市"];
        return ;
    }
    if (self.tf_county.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请先选择区县"];
        return ;
    }
    if (self.tf_XZ.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请先选择乡镇"];
        return ;
    }
    
    if (self.tf_cwh.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请先选择村委会"];
        return ;
    }
    
    if (self.tf_mph.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入门牌号"];
        return ;
    }
    
    
    NSString *addressStr = [NSString stringWithFormat:@"%@%@%@%@%@%@",self.tf_province.text,self.tf_city.text,self.tf_county.text,self.tf_XZ.text,self.tf_cwh.text,self.tf_mph.text];
    
    if (self.block) {
        self.block(addressStr);
    }
    
    [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
