//
//  PersonInfoViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/7/22.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "PersonInfoViewController.h"
#import "SettingTableViewCell.h"

#import "UIImageView+WebCache.h"

#import "PFModel.h"
#import "PFInfoSelectView.h"

#import "ChangeUserInfoViewController.h"
#import "KKUserAuthViewController.h"
#import "KKUserAuthSuccessViewController.h"
#import "SWCenterDatePickerView.h"

#import "ChooseLocationView.h"

#import "CitiesDataTool.h"

#import "BirthdayView.h"

#import "PrizeInfoCommitSuccessAlertView.h"


//穿山甲
#import <BUAdSDK/BUAdSDK.h>



@interface PersonInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SWCenterDatePickerViewDelegate,UIGestureRecognizerDelegate,BUNativeExpressAdViewDelegate>
{
    BOOL haveBirth;
}

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSArray *dataArray;

@property (nonatomic, strong)PFModel *model;

@property (nonatomic,strong) ChooseLocationView *chooseLocationView;

@property (nonatomic,strong) UIView  *cover;

@property (nonatomic, strong) LVDatePickerModel *birth;

@property (strong, nonatomic) BUNativeExpressAdManager *nativeExpressAd3Manager;

@property (nonatomic, strong)UIView* xmADView;

@end

@implementation PersonInfoViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    
    [self getPersonSupplementaryInfoRequest];
    
    [[CitiesDataTool sharedManager]requestAllProvince];
    
    
}

#pragma mark - 获取个人补充信息接口
- (void)getPersonSupplementaryInfoRequest
{
    NSString *url = [NSString stringWithFormat:@"%@socialsecurity/personService/getPersonInfo",[NetworkConfig ipKKSBConfig]];
    
    NSDictionary *params = @{
        @"userid":@([getPeopleID PeopleID]),
        @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
    };
    
    [BaseNetManager POST:url parameters:params completionHandler:^(id responseObj, NSError *error) {
        
        if (error) {
            NSLog(@"error:%@",error);
            return;
        }
        
        if ([responseObj isKindOfClass:[NSDictionary class]]) {
            NSString *code = [NSString stringWithFormat:@"%@",responseObj[@"code"]];
            if ([code isEqualToString:@"0"]) {
                self.model = [PFModel mj_objectWithKeyValues:responseObj[@"result"]];
                if (![Tools isBlankString:self.model.birthStr]) {
                    self->haveBirth = YES;
                }
                
                [self.tableView reloadData];
            }
        }
        
        NSLog(@"responseObj:%@",responseObj);
        
    }];
}

#pragma mark - 更新个人信息

- (void)uploadPersonInfoRequestWithKey:(NSString *)key value:(NSString *)value
{
    NSString *url = [NSString stringWithFormat:@"%@socialsecurity/personService/uploadPerson",[NetworkConfig ipKKSBConfig]];
    
    NSMutableDictionary *params = [@{
        @"userid":@([getPeopleID PeopleID]),
        @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
    } mutableCopy];
    
    [params setObject:value forKey:key];
    
    [KKLoadingAnimationView show];
    [BaseNetManager POST:url parameters:params completionHandler:^(id responseObj, NSError *error) {
        
        [KKLoadingAnimationView dismiss];
        if (error) {
            NSLog(@"error:%@",error);
            return;
        }
        
        if ([responseObj isKindOfClass:[NSDictionary class]]) {
            NSString *code = [NSString stringWithFormat:@"%@",responseObj[@"code"]];
            if ([code isEqualToString:@"0"]) {
                
                if ([responseObj[@"result"] isKindOfClass:[NSDictionary class]]) {
                    
                    NSDictionary *dic = (NSDictionary *)responseObj[@"result"];
                    NSString *plusScore = [NSString stringWithFormat:@"%@",dic[@"plusScore"]];
                    if (plusScore.integerValue > 0) {
                        if ([self.from isEqualToString:@"coinCenter"] && self.block) {
                            self.block(plusScore);
                        }else{
                            WeakSelf
                            [PrizeInfoCommitSuccessAlertView showReceiveViewWithVC:self Number:plusScore block:^(CTShareType type) {
                                [weakSelf.xmADView removeFromSuperview];
                            
                            }];
                            
                            [self showADView];
                        }
                        
                    }
                        
                        
                    
                }
               
                [self getPersonSupplementaryInfoRequest];
                
            }
        }
        
        NSLog(@"responseObj:%@",responseObj);
        
    }];
}


