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

#import "FirstPersonInformationViewController.h"
#import "testObject.h"
@interface FirstPersonInformationViewController ()<UITextFieldDelegate,UIScrollViewDelegate,chooseAddressViewcontrollerDelegate>
{
  __block  int  sexKK;
 __block   int  nationKK;
}
@end

@implementation FirstPersonInformationViewController
//实例




-(addressGatherModel *)addressModel
{
    if(!_addressModel){
        _addressModel =[[addressGatherModel alloc]initWithViewController:self];
    }
    return _addressModel;
    
}
//所有选择数据
-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr =[NSMutableArray array];
        NSArray *result = [CWSqliteModelTool queryAllModels:[PersonJob class]];
        if (result.count > 0) {
            _dataArr = [NSMutableArray arrayWithArray:result];
        }
        
    }
    return _dataArr;
}
#pragma mark - View
+ (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;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
   [MobClick beginLogPageView:@"就业采集"];
   [JANALYTICSService startLogPageView:@"就业采集"];
    
    if (![[self ocrImageStr] isEqualToString:@""] && [self.personAddress.text isEqualToString:@""] ) {
        self.personName.text = [self ocrName];
        self.personID.text =[self ocrID];
        if (self.personID.text.length >14) {
            [self checkMessageIsRight];
        }
       // self.personNation.text =[self ocrFolk];
        self.birth.text = [self ocrBirthday];//touble
        self.personAddress.text =[self ocrAddress];
        if ([self.ocrSex isEqualToString:@"男"] ) {
            sexKK =1;//男是1
            self.genderMan.selected =YES;
             self.genderWomen.selected =NO;
        }else{
            sexKK =2;//女是2
            self.genderWomen.selected =YES;
             self.genderMan.selected =NO;
        }
    }
   
    
//    NSArray * arrayHJT =  [HJTsqlite selectData:2 andModel:[citySqliteModel class] andName:@"CityId"];
//    if ( arrayHJT == 0) {
//       return ;
//    }else{
//
//
//        for (citySqliteModel * models in arrayHJT) {
//            self.personAddress.text =[NSString stringWithFormat:@"%@%@%@%@%@",models.province,models.downTown,models.area,models.village,models.villageCommittee];
//
//        }
//
//
//    }
    
    
}






-(void)dsfdsg{
       [self.view endEditing:YES];
       [self startOCR:YES];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    //设置高度
    self.personScroll.bounces = NO;
    self.title =@"证件信息";
    sexKK = 1;
    nationKK =1;
//    [self.personHeightView openKeyboardOffsetView];
//    self.personHeightView.keyboardGap =50;
    [self jiantingKeyBoard];
    self.isgetOCR = NO;
    [self delegate];
 SVProgressHUD.minimumDismissTimeInterval =1.0;
    //test
    UITapGestureRecognizer *get =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(asdasd)];
    [self.personHeightView addGestureRecognizer:get];

    //按钮调用接口
        NSArray *arr = @[_genderMan,_genderWomen];
    [self  buttonUse:arr andID:10007];

__weak __typeof(self)weakSelf = self;
    
    
    self.buttonS = ^(CLMarkButton *buttonName) {
       weakSelf.redButton = buttonName;
        if (weakSelf.redButton == weakSelf.genderMan) {
            sexKK = 1;
        }else{
            sexKK = 2;
        }
        
    };
 
    //写上要填写的内容
    self.personName.placeholder =@"";
//    self.personID.placeholder =@"";
//    self.personNation.placeholder =self;
//    self.birth.placeholder =self;
//    self.personTel.placeholder =self;
//    self.personAddress.placeholder =self;
//    self.personScroll.placeholder =self;
    
    self.buttonA = ^(CLMarkButton *buttonName_A) {
        
    };
    self.buttonB = ^(CLMarkButton *buttonName_B) {
        
    };
    //监听
     
     

}




//- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
//{
//    return self.personHeightView;
//}

//scrollDelegate
- (void)updateViewConstraints {
    [super updateViewConstraints];
    self.scroll_width.constant =self.personPageHeightButton.frame.origin.y+self.personPageHeightButton.bounds.size.height;
    
}
#pragma mark - 文本框代理
-(void)delegate{
    self.personName.delegate =self;
    self.personID.delegate =self;
    self.personNation.delegate =self;
    self.birth.delegate =self;
    self.personTel.delegate =self;
    self.personAddress.delegate =self;

    [self textFieldAddTwoBlackPlaceinTextFiled:self.personName];
     [self textFieldAddTwoBlackPlaceinTextFiled:self.personID];
     [self textFieldAddTwoBlackPlaceinTextFiled:self.personNation];
     [self textFieldAddTwoBlackPlaceinTextFiled:self.birth];
     [self textFieldAddTwoBlackPlaceinTextFiled:self.personAddress];
     [self textFieldAddTwoBlackPlaceinTextFiled:self.personTel];

    
}
#pragma mark - textfieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField{
    if (self.isgetOCR == YES) {
        if (textField ==  self.birth ||
            textField ==  self.personNation ||
            textField ==  self.personAddress
            ){
            [self sdfdsf:textField];
            [textField resignFirstResponder];
            return NO;
        }else{
            return YES;
        }
    }else{
        UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"是否身份证采集" message:nil preferredStyle:UIAlertControllerStyleAlert];
        __weak __typeof(self)weakSelf = self;
        [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.isgetOCR = YES;
        }]];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [weakSelf dsfdsg];
        }]];
        [self presentViewController:alertCon animated:YES completion:nil];
        return NO;
        
    }


    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - 所有不能手动输入的情况
