//
//  enterTableViewController.m
//  Open
//
//  Created by 看看智能 on 2017/2/21.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "enterTableViewController.h"
#import "UIImageView+WebCache.h"
#import "timeForButtonCount.h"
#import "AppDelegate.h"
#import "LoginVC.h"
@interface enterTableViewController ()<UIImagePickerControllerDelegate,UITextFieldDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong)UITextField *textField;
@end

@implementation enterTableViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.toolbarHidden = NO;
    self.imageViewTitle.layer.masksToBounds =YES;
    self.imageViewTitle.layer.cornerRadius =self.imageViewTitle.bounds.size.width*0.5;
    self.imageViewTitle.layer.borderWidth=2.0;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"secondImage"]) {
        self.imageViewTitle.image =[UIImage imageWithData:[getPeopleID getFileImage]];
    }else
    {
  [self.imageViewTitle sd_setImageWithURL:[getPeopleID PeoplePhoto] placeholderImage:[UIImage imageNamed:@"titleimage_1"]options:SDWebImageRetryFailed];
    }
    self.yourName.text=[getPeopleID Peopletitle];

  self.yourIphone.text =   [self numberSuitScanf:[getPeopleID PeopleIphoneNmber]];
    NSLog(@"%@", [self numberSuitScanf:[getPeopleID PeopleIphoneNmber]]);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableViews.scrollEnabled=NO;
    self.title=@"登入信息";
    self.yourName.delegate =self;
    self.yourIphone.delegate=self;
    if (@available(iOS 11.0, *)) {

        
        
        if( [UIScreen mainScreen].bounds.size.height == 812 || [UIScreen mainScreen].bounds.size.height == 896){

            self.tableViews.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            self.tableViews.contentInset = UIEdgeInsetsMake(88, 0, 49, 0);
            self.tableViews.scrollIndicatorInsets = self.tableViews.contentInset;
            
            
            
            
        }else{

            
            self.tableViews.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            self.tableViews.contentInset = UIEdgeInsetsMake(69, 0, 49, 0);
            self.tableViews.scrollIndicatorInsets = self.tableViews.contentInset;
            
        }
        
        
        
        
    }
    self.navigationController.toolbarHidden=NO;
    [self.navigationController.toolbar setTranslucent:YES];
     
    [self.navigationController.toolbar setTintColor:[UIColor redColor]];
    [self.navigationController.toolbar setBarTintColor:[UIColor whiteColor]];

    UIBarButtonItem *item2 =[[UIBarButtonItem alloc]initWithTitle:@"退出当前账号" style:UIBarButtonItemStyleDone target:self action:@selector(titleAction)];
    UIBarButtonItem *fixibleSpace =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    NSArray *itemarray =@[fixibleSpace,item2,fixibleSpace];
    self.toolbarItems =itemarray;
}
-(void)titleAction
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"退出账号" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf exitAccount];
    }];
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
      
    }];