#pragma mark - 穿山甲广告 任务弹框
- (void)loadBUADData3
{
    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
    slot1.adSize = CGSizeMake(300, 300/375.0 * 123.5);
    slot1.ID = @"946421253";
    slot1.AdType = BUAdSlotAdTypeFeed;
    
    BUSize *imgSize = [BUSize sizeBy:BUProposalSize_Feed228_150];
    slot1.imgSize = imgSize;
    slot1.position = BUAdSlotPositionFeed;
    
    
    self.nativeExpressAd3Manager = [[BUNativeExpressAdManager alloc] initWithSlot:slot1 adSize:CGSizeMake(300, 300/375.0 * 123.5)];
    self.nativeExpressAd3Manager.delegate = self;
    
    [self.nativeExpressAd3Manager loadAdDataWithCount:1];
}


- (void)showADView
{
//    WeakSelf
//    [PrizeInfoCommitSuccessAlertView showReceiveViewWithVC:self Number:@"60" block:^(CTShareType type) {
//        [weakSelf.xmADView removeFromSuperview];
//
//    }];
    
    UIView * adView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth - 299) / 2, (ScreenHeight - 288) / 2 - 20 + 288 + 20, 299, 300/375.0 * 123.5 + 25)];

    adView.backgroundColor = [UIColor whiteColor];

    adView.layer.cornerRadius = 10 * WIDTHRADIU;

    [self.view addSubview:adView];

    self.xmADView = adView;
    
    [self loadBUADData3];
}



#pragma mark - 获取生肖
-(NSString *)getZodiacWithYear:(NSInteger)a{
    if (a <0) {
        return @"错误日期格式!!!";
    }
    NSString *shengxiao = @"";
    
    if (a % 12 == 0) {
        shengxiao = @"猴";
    }
    else if (a % 12 == 1){
        shengxiao = @"鸡";
    }
    else if (a % 12 == 2){
        shengxiao = @"狗";
    }
    else if (a % 12 == 3){
        shengxiao = @"猪";
    }
    else if (a % 12 == 4){
        shengxiao = @"鼠";
    }
    else if (a % 12 == 5){
        shengxiao = @"牛";
    }
    else if (a % 12 == 6){
        shengxiao = @"虎";
    }
    else if (a % 12 == 7){
        shengxiao = @"兔";
    }
    else if (a % 12 == 8){
        shengxiao = @"龙";
    }
    else if (a % 12 == 9){
        shengxiao = @"蛇";
    }
    else if (a % 12 == 10){
        shengxiao = @"马";
    }
    else if (a % 12 == 11){
        shengxiao = @"羊";
    }
    
    return shengxiao;
    
}


#pragma mark - //得到星座的算法
-(NSString *)getAstroWithMonth:(NSInteger)m day:(NSInteger)d{
    
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    
    NSString *astroFormat = @"102123444543";
    
    NSString *result;
    
    if (m<1||m>12||d<1||d>31){
        
        return @"错误日期格式!";
        
    }
    
    if(m==2 && d>29)
        
    {
        
        return @"错误日期格式!!";
        
    }else if(m==4 || m==6 || m==9 || m==11) {
        
        if (d>30) {
            
            return @"错误日期格式!!!";
            
        }
        
    }
    
    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]];
    
    return [result stringByAppendingString:@"座"];
    
}


