//
//  SettingViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/7/3.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SettingViewController.h"
#import <WebKit/WebKit.h>

#import "SettingTableViewCell.h"
#import "Constants.h"
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"

#import "regardTableViewController.h"
#import "ChangeUserInfoViewController.h"
#import "UPViewController.h"
#import "loginProtocol.h"

#import "CTAPIBaseManager.h"
#import "PayUserInfoManager.h"
#import "YDTempUrlInstance.h"
//凡泰
#import <FinApplet/FinApplet.h>
#import "LoginOff.h"
@interface SettingViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,LoginOffDelegate>

{
    NSString *bindStr;
}

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSArray *dataArray;

@end

@implementation SettingViewController
- (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];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    [self.view addSubview:self.tableView];
    
    UIButton *logOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    logOutBtn.frame = CGRectMake(0, 0, cl_kScreenWidth, 45*WIDTHRADIU);
    [logOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [logOutBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    logOutBtn.titleLabel.font = [UIFont systemFontOfSize:17*WIDTHRADIU];
    logOutBtn.backgroundColor = [UIColor whiteColor];
    
    [logOutBtn addTarget:self action:@selector(logOutClick:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = logOutBtn;
    
    [self requestBindAPI];
    
    bindStr = @"未绑定";
    
}

- (void)logOutClick:(UIButton *)sender{
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstlog"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"secondImage"];
    [getPeopleID getpeopleLimitedAuthority:NO];
    [getPeopleID socialSate:0];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
    
    //雷俊博退出时清除登录类型和账号密码
    [getPeopleID getLoginType:nil];
    [getPeopleID getLoginAccount:nil];
    [getPeopleID getLoginPassword:nil];
    [getPeopleID saveDefaultLoginAccount:nil];
    [getPeopleID saveDefaultLoginPassword:nil];
    [getPeopleID getTotalCoins:nil];
    [getPeopleID clearTotalCoins];
    [getPeopleID clearDefaultProvince];
    
    [getPeopleID saveAccountAuthWithState:NO];
    
    
    [PayUserInfoManager sharedManager].model = nil;
    
    
    //清除分享时间
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"shareLastTime"];
    //清除最近认证记录
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"ValidationDic"];
    //清除认证成功弹框时间
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"coinsauthenticationLastTime"];
    
    //清除走路赚金币领取时间
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"onFootCoinsDate"];
    
    
    [UserDefault setInteger:0 forKey:@"appleLoginState"];
    
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    //清除登录时间
    [getPeopleID saveLoginTime:nil];
    
    //[self deleterzUserTable];
    
    [self cleanCacheAndCookie];
    [YDTempUrlInstance destroyInstance];
    
    if (self.block) {
        self.block(YES);
    }
      
    [[FATClient sharedClient] clearLocalApplets];//清除缓存的凡泰小程序
   
    [self.navigationController popViewControllerAnimated:YES];
}

//删除认证表
- (void)deleterzUserTable{
    FMDatabase *db = [FMDatabase databaseWithPath:[self getrzUserDBPath]];
       if ([db open]){
             BOOL res = [db executeUpdate:@"DROP TABLE t_rzUser"];
           if (res) {
               NSLog(@"表格删除成功");
           }else{
               NSLog(@"表格删除失败");
           }
           [db close];
       }
       
       
}

- (NSString *)getrzUserDBPath
{
     NSString *doc= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        return [doc stringByAppendingPathComponent:@"rzUserlist.sqlite"];

}


#pragma mark - api 调用
- (void)requestBindAPI
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
        
        return;

    }
    
    
    WeakSelf
    NSString *url = [NSString stringWithFormat:@"%@scorepay/validateBind",CoinsBaseUrl];
    
    NSDictionary *dic = @{
                          @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2",
                          @"accounttype":[NSNumber numberWithInt:1],
                          };
    
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&weface9578",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    
    [KKLoadingAnimationView show];
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        [KKLoadingAnimationView dismiss];
        if (error) {
            [SVProgressHUD showInfoWithStatus:@"无网络"];
            return ;
        }
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            NSString *des = responseObject[@"des"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 0) {
                    
                     NSString *screenName = [NSString blankString:responseObject[@"result"][@"screenName"]] ? @"" : responseObject[@"result"][@"screenName"];
                    
                    self->bindStr = [NSString stringWithFormat:@"%@(已绑定)",screenName];
                    
                    [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
                    
                    
                }else if (code.integerValue == 1018){
                   
                    
                }else{
                    [SVProgressHUD showInfoWithStatus:des];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器错误"];
            }
        }
    }];
}

