//
//  SSCardCollectViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/10/9.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SSCardCollectViewController.h"
#import "Constants.h"

#import "CTAPIBaseManager.h"

#import "SSCardAdultInfoCollectViewController.h"

@interface SSCardCollectViewController ()
{
    NSString *_accessToken;
}

@property (nonatomic, strong)UIImageView *img_Name;

@property (nonatomic, strong)UIButton *btn_adult;

@property (nonatomic, strong)UIButton *btn_child;


@end

@implementation SSCardCollectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.img_Name];
    [self.view addSubview:self.btn_adult];
    [self.view addSubview:self.btn_child];
    
    [self setupUI];
    
    [self getSSCardToken];
    
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self.img_Name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25 + cl_kNavigationBarHeight);
        make.centerX.offset(0);
        make.width.offset(329 * WIDTHRADIU);
        make.height.offset(56 * WIDTHRADIU);
    }];
    
    [self.btn_adult mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.img_Name.mas_bottom).offset(57);
        make.centerX.offset(0);
        make.width.offset(344 * WIDTHRADIU);
        make.height.offset(149 * WIDTHRADIU);
        
    }];
    
    [self.btn_child mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.btn_adult.mas_bottom).offset(57);
        make.centerX.offset(0);
        make.width.offset(343 * WIDTHRADIU);
        make.height.offset(168 * WIDTHRADIU);
        
    }];
}

- (void)setupUI
{
    UIButton *btn_back = [UIButton buttonWithType:UIButtonTypeCustom];
    btn_back.frame = CGRectMake(0, 0, 60, 40);
    
    [btn_back setTitle:@"返回" forState:UIControlStateNormal];
    [btn_back setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    btn_back.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn_back setImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    [btn_back addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [btn_back layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btn_back];
    if ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7) {
        UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negativeSpacer.width = -15;
        self.navigationItem.leftBarButtonItems = @[negativeSpacer, backItem];
    }else{
        self.navigationItem.leftBarButtonItem = backItem;
        
    }
    
    
    UIButton *checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame = CGRectMake(0, 0, 60, 40);
    [checkBtn setTitle:@"采集记录" forState:UIControlStateNormal];
    [checkBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    checkBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    
    [checkBtn addTarget:self action:@selector(checkCollectHistory) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *checkItem = [[UIBarButtonItem alloc]initWithCustomView:checkBtn];
    
    self.navigationItem.rightBarButtonItem = checkItem;
}


#pragma mark - api request
//获取accessToken
- (void)extracted:(NSDictionary *)params url:(NSString *)url {
    [CTAPIBaseManager POST3:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error, id  _Nonnull responseHeader) {
        [KKLoadingAnimationView dismiss];
        
        if (error) {
            NSLog(@"社保卡采集token的error:%@",error);
            
        }else{
            NSLog(@"社保卡采集token的responseObject:%@",responseObject);
        }
        
        
        if (responseHeader) {
            NSLog(@"社保卡采集token的responseHeader:%@",responseHeader);
            NSDictionary *responseHeaderDic = responseHeader;
            
            NSString *accessToken = responseHeaderDic[@"accesstoken"];
            
            if (![NSString blankString:accessToken]) {
                self->_accessToken = responseHeaderDic[@"accesstoken"];
                
                
            }
            NSLog(@"社保卡采集token的accessToken:%@",responseHeaderDic[@"accesstoken"]);
            
        }else{
            [SVProgressHUD showInfoWithStatus:@"token获取失败,请检查网络并退出重进"];
            return ;
        }
    }];
}

//获取社保卡采集token
- (void)getSSCardToken
{
    NSString *url = [NSString stringWithFormat:@"%@please/login",SSCardCollectBaseUrl];
    NSDictionary *params = @{
                             @"loginTel":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                             @"loginId":[NSNumber numberWithInteger:[getPeopleID PeopleID]]
                             };
    
    
    [KKLoadingAnimationView show];
    
    NSLog(@"社保卡采集token的url:%@",url);
    NSLog(@"params:%@",params);
    [self extracted:params url:url];
}

//采集记录
- (void)checkCollectHistory
{
    NSString *url = [NSString stringWithFormat:@"%@login/count",SSCardCollectBaseUrl];
    NSDictionary *params = @{
                             @"operateid":[NSNumber numberWithInteger:[getPeopleID PeopleID]]
                             };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
     
  
    [manager.requestSerializer setValue:_accessToken forHTTPHeaderField:@"accessToken"];
     
    [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"JSON:%@",responseObject);
        
        NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSNumber *result = responseObject[@"result"];
            NSString *message = [NSString stringWithFormat:@"当前账户已采集了:%@人",result];
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"采集人数(每小时更新一次)" message:message preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSLog(@"点击了确认按钮");
                }];
            
            [alertVc addAction:conform];
            
            [self presentViewController:alertVc animated:YES completion:nil];
        }else{
            [SVProgressHUD showInfoWithStatus:@"请检查您的网络"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
    }];
     
}



#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goToNextVC:(UIButton *)sender
{
    SSCardAdultInfoCollectViewController *adultVC = [[SSCardAdultInfoCollectViewController alloc]init];
    adultVC.title = @"个人信息";
    
    adultVC.accessToken = _accessToken;
    
    [self.navigationController pushViewController:adultVC animated:YES];
  
}


#pragma mark - getters and setters
- (UIImageView *)img_Name
{
    if (!_img_Name) {
        _img_Name = [[UIImageView alloc]init];
        _img_Name.image = [UIImage imageNamed:@"标题"];
    }
    return _img_Name;
}


- (UIButton *)btn_adult
{
    if (!_btn_adult) {
        _btn_adult = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_adult setBackgroundImage:[UIImage imageNamed:@"成人社保采集"] forState:UIControlStateNormal];
        [_btn_adult addTarget:self action:@selector(goToNextVC:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_adult;
}

- (UIButton *)btn_child
{
    if (!_btn_child) {
        _btn_child = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_child setBackgroundImage:[UIImage imageNamed:@"儿童社保采集"] forState:UIControlStateNormal];
    }
    return _btn_child;
}

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