#pragma mark - 更新出生年月 以及属相 星座
- (void)upDateBirthInfoRequestWithbirthYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day
{
    NSString *url = [NSString stringWithFormat:@"%@socialsecurity/personService/uploadPerson",[NetworkConfig ipKKSBConfig]];
    
    NSMutableDictionary *params = [@{
        @"userid":@([getPeopleID PeopleID]),
        @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
    } mutableCopy];
    
    NSString *zodiac = [self getZodiacWithYear:year];
    
    NSString *constellation = [self getAstroWithMonth:month day:day];
    
    [params setObject:[NSString stringWithFormat:@"%@-%@-%@",@(year),month < 10 ? [NSString stringWithFormat:@"0%ld",month] : @(month),day < 10 ? [NSString stringWithFormat:@"0%ld",day] : @(day)] forKey:@"birthStr"];
    [params setObject:zodiac forKey:@"zodiac"];
    [params setObject:constellation forKey:@"constellation"];
    
    [KKLoadingAnimationView show];
    [BaseNetManager POST:url parameters:params completionHandler:^(id responseObj, NSError *error) {
        
        [KKLoadingAnimationView dismiss];
        if (error) {
            NSLog(@"error:%@",error);
            return;
        }
        
        if ([responseObj isKindOfClass:[NSDictionary class]]) {
            NSString *code = [NSString stringWithFormat:@"%@",responseObj[@"code"]];
            if ([code isEqualToString:@"0"]) {
                
                if ([responseObj[@"result"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic = (NSDictionary *)responseObj[@"result"];
                    NSString *plusScore = [NSString stringWithFormat:@"%@",dic[@"plusScore"]];
                    if (plusScore.integerValue > 0) {
                        if ([self.from isEqualToString:@"coinCenter"] && self.block) {
                            self.block(plusScore);
                        }else{
                            WeakSelf
                            [PrizeInfoCommitSuccessAlertView showReceiveViewWithVC:self Number:plusScore block:^(CTShareType type) {
                                [weakSelf.xmADView removeFromSuperview];
                            
                            }];
                            
                            [self showADView];
                        }
                    }
                    
                }
               
                [self getPersonSupplementaryInfoRequest];
                
            }
        }
        
        NSLog(@"responseObj:%@",responseObj);
        
    }];
}

#pragma mark - 更新地址信息
- (void)uploadLocationWithProvince:(NSString *)province city:(NSString *)city county:(NSString *)county
{
    NSString *url = [NSString stringWithFormat:@"%@socialsecurity/personService/uploadPerson",[NetworkConfig ipKKSBConfig]];
    
    NSMutableDictionary *params = [@{
        @"userid":@([getPeopleID PeopleID]),
        @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
    } mutableCopy];
    
    [params setObject:province forKey:@"provincename"];
    [params setObject:city forKey:@"cityname"];
    [params setObject:county forKey:@"countryname"];
    
    [KKLoadingAnimationView show];
    [BaseNetManager POST:url parameters:params completionHandler:^(id responseObj, NSError *error) {
        
        [KKLoadingAnimationView dismiss];
        if (error) {
            NSLog(@"error:%@",error);
            return;
        }
        
        if ([responseObj isKindOfClass:[NSDictionary class]]) {
            NSString *code = [NSString stringWithFormat:@"%@",responseObj[@"code"]];
            if ([code isEqualToString:@"0"]) {
                
                if ([responseObj[@"result"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic = (NSDictionary *)responseObj[@"result"];
                    NSString *plusScore = [NSString stringWithFormat:@"%@",dic[@"plusScore"]];
                    if (plusScore.integerValue > 0) {
                        if ([self.from isEqualToString:@"coinCenter"] && self.block) {
                            self.block(plusScore);
                        }else{
                            WeakSelf
                            [PrizeInfoCommitSuccessAlertView showReceiveViewWithVC:self Number:plusScore block:^(CTShareType type) {
                                [weakSelf.xmADView removeFromSuperview];
                            
                            }];
                            
                            [self showADView];
                        }
                       
                    }
                    
                }
               
                [self getPersonSupplementaryInfoRequest];
                
            }
        }
        
        NSLog(@"responseObj:%@",responseObj);
        
    }];
}


#pragma mark - 判断账户是否已实名
- (NSDictionary *)judgeAccountAuthRequestParams {
    NSString*tel =  [getPeopleID PeopleIphoneNmber];
    
    tel = [EnercryTool AES256Encrypt:tel key:DESKEY];
    NSDictionary *dic = @{
           @"tel":tel
       };
    
    return dic;
}

- (void)judgeAccountAuthStateRequest {
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipESSCConfig],KKCheckAccountStateRequest];
    NSLog(@"判断账户是否已实名url:%@",urlString);
    NSLog(@"params:%@",[self judgeAccountAuthRequestParams]);
    [KKLoadingAnimationView show];
    [NetworkRequest SBAuthPost:urlString Params:[self judgeAccountAuthRequestParams] Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString* code = [NSString stringWithFormat:@"%@",objc[@"state"]];
            NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
            if ([code isEqualToString:@"200"]) {
                
                if ([objc[@"result"] isKindOfClass:[NSDictionary class]]) {
                    NSString* idcard = [NSString stringWithFormat:@"%@",objc[@"result"][@"idcard"]];
                    NSString* name = [NSString stringWithFormat:@"%@",objc[@"result"][@"name"]];
                    
                    KKUserAuthSuccessViewController* vc = [KKUserAuthSuccessViewController new];
                    vc.nameTT = name;
                    vc.numTT = idcard;
                    vc.type = KKUserAuthFromVCTypeAccount;
                    vc.title = @"实名认证";
                    vc.from = @"personInfo";
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
            }else if ([code isEqualToString:@"204"]) {
                KKUserAuthViewController* vc = [KKUserAuthViewController new];
                vc.title = @"实名认证";
                vc.type = KKUserAuthFromVCTypeAccount;
                vc.block = ^(BOOL success) {
                    [self.tableView reloadData];
                };
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                [self alertShowMessage:describe];
            }
        }else{
            [self alertShowMessage:@"服务器异常"];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShowMessage:@"网络异常"];
        
    }];
}

#pragma mark - 提示
- (void)alertShowMessage:(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 - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *items = self.dataArray[section];
    
    return items.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *items = self.dataArray[indexPath.section];
    
    NSString *title = items[indexPath.item];
    
    SettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.lb_Title.text = title;
    
    cell.lb_Title.textColor = [UIColor colorWithHex:0x4d4d4d];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NSURL *url = [getPeopleID PeoplePhoto];
            if (url) {
                
                if (self.model && ![Tools isBlankString:self.model.sex]){
                    if ([self.model.sex isEqualToString:@"男"]) {
                        [cell.img_Photo sd_setImageWithURL:[getPeopleID PeoplePhoto] placeholderImage:[UIImage imageNamed:@"userDefaultIcon_man"]];
                    }else if ([self.model.sex isEqualToString:@"女"]){
                        [cell.img_Photo sd_setImageWithURL:[getPeopleID PeoplePhoto] placeholderImage:[UIImage imageNamed:@"userDefaultIcon_woman"]];
                    }else{
                        [cell.img_Photo sd_setImageWithURL:[getPeopleID PeoplePhoto] placeholderImage:[UIImage imageNamed:@"userDefaultIcon_man"]];
                    }
                }else{
                    [cell.img_Photo sd_setImageWithURL:[getPeopleID PeoplePhoto] placeholderImage:[UIImage imageNamed:@"userDefaultIcon_man"]];
                }
                
                
                
            }else{
                
                if (self.model && ![Tools isBlankString:self.model.sex]){
                    if ([self.model.sex isEqualToString:@"男"]) {
                        cell.img_Photo.image = [UIImage imageNamed:@"userDefaultIcon_man"];
                    }else if ([self.model.sex isEqualToString:@"女"]){
                        cell.img_Photo.image = [UIImage imageNamed:@"userDefaultIcon_woman"];
                    }else{
                        cell.img_Photo.image = [UIImage imageNamed:@"userDefaultIcon_man"];
                    }
                }else{
                    cell.img_Photo.image = [UIImage imageNamed:@"userDefaultIcon_man"];
                }
                
                
                
            }
           
        }else if (indexPath.row == 1){
            
            if ([Tools isBlankString:[getPeopleID Peopletitle]]) {
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }else{
                cell.lb_Content_ArrowShow.text = [getPeopleID Peopletitle];
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }
            
            
        }else if (indexPath.row == 2){
            if (self.model && ![Tools isBlankString:self.model.sex]) {
                cell.lb_Content_ArrowShow.text = self.model.sex;
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }
        }else if (indexPath.row == 3){
            
            if (self.model && ![Tools isBlankString:self.model.birthStr]) {
                cell.lb_Content_ArrowShow.text = self.model.birthStr;
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }
            
        }else if (indexPath.row == 4){
            
            if (self.model && ![Tools isBlankString:self.model.zodiac]) {
                cell.lb_Content_ArrowShow.text = self.model.zodiac;
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }
            
        }else if (indexPath.row == 5){
            
            if (self.model && ![Tools isBlankString:self.model.constellation]) {
                cell.lb_Content_ArrowShow.text = self.model.constellation;
                cell.lb_Content_ArrowShow.textColor =  [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }
            
        }
        
        if (self.model && ![Tools isBlankString:self.model.birthStr]) {
            cell.line.hidden = (indexPath.row == 5);
        }else{
            cell.line.hidden = (indexPath.row == 3);
        }
        
        
    }else if (indexPath.section == 1){
        
        if (indexPath.row == 0) {
            
            if (self.model && ![Tools isBlankString:self.model.provincename]) {
                cell.lb_Content_ArrowShow.text = [NSString stringWithFormat:@"%@%@%@",self.model.provincename,self.model.cityname,self.model.countryname];
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }
            
        }else if (indexPath.row == 1){
            
            if (self.model && ![Tools isBlankString:self.model.profession]) {
                cell.lb_Content_ArrowShow.text = self.model.profession;
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor =  [UIColor colorWithHex:0x808080];
            }
            
        }else if (indexPath.row == 2){
            if (self.model && ![Tools isBlankString:self.model.education]) {
                cell.lb_Content_ArrowShow.text = self.model.education;
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0xb3b3b3];
            }else{
                cell.lb_Content_ArrowShow.text = @"未填写";
                cell.lb_Content_ArrowShow.textColor = [UIColor colorWithHex:0x808080];
            }
        }
        cell.line.hidden = (indexPath.row == 2);
        
    }else if (indexPath.section == 2){
        cell.lb_Content_ArrowShow.textColor = K_MainColor;
        
        BOOL accountState = [getPeopleID accountState];
        
        cell.lb_Content_ArrowShow.text = accountState ? @"已实名" : @"未实名";
        
        cell.line.hidden = (indexPath.row == 0);
    }
    
    cell.img_Photo.hidden = !(indexPath.section == 0 && indexPath.row == 0);
    
    cell.img_Arrow.hidden = (indexPath.section == 0 && (indexPath.row == 4 || indexPath.row == 5));
    
    
    
    
    
    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 == 2) {
        return 0.0;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc]init];
    header.backgroundColor = [UIColor clearColor];
    return header;
}
- (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];
    
    
    