#pragma mark - 绑定微信
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{WeakSelf
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        NSLog(@">>>>>wx>>result:%@, error:%@",result,error);
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"微信授权失败!"];
            return;
        }
        
        UMSocialUserInfoResponse *resp = result;
        if(resp.uid ){
            if (!resp.name) {
                resp.name =@"";
            }
            if (!resp.iconurl) {
                resp.iconurl=@"";
            }
            
           
        }
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);//uuid
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.gender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
        
        NSDictionary *dic = @{
                              @"iconurl":resp.iconurl ? resp.iconurl :@"",
                              @"openid":resp.openid ? resp.openid : @"",
                              @"uid":resp.uid ? resp.uid : @"",
                              @"token":resp.accessToken ? resp.accessToken : @"",
                              @"screenname":resp.name ? resp.name : @"",
                              };
        [weakSelf bindWxApiWithParams:dic];
    }];
}

- (void)bindWxApiWithParams:(NSDictionary *)dic
{
    NSString *url = [NSString stringWithFormat:@"%@scorepay/accountBind",CoinsBaseUrl];
    
    
    
    NSDictionary *dic2 = @{
                          @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"accounttype":[NSNumber numberWithInt:1],
                          @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2"
                          };
    
    NSMutableDictionary *dic3 = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    [dic3 addEntriesFromDictionary:dic2];
    
    
    NSArray *result = [dic3.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic3[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic3[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&weface9578",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic3];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    NSString *username = dic3[@"screenname"];
    [params setObject:[username stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]] forKey:@"screenname"];
    
//    WeakSelf
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (error) {
            [SVProgressHUD showInfoWithStatus:@"无网络"];
            return ;
        }
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            NSString *des = responseObject[@"des"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 0) {
                    
                  
                    
                    NSString *screenName = username ? username : @"";
                    
                    
                    self->bindStr = [NSString stringWithFormat:@"%@(已绑定)",screenName];
                                       
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
                   
                    
                }else if (code.integerValue == 1018){
                    
                }else{
                    [SVProgressHUD showInfoWithStatus:des];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器错误"];
            }
        }
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSArray *array = self.dataArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    
    NSDictionary *dic = self.dataArray[indexPath.section][indexPath.row];
    
    [cell configurationDataWith:dic];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
           
            NSURL *url = [getPeopleID PeoplePhoto];
            if (url) {
                [cell.img_Photo sd_setImageWithURL:[getPeopleID PeoplePhoto] placeholderImage:[UIImage imageNamed:@"userDefaultIcon_man"]];
            }else{
                cell.img_Photo.image = [UIImage imageNamed:@"userDefaultIcon_man"];
            }
            
        }else if (indexPath.row == 1){
            cell.lb_Content_ArrowShow.text = [getPeopleID Peopletitle];
        }else if (indexPath.row == 2){
            NSString *tel = [getPeopleID PeopleIphoneNmber];
            
            if (tel.length == 11) {
                 cell.lb_Content_ArrowShow.text = [NSString stringWithFormat:@"%@****%@",[tel substringToIndex:2],[tel substringFromIndex:8]] ;
            }else{
                cell.lb_Content_ArrowShow.text = @"未绑定";
            }
           
        }else if (indexPath.row == 3){
            cell.lb_Content_ArrowShow.text = bindStr;
        }else if (indexPath.row == 4){
            cell.lb_Content_ArrowShow.text = @"修改";
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
        
            cell.lb_Content_ArrowHidden.text = @"";
        }else if (indexPath.row == 1){
            cell.lb_Content_ArrowHidden.text = @"wangqin@weface.com.cn";
        }else if(indexPath.row==2){
            SDImageCache *sdImageCache = [SDImageCache sharedImageCache];

            NSInteger intg = [sdImageCache getSize];
            cell.lb_Content_ArrowHidden.text =  [NSString stringWithFormat:@"%@",[self fileSizeWithInterge:intg]];
            
        }else if(indexPath.row==3){
            cell.lb_Content_ArrowHidden.text = @"400-002-1799";
        }else if(indexPath.row==4){
            cell.lb_Content_ArrowHidden.text = @"注销后无法恢复,请谨慎操作  ";
        }
        
        
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 55;
    }
    
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return 30;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footer = [[UIView alloc]init];
    footer.backgroundColor = [UIColor colorWithHex:0xf5f5f5];
    return footer;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    NSInteger loginState = [UserDefault integerForKey:@"appleLoginState"];
    
    if (indexPath.section ==0) {
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"] && loginState == 1031) {
            
            
            
            NSString* uid = [UserDefault objectForKey:@"appleId"];
            NSString* userId = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
            NSString* cus_name = [getPeopleID Peopletitle];
            NSString* photoUrl = [getPeopleID PeoplePhoto].absoluteString;
            
            
            BPViewController *bpVC = [[BPViewController alloc]init];
            bpVC.UID = uid;
            bpVC.Id = userId;
            bpVC.wxName = [NSString blankString:cus_name] ? @"" :cus_name;
            bpVC.wxPhotoUrl = photoUrl;
            bpVC.title = @"绑定手机号";
            bpVC.from = @"other";
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:bpVC];
            [self presentViewController:nav animated:YES completion:nil];
            
            return;

        }
    }
    
    
    if (indexPath.section == 0 ) {
        if (indexPath.row == 0) {
            [self changeHeadView1:nil];
        }else if (indexPath.row == 1){
            
            SettingTableViewCell *cell = (SettingTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
            ChangeUserInfoViewController *vc = [ChangeUserInfoViewController new];
            vc.block = ^(BOOL isSuccess){
                if (isSuccess) {
                    [self.tableView reloadData];
                }
            };
            vc.type = CTSettingChangeUserinfoTypeNickname;
            vc.content = cell.lb_Content_ArrowShow.text;
            vc.title = @"更改昵称";
            
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 3){
            if ([bindStr isEqualToString:@"未绑定"]) {
                [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
            }
        }else if (indexPath.row == 4){
            
            UPViewController *upVC  = [UPViewController new];
            upVC.title = @"修改密码";
            [self.navigationController pushViewController:upVC animated:YES];
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            WXOpenCustomerServiceReq *req = [[WXOpenCustomerServiceReq alloc] init];
               req.corpid = @"ww1b3dc1cff3883128"; //企业ID
               req.url = @"https://work.weixin.qq.com/kfid/kfc598def0be61952bb";   //客服URL
               return [WXApi sendReq:req completion:nil];
            
        }else if (indexPath.row == 1){
            NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"mailto://wangqin@weface.com.cn"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }else if (indexPath.row == 2){
            
            //regardTableViewController *vc =[regardTableViewController sharedInstance];
            //[self.navigationController pushViewController:vc animated:YES];
            SDImageCache *sdImageCache = [SDImageCache sharedImageCache];
            NSInteger intg = [sdImageCache getSize];
           
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"清理" message:[NSString stringWithFormat:@"已清理%@缓存",[self fileSizeWithInterge:intg]] preferredStyle:UIAlertControllerStyleAlert];
            
            [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"点击取消");
                
            }]];
            
            [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"点击确认");
                
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    
                   [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //[self.tableView reloadData];
                    });
                });
                
            }]];
            
             [self presentViewController:alertVC animated:YES completion:nil];
        }else if (indexPath.row==3){
            NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://400-002-1799"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }else if (indexPath.row==4){
            NSLog(@"注销账号!");
            LoginOff *upVC  = [[LoginOff alloc]init];
            upVC.delegate=self;
            //upVC.title = @"修改密码";
            [self.navigationController pushViewController:upVC animated:YES];
        }
    }

}
- (void)loginOffResult{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstlog"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"secondImage"];
    [getPeopleID getpeopleLimitedAuthority:NO];
    [getPeopleID socialSate:0];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
    
    //雷俊博退出时清除登录类型和账号密码
    [getPeopleID getLoginType:nil];
    [getPeopleID getLoginAccount:nil];
    [getPeopleID getLoginPassword:nil];
    [getPeopleID saveDefaultLoginAccount:nil];
    [getPeopleID saveDefaultLoginPassword:nil];
    [getPeopleID getTotalCoins:nil];
    [getPeopleID clearTotalCoins];
    [getPeopleID clearDefaultProvince];
    
    [getPeopleID saveAccountAuthWithState:NO];
    
    
    [PayUserInfoManager sharedManager].model = nil;
    
    
    //清除分享时间
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"shareLastTime"];
    //清除最近认证记录
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"ValidationDic"];
    //清除认证成功弹框时间
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"coinsauthenticationLastTime"];
    
    //清除走路赚金币领取时间
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"onFootCoinsDate"];
    
    
    [UserDefault setInteger:0 forKey:@"appleLoginState"];
    
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    //清除登录时间
    [getPeopleID saveLoginTime:nil];
    
    //[self deleterzUserTable];
    
    [self cleanCacheAndCookie];
    [YDTempUrlInstance destroyInstance];
    
    if (self.block) {
        self.block(YES);
    }
      
    [[FATClient sharedClient] clearLocalApplets];//清除缓存的凡泰小程序
   
    [self.navigationController popViewControllerAnimated: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:^{
                
                
                NSData  *dateImage1 =UIImageJPEGRepresentation(image,0.86);
                [getPeopleID getPeopleFilePhoto:dateImage1];
                
                NSString *url = [[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/uploadAccountPhoto"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                
                NSDictionary *params = @{
                                         @"image":[EnercryTool encryptBase64:dateImage1],
                                         @"id":@([getPeopleID PeopleID]),
                                         @"flag":@(2)
                                         };
                
                [NetworkRequest SBAuthPost:url Params:params Success:^(id _Nonnull responseObj) {
                    
                    if ([responseObj isKindOfClass:[NSDictionary class]]) {
                        NSString *code = [responseObj[@"code"] stringValue];
                        NSString *msg = responseObj[@"msg"];
                        NSString *url = responseObj[@"result"];
                        if ([code isEqualToString:@"0"]) {
                            if (msg.length > 0) {
                                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                            }
                            [getPeopleID getPeoplePhoto:url];
                            
                            [self.tableView reloadData];
                        }else{
                            [SVProgressHUD showInfoWithStatus:@"上传失败"];
                        }
                    }else{
                        [SVProgressHUD showInfoWithStatus:@"上传失败"];
                    }
                    
                } Failure:^(NSError *error) {
                    
                    if (error) {
                        [SVProgressHUD showErrorWithStatus:@"请检查您的网络!"];
                    }
                    
                }];
                
            }];
        });
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - webview清楚缓存
- (void)cleanCacheAndCookie{
    
    // 获取
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        
        [cookieJar deleteCookie:cookie];
    
    }
   
}