- (IBAction)sdfdsf:(id)sender {

    //最后再写
//保存
//    省
//    市
//    区
//    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
//    [userDefault setValue:self.nameText.text forKey:@"name"];
//    [userDefault setValue:newStr  forKey:@"identityNumber"];
//    [userDefault synchronize];
 

    //shengri
    if (sender == self.birth) {
        __weak typeof(self) wself = self;
        [self.view endEditing:YES];
              [sender resignFirstResponder];
            [LYLDatePicker showDateDetermineChooseInView:self.view determineChoose:^(NSString *dateString) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    wself.birth.text = dateString;
 });
            }];
  
    }
    
    
    if(sender == self.personNation){
        __weak typeof(self) wself = self;
           [sender resignFirstResponder];
         [self.view endEditing:YES];
        if (self.dataArr.count >0) {
            for (PersonJob *model in self.dataArr) {
                if ([model.nameJob isEqualToString:@"nation"]) {
                    [self.addressModel onlySelect:model.politicalStatus  Handle:^(NSString *str1, NSString *str2, NSError *error) {
                        nationKK = (int)[JobUtil chooseEmployeeFamilyRelation:model.politicalStatus andSelectedString:str1];
                        if (nationKK == 9999) {
                            nationKK =1;
                             wself.personNation.text =@"汉族";
                        }else{
                             wself.personNation.text =str1;
                        }
                       
                    }];
                }
            }
        }
        
        
    }
    
    
    
    
    
    
    
    
    
    if (sender == self.personAddress) {
           [sender resignFirstResponder];
          [self.view endEditing:YES];
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        chooseAddressViewController*once  = [sb instantiateViewControllerWithIdentifier:@"chooseAddressViewController"];
        once.title = @"地址选择";
        once.stringChoose =@"stringChoose";
        once.delegate =self;
        UINavigationController*nav = [[UINavigationController alloc]initWithRootViewController:once];
        
        
        [self presentViewController:nav animated:YES completion:^{
    
        }];
    }
    

    
    
    
    
}

#pragma mark - 收起按钮
-(void)asdasd{
    [self.view endEditing:YES];
    [SVProgressHUD dismiss];
    
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField ==self.personID) {
        [self checkMessageIsRight];
    }
    
    
    
}
//性别
-(void)checkMessageIsRight{
    if (self.personID.text.length >14 ) {
        if ( [IDCardNumber_Validate isValidateIDCardString:self.personID.text] == NO ) {
            dispatch_async(dispatch_get_main_queue(), ^{
                return    [SVProgressHUD  showErrorWithStatus:@"身份证不正确"];
            });
        }
        
        __weak __typeof(self)weakSelf = self;
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [PersonGatherJobNetManager getPANDUANBase:weakSelf.personID.text completionHandle:^(PersonJob *model, NSError *error) {
//                  complete( [PersonJob mj_objectWithKeyValues:responseObj],error);
               
                
                
                
                if (error) {
                    
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (model.state == 2010) {
                        
                        UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"用户已经采集完毕,是否要修改" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        }]];
                        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        }]];
                        [weakSelf presentViewController:alertCon animated:YES completion:nil];
                        
                        
                    }else if(model.state == 2012 || model.state == 2011){
                    }else{
                        codeSelected *code = [codeSelected MustTakeReturn:model.state];
                        [code returnCodeMethod];
                        return;
                    }
                });
            }];
            
        });
    }
}




-(void)sendCityToFirstInfornation:(chooseAddressViewController *)avc senderProvince:(NSString *)province senderDownTown:(NSString *)downTown senderArea:(NSString *)area senderVillage:(NSString *)village senderVillageCommit:(NSString *)villageCommite senderDoor:(NSString *)door
{
    if (![villageCommite isEqualToString:@""]) {
        self.personAddress.text =[NSString stringWithFormat:@"%@%@%@%@%@%@",province,downTown,area,village,villageCommite,door];
    }
    
    
}

-(void)dealloc
{
  
    [[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+100, 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);
    }];
}