//    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action4];
    
   
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}
-(void)exitAccount
{
    self.navigationController.toolbarHidden=YES;
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstlog"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"secondImage"];
    [getPeopleID getpeopleLimitedAuthority:NO];
       [getPeopleID socialSate:0];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.row == 0) {
        [self changeHeadView1:nil];
    }else if(indexPath.row ==1){
        

        
    }else if(indexPath.row ==2){
//        LoginViewController *log=  [[LoginViewController alloc]init];
//        self.navigationController.toolbarHidden = YES;
//        log.editText =YES;
//        [self.navigationController pushViewController:log animated:YES];
        LoginVC *loginVC = [[LoginVC alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
        
    }else if (indexPath.row == 3){

    }else
    {
        [self.view endEditing:YES];
    
    }
}

#pragma mark-照片
-(void)changeHeadView1:(UIButton *)tap
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更改头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self snapImage];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self localPhoto];
             });
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)snapImage
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        __block UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.delegate = self;
        ipc.allowsEditing = YES;
        ipc.navigationBar.barTintColor =[UIColor whiteColor];
        ipc.navigationBar.tintColor = [UIColor whiteColor];
        ipc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
        [self presentViewController:ipc animated:YES completion:^{
            ipc = nil;
        }];
    } else {
        NSLog(@"模拟器无法打开照相机");
    }
}
-(void)localPhoto
{
    __block UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    picker.navigationBar.barTintColor =[UIColor blackColor];
    picker.navigationBar.tintColor = [UIColor whiteColor];
    picker.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
    
    
 
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:picker animated:YES completion:^{
            picker = nil;
        }];
 });
    //主线程

}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //完成选择
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //NSLog(@"type:%@",type);
    if ([type isEqualToString:@"public.image"]) {
        //转换成NSData
   __block UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        if (image == nil) {
            [SVProgressHUD showErrorWithStatus:@"请在设置中打开照片访问权限"];
        }
        //关闭相册界面
        dispatch_async(dispatch_get_main_queue(), ^{
        [picker dismissViewControllerAnimated:YES completion:^{
  

            self.imageViewTitle.layer.masksToBounds =YES;
            self.imageViewTitle.layer.cornerRadius =self.imageViewTitle.bounds.size.width*0.5;
            self.imageViewTitle.layer.borderWidth=0.5;
            self.imageViewTitle.image =image;
    NSData  *dateImage1 =UIImageJPEGRepresentation(image,0.86);
            [getPeopleID getPeopleFilePhoto:dateImage1];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"secondImage"];
         
   
                        [logNetModel getDidLogMessage:[getPeopleID PeopleID] andTelephone:[NSNull null] andcusName:[NSNull null]andOldCusName:[NSNull null] andnowCusName:[NSNull null] andphoto:[EnercryTool encryptBase64:dateImage1] completionHandle:^(lodModel *model, NSError *error) {
                            NSLog(@"%@",model.code);
                          
                        }]; 
             }];
        });
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (IBAction)cusNameandIphoneName:(UITextField *)sender {
    if (sender ==self.yourName) {
    
        [getPeopleID getPeopletitle:[EnercryTool encryptUseDES:self.yourName.text key:DESKEY]];
       
        [logNetModel getDidLogMessage:[getPeopleID PeopleID] andTelephone:[NSNull null] andcusName: [EnercryTool encryptUseDES:[getPeopleID Peopletitle] key:DESKEY]  andOldCusName:[NSNull null] andnowCusName:[NSNull null] andphoto:[NSNull null] completionHandle:^(lodModel *model, NSError *error) {
            if ([model.code isEqualToString:@"16"]) {
                SVProgressHUD.minimumDismissTimeInterval=1.0;
                [SVProgressHUD showErrorWithStatus:@"包含敏感字符"];
                self.yourName.text=@"点击修改";
                [getPeopleID getPeopletitle:[EnercryTool encryptUseDES:self.yourName.text key:DESKEY]];
            }
        }];
        
    }
    if(sender == self.yourIphone)
    {
        
       
        NSInteger numberIphone =[self.yourIphone.text intValue];
         NSLog(@"%ld",numberIphone);
        if ([self.yourIphone.text length] ==11 && ( [self isPureInt:self.yourIphone.text] || [self isPureFloat:self.yourIphone.text])){
        
        
        
        
         [getPeopleID getPeopleIphoneNmber:[EnercryTool encryptUseDES:self.yourIphone.text key:DESKEY]];
        
        [logNetModel getDidLogMessage:[getPeopleID PeopleID] andTelephone:[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY] andcusName:[NSNull null]  andOldCusName:[NSNull null]  andnowCusName:[NSNull null]  andphoto:[NSNull null]  completionHandle:^(lodModel *model, NSError *error) {
            if ([model.code isEqualToString:@"0"])
                [self exitAccount];
        }];
    }else
        {
            SVProgressHUD.minimumDismissTimeInterval=1.0;
            [SVProgressHUD showErrorWithStatus:@"不是电话号码"];
            self.yourIphone.text =[self numberSuitScanf:[getPeopleID PeopleIphoneNmber]];
            
        }
   }
}
//判断是否是整形
- (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return[scan scanInt:&val] && [scan isAtEnd];
    
}
//判断是否为浮点形：

- (BOOL)isPureFloat:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    float val;
    
    return[scan scanFloat:&val] && [scan isAtEnd];
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _yourName) {
        [_yourName resignFirstResponder];
    }
    if (textField == _yourIphone) {
        [_yourIphone resignFirstResponder];
    }

    
    return YES;
}
-(NSString *)numberSuitScanf:(NSString*)number{
    
    //首先验证是不是手机号码
//    
//    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\\\d{8}$";
//    
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    
////    BOOL isOk = [regextestmobile evaluateWithObject:number];
    
    if (!number || number == NULL || [number isEqualToString:@""]) {
       return NULL;
    }else{
        return [number stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    
    
    
        
   

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
   [_yourName resignFirstResponder];

}


@end