#pragma mark - private methods
//计算缓存数据大小
//计算出大小
- (NSString *)fileSizeWithInterge:(NSInteger)size{
    // 1k = 1024, 1m = 1024k
    if (size < 1024) {// 小于1k
        return [NSString stringWithFormat:@"%ldB",(long)size];
    }else if (size < 1024 * 1024){// 小于1m
        CGFloat aFloat = size/1024;
        return [NSString stringWithFormat:@"%.0fK",aFloat];
    }else if (size < 1024 * 1024 * 1024){// 小于1G
        CGFloat aFloat = size/(1024 * 1024);
        return [NSString stringWithFormat:@"%.1fM",aFloat];
    }else{
        CGFloat aFloat = size/(1024*1024*1024);
        return [NSString stringWithFormat:@"%.1fG",aFloat];
    }
}

#pragma mark - 获取当前时间戳

-(NSInteger )getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSInteger timeSp = [datenow timeIntervalSince1970]*1000;
    
    return timeSp;
}

#pragma mark - getters and setters
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, cl_kScreenWidth, cl_kScreenHeight - cl_kNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"SettingTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor colorWithHex:0xf5f5f5];
    }
    return _tableView;
}

- (NSArray *)dataArray
{
    if (!_dataArray) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"SettingItemList" ofType:@"plist"];
        
        _dataArray = [NSArray arrayWithContentsOfFile:path];
    }
    
    return _dataArray;
}

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