//    [self showADView];
//    
//    return;
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            [self changeHeadView1];
        }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 == 2){
            
            NSArray *sexArray = @[@"男",@"女",@"保密"];
            
            [PFInfoSelectView showSelectViewWithDataArray:sexArray block:^(NSString * _Nonnull result) {
                if (result) {
                    [self uploadPersonInfoRequestWithKey:@"sex" value:result];
                }
            }];
            
            
            
        }else if (indexPath.row == 3){
//            SWCenterDatePickerView *view = [[SWCenterDatePickerView alloc] initDatePickerViewWithType:DatePickerViewType_YMD Delegate:self];
//            //view.currentTime = self.selectDateStr;
//            [view showDatePickerView];
            
            [self addDatePicker];
        }
        
    }else if (indexPath.section == 1){
        
        if (indexPath.row == 0) {
            [[UIApplication sharedApplication].keyWindow addSubview:self.cover];
            
            [self addressShow];
        }else if (indexPath.row == 1){
            NSArray *professionArray = @[@"IT互联网",@"文化传媒",@"金融",@"教育培训",@"医疗生物",@"政府组织",@"工业制造",@"餐饮出行",@"服务业",@"其他"];
            
            [PFInfoSelectView showSelectViewWithDataArray:professionArray block:^(NSString * _Nonnull result) {
                if (result) {
                    [self uploadPersonInfoRequestWithKey:@"profession" value:result];
                }
            }];
        }else if (indexPath.row == 2){
            NSArray *educationArray = @[@"初中以下",@"初中",@"中专",@"高中",@"大专",@"本科",@"硕士及以上"];
            
            [PFInfoSelectView showSelectViewWithDataArray:educationArray block:^(NSString * _Nonnull result) {
                if (result) {
                    [self uploadPersonInfoRequestWithKey:@"education" value:result];
                }
            }];
        }
        
    }else if (indexPath.section == 2){
        
        if (indexPath.row == 0) {
            [self judgeAccountAuthStateRequest];
        }
        
    }
  
    
    
}


