//
//  chooseAddressViewController.m
//  Open
//
//  Created by 看看智能 on 2018/1/18.
//  Copyright © 2018年 黄江涛 . All rights reserved.
//

#import "chooseAddressViewController.h"


@interface chooseAddressViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)addressGatherModel *addressModel;
@end


@implementation chooseAddressViewController
{
    __block  NSString *static_province;
    __block  NSString *static_city;
    __block  NSString *static_downTown;
    __block  NSString *static_area;
    __block  NSString *static_village;
    __block  NSString *static_villageCommittee;
    
}
-(addressGatherModel *)addressModel
{
    if(!_addressModel){
        _addressModel =[[addressGatherModel alloc]initWithViewController:self];
        _addressModel.stringChoose = self.stringChoose;
    }
    return _addressModel;
    
}


+ (FirstPersonInformationViewController *)sharedInstance{
    static FirstPersonInformationViewController *p = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        p=[sb instantiateViewControllerWithIdentifier:@"FirstPersonInformationViewController"];
    });
    return p;
}

#pragma mark - view


-(void)enterDate{


    
    //取数据二的
    NSArray *result_2 = [CWSqliteModelTool queryAllModels:[workTypeSelectionNSObject class]];
    if (result_2.count == 0) {
        jobXML *parser = [jobXML new];
        parser.xmlName =@"workTypeSelection";
        NSString *path = [[NSBundle mainBundle]pathForResource:@"workTypeSelection" ofType:@"xml"];
        NSArray *arrddd = [parser parseWithPath:path];
        for (workTypeSelectionNSObject *person in arrddd) {
            [HJTsqlite addDate:person];
        }
    }
    
    
    
    
     NSArray *result = [CWSqliteModelTool queryAllModels:[PersonJob class]];
    if (result.count == 0) {
        jobXML *parser = [jobXML new];
        NSString *path = [[NSBundle mainBundle]pathForResource:@"JobGatherStrings" ofType:@"xml"];
        NSArray *arr = [parser parseWithPath:path];
        
        for (PersonJob *person in arr) {
            [HJTsqlite addDate:person];
        }
        
        //将数据压缩
        

        
        
        
        
//        NSArray *result = [CWSqliteModelTool queryAllModels:[PersonJob class]];
//          AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
//        if (result.count > 0 && delegate.numberXMLArray.count ==0) {
//            [delegate.numberXMLArray  removeAllObjects];
//            for (PersonJob *PersonModel   in result) {
//                        NSData *data =[NSKeyedArchiver archivedDataWithRootObject:PersonModel.politicalStatus];
//                        [delegate.numberXMLArray addObject:data];
//    
//            }
//            
//            
//         
//        }
        

        
    }
//     NSArray *result_2 = [CWSqliteModelTool queryAllModels:[PersonJob class]]; //不到不要改2018月4月26奚大大生日 
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    if (result.count > 0 && delegate.numberXMLArray.count ==0) {
        [delegate.numberXMLArray  removeAllObjects];
        for (PersonJob *PersonModel   in result) {
            //                NSData *data =[NSKeyedArchiver archivedDataWithRootObject:PersonModel];
            [delegate.numberXMLArray addObject:PersonModel];
        }
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择地址";
     SVProgressHUD.minimumDismissTimeInterval =1.0;
    [self enterDate];

    [self allDelegateAndAllZero:self.province];
    [self allDelegateAndAllZero:self.downTown];
    [self allDelegateAndAllZero:self.area];
    [self allDelegateAndAllZero:self.village];
    [self allDelegateAndAllZero:self.villageCommittee];
    [self allDelegateAndAllZero:self.door];
    [self allDelegateAndAllZero:self.searchTime];
    
    [self UserNumber];
    [self jianting];
    [self search];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"dont"];

    
    [self navConfig];

}
-(void)search{
    if (self.isSearch == YES) {
        self.searchLab.text =@"查询时间";
        self.searchLab.font =[UIFont systemFontOfSize:14];
        self.door.hidden =YES;
        self.searchTime.hidden =NO;
        
        self.village.text =nil;
        self.area.text =nil;
        self.downTown.text =nil;
     static_city = static_village =static_villageCommittee =static_area=nil;
        
    }else{
        self.searchLab.text =@"门牌号";
        self.searchLab.font =[UIFont systemFontOfSize:17];
        self.door.hidden =NO;
         self.searchTime.hidden =YES;
    }
    
    
}

- (void)navConfig {
    if ([self.stringChoose isEqualToString:@"stringChoose"]) {
        UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setTitle:@"返回" forState:UIControlStateNormal];
        [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
        [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        backBtn.frame = CGRectMake(0, 0, 60, 44);
        [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:8];
        [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem*backItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
        
        self.navigationItem.leftBarButtonItem = backItem;
    }
}


-(void)allDelegateAndAllZero:(UITextField*)textField{
    //[self addShadowToView:textField withColor:[UIColor redColor]];
    textField.delegate =self;
    textField.textAlignment =NSTextAlignmentCenter;

}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self jiantingKeyBoard];

    self.villageCommittee.text =@"";
    
    //test

}




