//
//  CollectionAddressSelectedViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/10/8.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "CollectionAddressSelectedViewController.h"
#import "Constants.h"

#import "CYAddressSelectedView.h"

#import "CTAPIBaseManager.h"

#import "SSCardCollectViewController.h"

@interface CollectionAddressSelectedViewController ()<UITextFieldDelegate>
{
    NSInteger selectedProvinceCode;
    NSInteger selectedCityCode;
    NSInteger selectedcountieCode;
}

@property (nonatomic, strong)UILabel *lb_province;
@property (nonatomic, strong)UITextField *tf_province;

@property (nonatomic, strong)UILabel *lb_city;
@property (nonatomic, strong)UITextField *tf_city;


@property (nonatomic, strong)UILabel *lb_counties;
@property (nonatomic, strong)UITextField *tf_counties;

@property (nonatomic, strong)UIButton *btn_confirm;

@property (nonatomic, strong)NSArray *array_province;

@property (nonatomic, strong)NSArray *array_city;

@property (nonatomic, strong)NSArray *array_counties;

@end

@implementation CollectionAddressSelectedViewController
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.lb_province];
    [self.view addSubview:self.tf_province];
    
    
    [self.view addSubview:self.lb_city];
    [self.view addSubview:self.tf_city];
    
    [self.view addSubview:self.lb_counties];
    [self.view addSubview:self.tf_counties];
    [self.view addSubview:self.btn_confirm];
    
    //获取plist文件
    NSURL *URL=[[NSBundle mainBundle]URLForResource:@"provinceAddressList" withExtension:@"plist"];
    //plist 文件为字典类型
    NSArray *province= [NSArray arrayWithContentsOfURL:URL];
   
    
    self.array_province = province;
    
    
    [self setupUI];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    [self.lb_province mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(30 + cl_kNavigationBarHeight);
        make.left.offset(30);
        make.width.offset(35);
        make.height.offset(40);
    }];
    
    [self.tf_province mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.lb_province.mas_right).offset(30);
        make.centerY.equalTo(self.lb_province);
        make.right.offset(-20);
        make.height.offset(40);
    }];
    
    [self.lb_city mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.lb_province.mas_bottom).offset(10);
        make.left.offset(30);
        make.width.offset(35);
        make.height.offset(40);
    }];
    
    [self.tf_city mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.lb_province.mas_right).offset(30);
        make.centerY.equalTo(self.lb_city);
        make.right.offset(-20);
        make.height.offset(40);
    }];
    
    
    [self.lb_counties mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.lb_city.mas_bottom).offset(10);
        make.left.offset(30);
        make.width.offset(35);
        make.height.offset(40);
    }];
    
    [self.tf_counties mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.tf_province);
        make.centerY.equalTo(self.lb_counties);
        make.right.offset(-20);
        make.height.offset(40);
    }];
    
    [self.btn_confirm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.right.offset(-10);
        make.bottom.offset(-30);
        make.height.offset(45);
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
    }];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithHex:0x4d4d4d],
                                                                      NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:17]}];
    
}


- (void)setupUI
{
    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)loadCityListApi:(NSDictionary *)dic
{
    NSString *url = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/city"];
    
    
    NSString *str1 = [NSString stringWithFormat:@"province_id=%@&province_name=%@&KkweInfo",[EnercryTool encryptUseDES: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: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"];
                        if ([dic[@"id"] isEqualToString:@"6"]) {
                            if (array.count == 14) {
                                NSMutableArray *cityArray = [[NSMutableArray alloc]initWithObjects:array[12], nil];
                                weakSelf.array_city = cityArray;
                                
                                return;
                            }
                        }else if ([dic[@"id"] isEqualToString:@"28"])
                        {
                            if (array.count == 14) {
                                NSMutableArray *cityArray = [[NSMutableArray alloc]initWithObjects:array[9], nil];
                                weakSelf.array_city = cityArray;
                                
                                return;
                            }
                        }
                        
                    }
                        weakSelf.array_city = 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)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];
    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]]) {
                        weakSelf.array_counties = responseObject[@"result"];
                    }else{
                        weakSelf.array_counties = 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:self.array_province  addressType:AddressTypeProvince resultBlock:^(NSDictionary * _Nonnull selectValue) {
            NSLog(@"采集省份:%@",selectValue);
            weakSelf.tf_province.text = selectValue[@"provice_name"];
            weakSelf.tf_city.text = @"";
            weakSelf.tf_counties.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:self.array_city addressType:AddressTypeCity resultBlock:^(NSDictionary * _Nonnull selectValue) {
            NSLog(@"采集城市:%@",selectValue);
            weakSelf.tf_city.text = selectValue[@"city_name"];
            weakSelf.tf_counties.text = @"";
            
            NSString *city_id = selectValue[@"city_id"];
            self->selectedCityCode = city_id.integerValue;
            
            [weakSelf loadCountiesListApi:selectValue];
        }];
    }else if (textField == self.tf_counties){
        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:self.array_counties  addressType:AddressTypeCounties resultBlock:^(NSDictionary * _Nonnull selectValue) {
             NSLog(@"采集区县:%@",selectValue);
            weakSelf.tf_counties.text = selectValue[@"county_name"];
            
            NSString *counties_id = selectValue[@"county_id"];
            self->selectedcountieCode = counties_id.integerValue;
                       
//                       [weakSelf loadCountiesListApi:selectValue];
        }];

    }
   
    
    return NO;
}