#pragma mark - SWCenterDatePickerViewDelegate
- (void)selectWithSelectTime:(NSString *)selectTime withYear:(NSString *)year withMonth:(NSString *)month{
//    self.selectDateStr = selectTime;
//
//    self.timeLab.text = [NSString stringWithFormat:@"当前选择：%@",selectTime];
}

- (void)selectWithSelectTime:(NSString *)selectTime withYear:(NSString *)year withMonth:(NSString *)month withDay:(NSString *)day{
//    self.selectDateStr = selectTime;
//    
//    self.timeLab.text = [NSString stringWithFormat:@"当前选择：%@",selectTime];
    
    [self upDateBirthInfoRequestWithbirthYear:year.integerValue month:month.integerValue day:day.integerValue];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    
    CGPoint point = [gestureRecognizer locationInView:gestureRecognizer.view];
    
    if (gestureRecognizer.view == self.cover){
        if (CGRectContainsPoint(_chooseLocationView.frame, point)){
             
                return NO;
            
        }
    }
    
    
    
    return YES;
}

#pragma mark - BUNativeExpressAdViewDelegate
- (void)nativeExpressAdSuccessToLoad:(BUNativeExpressAdManager *)nativeExpressAd views:(NSArray<__kindof BUNativeExpressAdView *> *)views {
    
    if (views.count > 0) {
        [views enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
                    expressView.rootViewController = self;
                    // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                    [expressView render];
        }];
        
        BUNativeExpressAdView *adView = views[0];
        [self.xmADView addSubview:adView];
        [adView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
    }
    
   
    [self pbud_logWithSEL:_cmd msg:@""];
}