#pragma mark - 下一个页面
//下一步
- (IBAction)nextPage:(id)sender {
    NSLog(@"生日和地址和名族还没有弄好");
    [SVProgressHUD show];
    NSScanner *scan = [NSScanner scannerWithString:self.personName.text];
    int val;
    BOOL isNUmber =   [scan scanInt:&val] &&[scan isAtEnd];
    //4月11日
    if ( isNUmber == YES || self.personName.text.length <2) {
          [SVProgressHUD showErrorWithStatus:@"姓名必须是汉字并且大于两位"];
        return;
    }
    if ([self.personName.text isEqualToString:@""]  ) {
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    if ([self.personTel.text isEqualToString:@""]) {
        
    
        
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    if (self.personTel.text.length  != 11) {
        [SVProgressHUD showErrorWithStatus:@"不是电话号码"];
        return;
    }
    

    
    JobUtil *jobUtil =[[JobUtil alloc ]init];
    if ([jobUtil isNumberYes:self.personTel.text] == FALSE  ) {
        [SVProgressHUD showErrorWithStatus:@"电话号码不正确"];
        return;
    }
    
    
    if ([self.birth.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    if ([self.personAddress.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    if ([self.personID.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    if(  [IDCardNumber_Validate isValidateIDCardString:self.personID.text] == NO)   return   [SVProgressHUD showErrorWithStatus:@"身份证不正确请检查"];
    
    if ([self.personAddress.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    
    self.personID.text = [self.personID.text stringByReplacingOccurrencesOfString:@"x" withString:@"X"];
    
    if ([self.personNation.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"信息没有填写完整"];
        return;
    }
    
    self.ocrStr = nil;
    if ([[self ocrImageStr] isEqualToString:@""]) {
        self.ocrStr = [NSNull null];
        
        
        
        
    }else{
        
        self.ocrStr = [self ocrImageStr];
        //数据库插入ocr的图片
        testObject *cityModel  = [[testObject alloc]init];
        cityModel.PicID =1;
        cityModel.picture = self.ocrStr;
        [HJTsqlite addDate:cityModel];
    }

    
    [self jiekouYi];
    
    
    
    
    
    
    

    //    SecondPersonInformationViewController *secondVC =   [SecondPersonInformationViewController  sharedInstance];
    //
    //    if(![self.navigationController.topViewController isKindOfClass:[secondVC class]]) {
    //
    //        [self.navigationController pushViewController:secondVC animated:YES];
    //    }
}

//接口一

-(void)jiekouYi
{
    [PersonGatherJobNetManager getPANDUANBase:self.personID.text completionHandle:^(PersonJob *model, NSError *error) {
        if (error) {
            [SVProgressHUD  showErrorWithStatus:@"网络状态不佳"];
            return;
        }
        
        [SVProgressHUD dismiss];
        if (model.state == 2010) {
            UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"用户已经采集完毕,是否要修改" message:nil preferredStyle:UIAlertControllerStyleAlert];
            __weak __typeof(self)weakSelf = self;
            [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf jiekouTwo];
            }]];
            [self presentViewController:alertCon animated:YES completion:nil];

            
        }else if(model.state == 2012 || model.state == 2011){
            [self jiekouTwo];
        }else{
        codeSelected *code = [codeSelected MustTakeReturn:model.state];
        [code returnCodeMethod];
        return;
        }
        
    }];
    
    
    
}
//接口二

-(void)jiekouTwo{
      [SVProgressHUD show];
    
 

    [PersonGatherJobNetManager getUserBase:nil andtelphone:self.personTel.text andregisterName:self.personName.text andidcard:self.personID.text andbirthday:[JobUtil onlyNumber:self.birth.text] andGender:sexKK andnation:nationKK andPicture:self.ocrStr andAddress:self.personAddress.text completionHandle:^(PersonJob *model, NSError *error) {
        if (error) {
               [SVProgressHUD  showErrorWithStatus:@"网络状态不佳"];
            return;
        }
        
        [SVProgressHUD dismiss];
        if (model.state == 0) {
            if (model.result.baseId != 0) {
                NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
                [userDefault setInteger:model.result.baseId forKey:@"jobBaseID"];
                [userDefault setObject:model.result.idcard forKey:@"jobPersonID"];
                [userDefault synchronize];
            }else if(model.result.baseId == 0){
                [SVProgressHUD  showErrorWithStatus:@"网络状态不佳"];
                return;
            }else{
                [SVProgressHUD  showErrorWithStatus:@"网络状态不佳"];
                return;
            }
            SecondPersonInformationViewController *secondVC =   [SecondPersonInformationViewController  sharedInstance];
            
            if(![self.navigationController.topViewController isKindOfClass:[secondVC class]]) {
                
                [self.navigationController pushViewController:secondVC animated:YES];
            }
        }else{
            codeSelected *code = [codeSelected MustTakeReturn:model.state];
            [code returnCodeMethod];
            return;
        }
        
    }];
    
}



@end
