//
//  HeathOrganViewController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2020/4/10.
//  Copyright © 2020 雷俊博. All rights reserved.
//

#import "HeathOrganViewController.h"
#import "WJHandelAddressAlertView.h"

#import "Globaltypedef.h"
#if TARGET_IPHONE_SIMULATOR == 0
#import "SCCaptureCameraController.h"
#endif

#import "WJWebVC.h"



#import "RZBottomCell.h"

#import "ApplyStateQueryViewController.h"


@interface HeathOrganViewController ()
#if TARGET_IPHONE_SIMULATOR == 0
   <UITextFieldDelegate,SCNavigationControllerDelegate>
#endif

@property (weak, nonatomic) IBOutlet UIImageView *backImg_name;
@property (weak, nonatomic) IBOutlet UIImageView *backImg_Id;
@property (weak, nonatomic) IBOutlet UITextField *tf_name;
@property (weak, nonatomic) IBOutlet UITextField *tf_IdCard;

@property (weak, nonatomic) IBOutlet UIButton *scanBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (nonatomic, strong)NSArray *array_province;

@property (nonatomic, strong)NSArray *array_city;

@property (nonatomic, strong)NSArray *array_counties;

@property (nonatomic, strong)UIImage*cardImg;
@property (weak, nonatomic) IBOutlet UIButton *cardImgBtn;

@property (nonatomic, strong)UICollectionView* collectionView;




@end

@implementation HeathOrganViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [GTCountSDK trackCountEvent:@"home_zhengwu_butiebanli" withArgs:@{}];//个推统计
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self configUI];
    [self configNav];
    [self creatBottomView];
}
- (void)configUI
{
    
    [self.cardImgBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:10];
    self.scanBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    if (self.view.bounds.size.width > 320) {
        UIEdgeInsets insets = UIEdgeInsetsMake(4, 72.5, 4, 4);
        UIImage *backImgName = [UIImage imageNamed:@"社保认证姓名"];
        UIImage *backImgId = [UIImage imageNamed:@"社保认证身份证"];
        backImgName = [backImgName resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        backImgId = [backImgId resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        self.backImg_name.image = backImgName;
        self.backImg_Id.image = backImgId;
    }
}

- (void)configNav
{
    UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] init];
    backButtonItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backButtonItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"进度查询" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    rightBtn.frame = CGRectMake(0, 0, 80, 44);
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

- (void)creatBottomView
{
    CGFloat height = 49;
    if (cl_kNavigationBarHeight > 64) {
        height = 83;
    }
    
    UIView*view = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - height - 5 , ScreenWidth, 49 + 5)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView*line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
    line.backgroundColor = [UIColor colorWithHex:0x4d4d4d];
    
    
    [self.view addSubview:view];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
     // 设置item的行间距和列间距
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView*collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 5, ScreenWidth, 49) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsVerticalScrollIndicator = NO;   //是否显示滚动条
    collectionView.scrollEnabled = YES;  //滚动使能
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerNib:[UINib nibWithNibName:@"RZBottomCell" bundle:nil] forCellWithReuseIdentifier:@"userCell"];
     
     self.collectionView = collectionView;
    [view addSubview:self.collectionView];
    [view addSubview:line];
    
    
//    collectionView.layer.borderWidth = 0.5;
//    collectionView.layer.borderColor = [UIColor colorWithHex:0xd4d4d4].CGColor;
    
   
}