-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField{
    
 
   
    if (textField !=  self.door) {
           [self provinceChoose:textField];
         [textField resignFirstResponder];
        return NO;
    }else{
        
       return YES;
    }
   
}





- (IBAction)provinceChoose:(UITextField *)sender {
    //     [self show1:sender];
    if (sender == self.province) {
        [self.view endEditing:YES];
        [self provinceLogic];
//        indexTag =1;

    }else if(sender == self.downTown)
    {[self.view endEditing:YES];
        [self downTownLogic];

    }else if (sender == self.area)
    {
        [self.view endEditing:YES];
        [self areaLogic];
    }else if (sender == self.village)
    {[self.view endEditing:YES];
        [self villageLogic];
        
        
    }else if (sender ==self.villageCommittee)
    {[self.view endEditing:YES];
        [self VillageCommitLogic];
    }else if (sender ==self.searchTime){
        [self.view endEditing:YES];
        [self timmer];
        
    }

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (IBAction)didend:(UITextField *)sender {
   
    if (sender !=  self.door) {
    
         [self.view endEditing:YES];
    }
}
#pragma mark - AllCityLogic
- (void)provinceLogic{
  
    [self.addressModel getProvinceHandle:^(NSString *str1, NSString *str2, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
           // self.province.text = str1;
            self.province.text=str1;
//            if ([_stringChoose isEqualToString:@"stringChoose"]) {
//                self.province.text=str1;
//            }else{
//               self.province.text=@"贵州省";
//            }
            NSLog(@"%@",str2);
            static_province = str2;
            static_city =nil;
            static_downTown=nil;
            static_area =nil;
            static_village =nil;
           static_villageCommittee =nil;
            self.downTown.text = @"";
            self.area.text =@"";
            self.village.text =@"";
            self.villageCommittee.text =@"";
            self.door.text =@"";
             [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"dont"];
        });
    }];
}
-(void)downTownLogic{
//    if ([_stringChoose isEqualToString:@"stringChoose"]) {
//
//    }else{
//           static_province =@"520";
//    }
    
 
    if (!static_province ) {
        return;    }
    NSLog(@"%@",static_province);
    [self.addressModel getDownTown:static_province Handle:^(NSString *str1, NSString *str2, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.downTown.text = str1;
            static_downTown =str2;

           static_area =nil;
          static_village =nil;
          static_villageCommittee =nil;
            self.area.text =@"";
            self.village.text =@"";
            self.villageCommittee.text =@"";
             self.door.text =@"";
            if (self.isSearch ==YES)
                [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"next"];
            else
                [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"dont"];
        });
    }];
}
-(void)areaLogic{
    if (!static_downTown ) {
        return;
    }
NSLog(@"%@",static_downTown);
    [self.addressModel getArea:static_downTown  Handle:^(NSString *str1, NSString *str2, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.area.text = str1;
            static_area =str2;

            static_village =nil;
            static_villageCommittee =nil;
            self.village.text =@"";
            self.villageCommittee.text =@"";
             self.door.text =@"";
            if (self.isSearch ==YES)
                [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"next"];
            else
                [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"dont"];
        });
    }];
    
}
-(void)villageLogic{
    if (!static_area ) {
        return;
    }
    NSLog(@"%@",static_area);
    [self.addressModel getVillage:static_area Handle:^(NSString *str1, NSString *str2, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.village.text =str1;
            static_village = str2;
            static_villageCommittee =nil;
            self.villageCommittee.text =@"";
             self.door.text =@"";
       
            if (self.isSearch ==YES)
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"next"];
 else
          [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"dont"];
        });
        
    }];
    
}
-(void)VillageCommitLogic{
    if (!static_village ) {
        return;
    }
    NSLog(@"%@",static_village);
    [self.addressModel getVillageCommitee:static_village Handle:^(NSString *str1, NSString *str2, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.villageCommittee.text = str1;
            static_villageCommittee = str2;
             self.door.text =@"";
       
                [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanNextButtom" object:@"next"];
            
            
           
        });
        
    }];
    
}
-(void)timmer{
    
    __weak typeof(self) wself = self;
    [LYLDatePicker showDateDetermineChooseInView:self.view determineChoose:^(NSString *dateString) {
        dispatch_async(dispatch_get_main_queue(), ^{
            wself.searchTime.text = dateString;
        });
    }];
    
}