- (void)nativeExpressAdFailToLoad:(BUNativeExpressAdManager *)nativeExpressAd error:(NSError *)error {
    
    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"error:%@", error]];
    
    [self.xmADView removeFromSuperview];
    
}

- (void)nativeExpressAdViewRenderSuccess:(BUNativeExpressAdView *)nativeExpressAdView {
    //[self.tableView reloadData];
    
}


- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView stateDidChanged:(BUPlayerPlayState)playerState {
    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"playerState:%ld", (long)playerState]];
}

- (void)nativeExpressAdViewRenderFail:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *)error {
    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"error:%@  此广告将会从列表中移除", error]];
    
    [self.xmADView removeFromSuperview];
    
   
    
//    [self.expressAdViews removeObject:nativeExpressAdView];
//    [self.tableView reloadData];
    
}

- (void)nativeExpressAdViewWillShow:(BUNativeExpressAdView *)nativeExpressAdView {
    [self pbud_logWithSEL:_cmd msg:@""];
}

- (void)nativeExpressAdViewDidClick:(BUNativeExpressAdView *)nativeExpressAdView {
    [self pbud_logWithSEL:_cmd msg:@""];
}

- (void)nativeExpressAdViewPlayerDidPlayFinish:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *)error {
    [self pbud_logWithSEL:_cmd msg:@""];
}

- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView dislikeWithReason:(NSArray<BUDislikeWords *> *)filterWords {
    
    
    [self.xmADView removeFromSuperview];
    
    
   
    
  
}

- (void)nativeExpressAdViewDidClosed:(BUNativeExpressAdView *)nativeExpressAdView {
    [self pbud_logWithSEL:_cmd msg:@""];
}

- (void)nativeExpressAdViewWillPresentScreen:(BUNativeExpressAdView *)nativeExpressAdView {
    [self pbud_logWithSEL:_cmd msg:@""];
}

- (void)nativeExpressAdViewDidCloseOtherController:(BUNativeExpressAdView *)nativeExpressAdView interactionType:(BUInteractionType)interactionType {
    NSString *str;
    if (interactionType == BUInteractionTypePage) {
        str = @"ladingpage";
    } else if (interactionType == BUInteractionTypeVideoAdDetail) {
        str = @"videoDetail";
    } else {
        str = @"appstoreInApp";
    }
    [self pbud_logWithSEL:_cmd msg:str];
}