#pragma mark - 查询接口
- (NSDictionary *)addressStateRequestPara
{
    NSString* idStr = [self.tf_IdCard.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSDictionary*params = @{
        @"code":@([idStr substringToIndex:6].integerValue)
    };
    
    return params;
}

- (void)addressStateRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],KKWeiJianIdAddressStateRequest];
    
    NSLog(@"看看卫健根据身份证查询地区url:%@",url);
    NSLog(@"params:%@",[self addressStateRequestPara]);
    [SVProgressHUD show];
    [NetworkRequest Get7:url Params:[self addressStateRequestPara] Success:^(id _Nonnull responseObject) {
        [SVProgressHUD dismiss];
        NSLog(@"responseObject:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString* describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
             NSString* idStr = [self.tf_IdCard.text stringByReplacingOccurrencesOfString:@" " withString:@""];
            if ([state isEqualToString:@"200"]) {
                
                [WJHandelAddressAlertView showWithViewController:self name:self.tf_name.text idStr:idStr contentDic:responseObject[@"result"] Callback:^(NSString * _Nonnull url, NSDictionary * _Nonnull params) {
                    NSString *idStr = [self.tf_IdCard.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                    NSMutableDictionary*mParams = [NSMutableDictionary dictionaryWithDictionary:params];
                   
                   [mParams setObject:self.tf_name.text forKey:@"name"];
                    [mParams setObject:idStr forKey:@"idCard"];
                    [mParams setObject:@([UserDefault integerForKey:@"userId"]) forKey:@"operate_id"];
                   
                   
                    NSString*imgStr = @"";
                    if (self.cardImg) {
                        NSData*imageData = UIImagePNGRepresentation(self.cardImg);
                       
                      imgStr =  [SecurityUtil encodeBase64Data:imageData];
                       
                    }
                   
                    [mParams setObject:imgStr forKey:@"img"];
                    
                    WJWebVC*vc = [[WJWebVC alloc]init];
                    vc.url = [NSString stringWithFormat:@"%@%@",urlIP,url];
                    vc.params = mParams;
                    
                    NSString* age = [self calculateAgeStr:idStr];
                    if (age.integerValue >= 80) {
                      vc.title = @"高龄登记";
                    }else{
                      vc.title = @"津贴申领";
                    }
                    [self.navigationController pushViewController:vc animated:YES];
                }];
               
                        
            }else if ([state isEqualToString:@"500"]){
                [WJHandelAddressAlertView showWithViewController:self name:self.tf_name.text idStr:idStr contentDic:nil Callback:^(NSString * _Nonnull url, NSDictionary * _Nonnull params) {
                    NSString *idStr = [self.tf_IdCard.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                    NSMutableDictionary*mParams = [NSMutableDictionary dictionaryWithDictionary:params];
                    
                    [mParams setObject:self.tf_name.text forKey:@"name"];
                    [mParams setObject:idStr forKey:@"idCard"];
                    [mParams setObject:@([UserDefault integerForKey:@"userId"]) forKey:@"operate_id"];
                    
                    NSString*imgStr = @"";
                    if (self.cardImg) {
                        NSData*imageData = UIImagePNGRepresentation(self.cardImg);
                        
                      imgStr =  [SecurityUtil encodeBase64Data:imageData];
                        
                    }
                    
                    [mParams setObject:imgStr forKey:@"idCardPhoto"];
                    
                    
                    WJWebVC*vc = [[WJWebVC alloc]init];
                    vc.url = [NSString stringWithFormat:@"%@%@/",urlIP,url];
                    vc.params = mParams;
                    
                    NSString* age = [self calculateAgeStr:idStr];
                    if (age.integerValue >= 80) {
                      vc.title = @"高龄登记";
                    }else{
                      vc.title = @"津贴申领";
                    }
                    
                    [self.navigationController pushViewController:vc animated:YES];
                }];
                        return;
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
        
    } Failure:^(NSError* error) {
        [SVProgressHUD dismiss];
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
    
    
}



#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        return 2;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
         RZBottomCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userCell" forIndexPath:indexPath];
         if (indexPath.item == 0){
            cell.lb_title.text = @"申报记录";
            cell.img.image = [UIImage imageNamed:@"bottom_rzHistory"];
        }else if (indexPath.item == 1){
            cell.lb_title.text = @"健康";
            cell.img.image = [UIImage imageNamed:@"life_unselect"];
        }
        return cell;
   
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
        CGFloat width =  CGRectGetWidth(collectionView.bounds)  /2 ;
         CGFloat realWidth = CGRectGetWidth(collectionView.bounds)   - floor(width)*(2 - 1);
         // CGFloat itemW = K_ScreenWidth/array.count;
         if (indexPath.item == 0) {
             return CGSizeMake(realWidth, 49);
         }

        return CGSizeMake(floor(width), 49);
    
   
}

/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{

    return 0;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
   
        return CGSizeZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        if (indexPath.item == 1) {

            self.tabBarController.selectedIndex = 3;
            [self.navigationController popToRootViewControllerAnimated:YES];



        }else if (indexPath.item == 0){
            ApplyStateQueryViewController* vc = [ApplyStateQueryViewController new];
            vc.title = @"登记进度查询";
            [self.navigationController pushViewController:vc animated:YES];
        }
    
  
    
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSCharacterSet *_set = [NSCharacterSet characterSetWithCharactersInString:@"0123456789xX"];;
    
    if (textField == self.tf_IdCard) {
        if ([string isEqualToString:@""]) { // 删除字符
            return YES;
        } else {
            
            if (textField.text.length   == 6 || textField.text.length   == 11 || textField.text.length   == 16 ) {
                  textField.text = [NSString stringWithFormat:@"%@ ", textField.text];

                    }
            }

            
             if (textField.text.length >= 21)
             {//大于18位无法再继续输入
                               return NO;
             }
                           
            NSRange range = [string rangeOfCharacterFromSet:_set];
            //判断输入的内容是否是规定的内容范围内 如果不是不做更改 如果是才输入
           if (range.length == 0) {
               return NO;
           }else{
               return YES;
           }
        return YES;
    }
    return YES;
}

#pragma mark - SCNavigationControllerDelegate
- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num
{
    self.tf_name.text =name;
    if (![IDCardNumber_Validate isValidateIDCardString:num]) {
        [Tools showMessage:@"身份证识别错误,请重新拍摄"];
        return;
    }
    
    NSString *st1 =[num substringWithRange:NSMakeRange(0, 6)];
    NSString *st2 =[num substringWithRange:NSMakeRange(6, 4)];
    NSString *st3 =[num substringWithRange:NSMakeRange(10, 4)];
    NSString *st4 =[num substringFromIndex:14];
    self.tf_IdCard.text =  [NSString stringWithFormat:@"%@ %@ %@ %@",st1,st2,st3,st4];
    
    
}

- (void)sendTakeImage:(TCARD_TYPE) iCardType image:(UIImage *)cardImage
{
    self.cardImg = cardImage;
}

#pragma mark - public methods
- (void)clearText
{
    self.tf_name.text = @"";
    self.tf_IdCard.text = @"";
}



#pragma mark - event response
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (IBAction)btnClick:(UIButton *)sender {
    
    [self.view endEditing:YES];
    
    if (sender == self.scanBtn) {
        [self startOCR];
    }else if (sender == self.nextBtn){
        if (self.tf_name.text.length == 0) {
            [Tools showMessage:@"姓名不能为空!"];
            return;
        }
        
        if (self.tf_IdCard.text.length ==0) {
           [Tools showMessage:@"身份证号码不能为空!"];
            return;
        }
        
        NSString *idStr = [self.tf_IdCard.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        if (![IDCardNumber_Validate isValidateIDCardString:idStr]) {
            [Tools showMessage:@"身份证号码格式不正确"];
            return;
        }
        
        if (![self getWorkType]) {
            [Tools showMessage:@"未到年龄,不可登记!"];
            return;
        }
        
        [self addressStateRequest];
        
    }
    
}

- (void)rightBtnClick:(UIButton *)sener
{
    ApplyStateQueryViewController* vc = [ApplyStateQueryViewController new];
    vc.title = @"登记进度查询";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 启动ocr
- (void)startOCR
{
    
    #if TARGET_IPHONE_SIMULATOR == 0
    SCCaptureCameraController*con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2; // 其他证件以此类推
    con.isDisPlayTxt = NO;
    con.ScanMode = TIDC_SCAN_MODE;
    con.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:con animated:YES completion:NULL];
    #endif
    
}

#pragma mark - alert message
- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}

#pragma mark - private methods
//截取身份证的出生日期并转换为日期格式
//18位
-(NSString *)subsIDStrToDate:(NSString *)str{
    NSMutableString *result = [NSMutableString stringWithCapacity:0];
    
    NSString *dateStr = [str substringWithRange:NSMakeRange(6, 8)];
    NSString  *year = [dateStr substringWithRange:NSMakeRange(0, 4)];
    NSString  *month = [dateStr substringWithRange:NSMakeRange(4, 2)];
    NSString  *day = [dateStr substringWithRange:NSMakeRange(6,2)];
    
    [result appendString:year];
    [result appendString:@"-"];
    [result appendString:month];
    [result appendString:@"-"];
    [result appendString:day];
    
    return result;
}
//14位

-(NSString *)subs2IDStrToDate:(NSString *)str{
    NSMutableString *result = [NSMutableString stringWithCapacity:0];
    
    NSString *dateStr = [str substringWithRange:NSMakeRange(6, 6)];
    NSString  *year = [dateStr substringWithRange:NSMakeRange(0, 2)];
    year = [NSString stringWithFormat:@"19%@",year];
    NSString  *month = [dateStr substringWithRange:NSMakeRange(2, 2)];
    NSString  *day = [dateStr substringWithRange:NSMakeRange(4,2)];
    
    [result appendString:year];
    [result appendString:@"-"];
    [result appendString:month];
    [result appendString:@"-"];
    [result appendString:day];
    
    return result;
}


//计算年龄
-(NSString *)calculateAgeStr:(NSString *)str{
 //截取身份证的出生日期并转换为日期格式
  NSString *dateStr = nil;
  
  if (str.length == 18) {
     dateStr = [self subsIDStrToDate:str];
  }else if (str.length == 15){
      dateStr = [self subs2IDStrToDate:str];
  }
  
  NSDate* currentDate = [NSDate date];
   
   NSArray*birthArray = [dateStr componentsSeparatedByString:@"-"];
   NSString*birthYear = birthArray[0];
   NSString*birthMonth = birthArray[1];
   
   NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
   [dateformatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
   [dateformatter setDateFormat:@"yyyy-MM"];

   //    今年

   NSString *thisYearString=[dateformatter stringFromDate:currentDate];
   
   NSArray*currentArray = [thisYearString componentsSeparatedByString:@"-"];
   NSString*currentYear = currentArray[0];
   NSString*currentMonth = currentArray[1];
   
   int age = currentYear.intValue -birthYear.intValue;
   
   if (currentMonth.intValue < birthMonth.intValue) {
       age = age - 1;
   }

   
   
   
  
   NSString *ageStr = [NSString stringWithFormat:@"%d", age];

   return ageStr;
}

- (BOOL)getWorkType
{
    NSString *idStr = [self.tf_IdCard.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString* age = [self calculateAgeStr:idStr];
    if (age.integerValue >= 60 && age.integerValue < 80) {
        
        return YES;
        
    }else if (age.integerValue >= 80){
        return YES;
    }
    
    return NO;
}



#pragma mark - getters and setters


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