//
//  CTAPIBaseManager.m
//  SocialSecurity
//
//  Created by 雷俊博 on 2019/7/15.
//  Copyright © 2019 KK. All rights reserved.
//

#import "CTAPIBaseManager.h"
#import "CTApiProxy.h"

@interface CTAPIBaseManager ()

@property (nonatomic, strong) AFHTTPRequestSerializer *httpRequestSerializer;

@property (nonatomic, strong) AFHTTPRequestSerializer *httpRequestSerializer2;

@property (nonatomic, strong) NSMutableArray *requestIdList;

@end

@implementation CTAPIBaseManager

#pragma mark - life cycle

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    [self cancelAllRequests];
    self.requestIdList = nil;
    NSLog(@"CTAPIBaseManager已销毁");
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

#pragma mark - public methods
- (void)cancelAllRequests
{
    [[CTApiProxy sharedInstance] cancelRequestWithRequestIDList:self.requestIdList];
    [self.requestIdList removeAllObjects];
}

- (void)cancelRequestWithRequestId:(NSInteger)requestID
{
    [self removeRequestIdWithRequestID:requestID];
    [[CTApiProxy sharedInstance] cancelRequestWithRequestID:@(requestID)];
}

- (void)loadDataWithUrl:url params:(NSDictionary *)params success:(void (^)(id responseObject))successCallback fail:(void (^)(NSError *))failCallback
{
    NSMutableURLRequest *request = [self.httpRequestSerializer requestWithMethod:@"GET" URLString:url parameters:params error:nil];
    
    NSNumber *requestId = [[CTApiProxy sharedInstance]callApiWithRequest:request success:^(id  _Nonnull response) {
        
        if (successCallback) {
            successCallback(response);
        }
    } fail:^(id  _Nonnull response) {
        if (failCallback) {
            failCallback(response);
        }
        
    }];
    [self.requestIdList addObject:requestId];
}

- (void)loadData2WithUrl:url params:(NSDictionary *)params success:(void (^)(id responseObject))successCallback fail:(void (^)(NSError *))failCallback
{
    NSMutableURLRequest *request = [self.httpRequestSerializer2 requestWithMethod:@"POST" URLString:url parameters:params error:nil];
    
    NSNumber *requestId = [[CTApiProxy sharedInstance]callApiWithRequest:request success:^(id  _Nonnull response) {
        
        if (successCallback) {
            successCallback(response);
        }
    } fail:^(id  _Nonnull response) {
        if (failCallback) {
            failCallback(response);
        }
        
    }];
    [self.requestIdList addObject:requestId];
}

- (void)POSTWithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(id responseObject))successCallback fail:(void (^)(NSError *))failCallback
{
    NSMutableURLRequest *request = [self.httpRequestSerializer requestWithMethod:@"POST" URLString:url parameters:params error:nil];
    
    NSNumber *requestId = [[CTApiProxy sharedInstance]callApiWithRequest:request success:^(id  _Nonnull response) {
        
        if (successCallback) {
            successCallback(response);
        }
    } fail:^(id  _Nonnull response) {
        if (failCallback) {
            failCallback(response);
        }
        
    }];
    [self.requestIdList addObject:requestId];
}



+(void)GET:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:url parameters:params headers:nil progress:nil  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"JSON:%@",responseObject);
        complete(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
        complete(nil,error);
    }];
    
}



+(void)GET2:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
    [manager GET:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"JSON:%@",responseObject);
        complete(responseObject,nil);
        NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;

        NSLog(@">>>>%ld",(long)r.statusCode);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
        complete(nil,error);
    }];
    
}

+(void)GET3:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                  NSLog(@"result:%@",result);
                  complete(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
        complete(nil,error);
    }];
    
}

+(void)POST:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
   
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
   [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    if ([url containsString:@"score/increateScore"]) {
        NSString* oldAgent =  [manager.requestSerializer valueForHTTPHeaderField:@"User-Agent"];
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        app_Version = [app_Version stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSString*newAgent = [NSString stringWithFormat:@"kkLifeIos#%@#%@",app_Version,oldAgent];
        [manager.requestSerializer setValue:newAgent forHTTPHeaderField:@"User-Agent"];
    }
    
    NSLog(@"url:%@",url);
    NSLog(@"prams:%@",params);
    
    
    
    [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"JSON:%@",responseObject);
        
       
      
        
        complete(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
        complete(nil,error);
    }];
}


+ (void)POST2:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/xml",@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"JSON:%@",responseObject);
        complete(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
        complete(nil,error);
    }];
}

+ (void)POST3:(NSString *)url params:(NSDictionary *)params completionHandler:(nonnull void (^)(id _Nonnull, NSError * _Nonnull, id _Nonnull))complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"JSON:%@",responseObject);
        
        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
            NSLog(@"%@",[r allHeaderFields]);
            if (r.statusCode == 200) {
                complete(responseObject,nil,[r allHeaderFields]);
                return ;
            }
            
        }
        complete(responseObject,nil,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@",error);
        complete(nil,error,nil);
    }];
}

+ (void)POST4:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
       [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
       manager.requestSerializer.timeoutInterval = 5.0;
       [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
     
        //设置请求体数据为json类型
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //设置响应体数据为json类型
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
   [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       NSLog(@"JSON:%@",responseObject);
       complete(responseObject,nil);
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       NSLog(@"Error: %@",error);
       complete(nil,error);
   }];
}

+ (void)POST5:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //设置请求体数据为json类型
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //设置响应体数据为json类型
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
       [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];

        manager.requestSerializer.timeoutInterval = 10.f;

        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    
   [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       NSLog(@"JSON:%@",responseObject);
       complete(responseObject,nil);
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       NSLog(@"Error: %@",error);
       complete(nil,error);
   }];
}


+ (void)POST6:(NSString *)url params:(NSDictionary *)params completionHandler:(void (^)(id responseObject, NSError *error))complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
     
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
     
     
     [manager POST:url parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"JSON:%@",responseObject);
         
        
       
         
         complete(responseObject,nil);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"Error: %@",error);
         complete(nil,error);
     }];
}



#pragma mark - private methods
- (void)removeRequestIdWithRequestID:(NSInteger)requestId
{
    NSNumber *requestIDToRemove = nil;
    for (NSNumber *storedRequestId in self.requestIdList) {
        if ([storedRequestId integerValue] == requestId) {
            requestIDToRemove = storedRequestId;
        }
    }
    if (requestIDToRemove) {
        [self.requestIdList removeObject:requestIDToRemove];
    }
}

#pragma mark - getters and setters
- (AFHTTPRequestSerializer *)httpRequestSerializer
{
    if (_httpRequestSerializer == nil) {
        _httpRequestSerializer = [AFHTTPRequestSerializer serializer];
        [_httpRequestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
         [_httpRequestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    }
    return _httpRequestSerializer;
}


- (AFHTTPRequestSerializer *)httpRequestSerializer2
{
    if (_httpRequestSerializer2 == nil) {
        _httpRequestSerializer2 = [AFHTTPRequestSerializer serializer];
         [_httpRequestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
    }
    return _httpRequestSerializer2;
}

- (NSMutableArray *)requestIdList
{
    if (_requestIdList == nil) {
        _requestIdList = [[NSMutableArray alloc] init];
    }
    return _requestIdList;
}

+ (AFSecurityPolicy*)getSecurityPolicy{
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"public" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    NSSet *certSet = [NSSet setWithObject:certData];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    policy.allowInvalidCertificates = YES;
    policy.validatesDomainName = NO;
    policy.pinnedCertificates = certSet;
    /**** SSL Pinning ****/
    return policy;
}



@end