- (void)pbud_logWithSEL:(SEL)sel msg:(NSString *)msg {
    //BUD_Log(@"SDKDemoDelegate BUNativeExpressFeedAdView In VC (%@) extraMsg:%@", NSStringFromSelector(sel), msg);
}



#pragma mark - 日期弹框
- (void)addDatePicker{
    BirthdayView *vc = [[BirthdayView alloc] init];
    [self.view addSubview:vc];
    vc.birthDay = self.birth;
    
    WeakSelf;
    vc.timeBlock = ^(LVDatePickerModel *birth) {
        weakSelf.birth = birth;
        //weakSelf.timeLabel.text = [NSString stringWithFormat:@"%@-%@-%@",birth.year,birth.month,birth.day];
        
        if (birth) {
            [self upDateBirthInfoRequestWithbirthYear:birth.year.integerValue month:birth.month.integerValue day:birth.day.integerValue];
        }
    };
    [vc showBirthView];
}



#pragma mark - 更改头像
-(void)changeHeadView1
{
    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];
}

#pragma mark - 拍照
-(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(@"模拟器无法打开照相机");
    }
}

#pragma mark - 相册
-(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;
        }];
    });
    //主线程
    
}

#pragma mark - UIImagePickerControllerDelegate
-(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 - 显示地址选择
/** 弹出此弹窗 */
- (void)addressShow {
    [UIView animateWithDuration:0.25 animations:^{
        //self.transform =CGAffineTransformMakeScale(0.95, 0.95);
    }];
    self.cover.hidden = NO;
    self.chooseLocationView.hidden = NO;
    self.chooseLocationView.frame =CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 350);
    
    [UIView animateWithDuration:0.25 animations:^{
        self.chooseLocationView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 350, [UIScreen mainScreen].bounds.size.width, 350);
    }];
}

/** 移除此弹窗 */
- (void)addressDismiss {
    [UIView animateWithDuration:0.25 animations:^{
        self.chooseLocationView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 350);
        
    } completion:^(BOOL finished) {
        self.chooseLocationView.hidden = YES;
        self.cover.hidden = YES;
        [self.cover removeFromSuperview];
    }];
}

- (void)tapCover:(UITapGestureRecognizer *)tap{
    
    [self addressDismiss];
}


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

    }
    return _tableView;
}

- (NSArray *)dataArray
{
    
    if (haveBirth) {
        _dataArray = @[@[@"头像",@"昵称",@"性别",@"生日",@"生肖",@"星座"],@[@"所在地区",@"职业",@"学历"],@[@"实名认证"]];
    }else{
        _dataArray = @[@[@"头像",@"昵称",@"性别",@"生日"],@[@"所在地区",@"职业",@"学历"],@[@"实名认证"]];
    }
    
    return _dataArray;
}

- (ChooseLocationView *)chooseLocationView{
    
    if (!_chooseLocationView) {
       _chooseLocationView = [[ChooseLocationView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 350, [UIScreen mainScreen].bounds.size.width, 350)];
      
    }
    return _chooseLocationView;
}

- (UIView *)cover{

    if (!_cover) {
        _cover = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _cover.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
        [_cover addSubview:self.chooseLocationView];
        __weak typeof (self) weakSelf = self;
        _chooseLocationView.chooseFinish = ^{

            [UIView animateWithDuration:0.25 animations:^{
                __strong __typeof(self) strongSelf = weakSelf;
                
//                NSLog(@"%@,%@,%@",_chooseLocationView.province,_chooseLocationView.city,_chooseLocationView.county);
                if (![Tools isBlankString:strongSelf.chooseLocationView.province] && ![Tools isBlankString:strongSelf.chooseLocationView.city]  && ![Tools isBlankString:strongSelf.chooseLocationView.county]) {
                    [strongSelf uploadLocationWithProvince:strongSelf.chooseLocationView.province city:strongSelf.chooseLocationView.city county:strongSelf.chooseLocationView.county];
                }
                
                
                [strongSelf addressDismiss];
            }];
        };
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCover:)];
        [_cover addGestureRecognizer:tap];
        tap.delegate = self;
        //[self addressDismiss];
    }
    return _cover;
}

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