#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goToNextVCClick:(UIButton *)sender
{
    SSCardCollectViewController *vc = [[SSCardCollectViewController alloc]init];
    vc.title = @"社保卡采集";
    
    if (selectedProvinceCode == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择省份"];
        
        return;
    }
    if (selectedCityCode == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择城市"];
        
        return;
    }
    
    
    if (selectedcountieCode == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择区县"];
        
        return;
    }
    
    
    vc.selectedProvinceCode = selectedProvinceCode;
    vc.selectedCityCode = selectedCityCode;
    vc.selectedcountieCode = selectedcountieCode;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - getters and setters
- (UILabel *)lb_province
{
    if (!_lb_province) {
        _lb_province = [[UILabel alloc]init];
        _lb_province.text = @"省";
        _lb_province.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_province.font = [UIFont systemFontOfSize:15];
        _lb_province.textAlignment = NSTextAlignmentCenter;
    }
    return _lb_province;
}

- (UITextField *)tf_province
{
    if (!_tf_province) {
        _tf_province = [[UITextField alloc]init];
        _tf_province.placeholder = @"请选择省份";
        _tf_province.textColor = [UIColor colorWithHex:0x4d4d4d];
        _tf_province.font = [UIFont systemFontOfSize:15];
        _tf_province.textAlignment = NSTextAlignmentCenter;
        _tf_province.delegate = self;
        _tf_province.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _tf_province;
}

- (UILabel *)lb_city
{
    if (!_lb_city) {
        _lb_city = [[UILabel alloc]init];
        _lb_city.text = @"市";
        _lb_city.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_city.font = [UIFont systemFontOfSize:15];
        _lb_city.textAlignment = NSTextAlignmentCenter;
    }
    return _lb_city;
}

- (UITextField *)tf_city
{
    if (!_tf_city) {
        _tf_city = [[UITextField alloc]init];
        _tf_city.placeholder = @"请选择城市";
        _tf_city.textColor = [UIColor colorWithHex:0x4d4d4d];
        _tf_city.font = [UIFont systemFontOfSize:15];
        _tf_city.textAlignment = NSTextAlignmentCenter;
        _tf_city.delegate = self;
        _tf_city.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _tf_city;
}

- (UILabel *)lb_counties
{
    if (!_lb_counties) {
        _lb_counties = [[UILabel alloc]init];
        _lb_counties.text = @"区县";
        _lb_counties.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_counties.font = [UIFont systemFontOfSize:15];
        _lb_counties.textAlignment = NSTextAlignmentCenter;
    }
    return _lb_counties;
}

- (UITextField *)tf_counties
{
    if (!_tf_counties) {
        _tf_counties = [[UITextField alloc]init];
        _tf_counties.placeholder = @"请选择区县";
        _tf_counties.textColor = [UIColor colorWithHex:0x4d4d4d];
        _tf_counties.font = [UIFont systemFontOfSize:15];
        _tf_counties.textAlignment = NSTextAlignmentCenter;
        _tf_counties.delegate = self;
        _tf_counties.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _tf_counties;
}

- (UIButton *)btn_confirm
{
    if (!_btn_confirm) {
        _btn_confirm = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_confirm setTitle:@"确认" forState:UIControlStateNormal];
        [_btn_confirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btn_confirm.backgroundColor = K_MainColor;
        _btn_confirm.layer.cornerRadius = 5;
        [_btn_confirm addTarget:self action:@selector(goToNextVCClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_confirm;
}

/*
#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