-(void)jianting{
    [self jiantingALL];
     __weak typeof(self) wself = self;
    self.nextB  = ^(BOOL isNext) {
        //按钮的
        if (isNext == YES) {
            wself.jumpToPhoto.userInteractionEnabled = YES;
            wself.jumpToPhoto.backgroundColor =kRGBColor(25, 149, 107);
            [wself.jumpToPhoto addTarget:wself action:@selector(enterMethod) forControlEvents:UIControlEventTouchUpInside];
        }else{
            wself.jumpToPhoto.userInteractionEnabled = NO;
            wself.jumpToPhoto.backgroundColor =kRGBColor(191, 191, 191);
        }
    };
}
-(void)UserNumber{
    

//    jobResultModel *jv = [jobResultModel new];
//    jv.jobSecondKey =1;
//  jobResultModelResult *asd =  jv.modelresult;
//    asd.resultModelaa = @"asdfasdf";
//    jv.modelresult.resultModelaa =asd.resultModelaa;
//    [HJTsqlite addDate:jv];
    //增加数据库
    NSArray *result = [CWSqliteModelTool queryAllModels:[citySqliteModel class] uid:nil targetId:nil];
    

    
    NSLog(@"查询结果: %@",result);
    
    
    
            NSArray * arrayHjt =  [HJTsqlite selectData:2 andModel:[citySqliteModel class] andName:@"CityId"];
 NSLog(@"查询结果: %ld",(long)[HJTsqlite selectData:2 andModel:[citySqliteModel class] andName:@"CityId"].count);
    if ( arrayHjt.count == 0) {
    }else{
        for (citySqliteModel * models in arrayHjt) {
            self.province.text = models.province;
            self.downTown.text = models.downTown;
            self.area.text = models.area;
            self.village.text = models.village;
            self.villageCommittee.text =models.villageCommittee;
            static_province= models.Staticprovince;
            static_downTown = models.StaticdownTown;
            static_area =models.Staticarea;
            static_village =models.StaticVillage;
            
        }
   
        
        
        
    }
    self.villageCommittee.text =@"";
     self.door.text =@"";
    
}


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

#pragma mark - NextVC
-(void)enterMethod{

    NSString* ing = 0;

    if ([self.searchTime.text isEqualToString:@""]) {
        ing  = @"";
    }else{
        ing =[JobUtil onlyBirthDai:self.searchTime.text];
    }
    
    if (self.isSearch == YES) {
        [SVProgressHUD show];

        
        
        [PersonGatherJobNetManager searchItem:ing andProvonce:nil andCity:static_downTown andCountry:static_area andTown:static_village andVillage:static_villageCommittee completionHandle:^(NewMessage *model, NSError *error) {
        
    
            [SVProgressHUD dismiss];
            if (error ) {
                return ;
            }
            if (model.state == 0) {
                
                UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"已经采集了%ld条",(long)model.result] message:nil preferredStyle:UIAlertControllerStyleAlert];
               // __weak __typeof(self)weakSelf = self;

                [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                }]];
                [self presentViewController:alertCon animated:YES completion:nil];
                
                
                
                
            }
            
            
            
            
            
        }];

        return;
    }
    
    
    
    
    
    if ([_stringChoose isEqualToString:@"stringChoose"]) {
//更新数据库
//        citySqliteModel *cityModel  = [[citySqliteModel alloc]init];
//        cityModel.CityId =1;
//        cityModel.province = self.province.text ;
//        cityModel.downTown =self.downTown.text;
//        cityModel.area =self.area.text;
//        cityModel.village =self.village.text;
//        cityModel.villageCommittee =self.villageCommittee.text;
//         [HJTsqlite addDate:cityModel];
        
        [self.delegate sendCityToFirstInfornation:self senderProvince:self.province.text senderDownTown:self.downTown.text senderArea:self.area.text senderVillage:self.village.text senderVillageCommit:self.villageCommittee.text senderDoor:self.door.text];
        [self dismissViewControllerAnimated:YES completion:^{
        
        }];
        
    }else{
        FirstPersonInformationViewController*once  = [Storyboard instantiateViewControllerWithIdentifier:@"FirstPersonInformationViewController"];
        once.hidesBottomBarWhenPushed =YES;
         citySqliteModel *cityModel  = [[citySqliteModel alloc]init];
            cityModel.CityId =1;
            cityModel.province = self.province.text ;
            cityModel.downTown =self.downTown.text;
            cityModel.area =self.area.text;
            cityModel.village =self.village.text;
            cityModel.villageCommittee =self.villageCommittee.text;
            cityModel.Staticprovince =static_province;
            cityModel.StaticdownTown =static_downTown;
            cityModel.Staticarea =static_area;
            cityModel.StaticVillage =static_village;
        cityModel.StaticVillageCommitte =static_villageCommittee;
            [HJTsqlite addDate:cityModel];

        
        
        [self.navigationController pushViewController:once animated:YES];
        
        
    }
    
    
    
    
    
    
    
    
    
}

#pragma mark - 添加阴影
/// 添加四边阴影效果
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 6;
}



#pragma mark -销毁监听
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"KankanNextButtom" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    

}

-(void)jiantingKeyBoard
{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
}

#pragma mark ---- 根据键盘高度将当前视图向上滚动同样高度
///键盘显示事件
- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = kbHeight;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

#pragma mark ---- 当键盘消失后，视图需要恢复原状
///键盘消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}







@end
