//
//  netWorkManager.m
//  隐私保护
//
//  Created by xd h on 2023/10/8.
//

#import "netWorkManager.h"
#import "AFNetworkReachabilityManager.h"
#import "AFHTTPSessionManager.h"


@interface netWorkManager ()
{
    AFHTTPSessionManager *manager;
    NSString *mCloudService;
    //NSString *mRequstAPI;

}

@end


@implementation netWorkManager

static netWorkManager *Game_NetWorkShareInstance = nil;
+(netWorkManager *)shareInstance;
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        Game_NetWorkShareInstance = [[netWorkManager alloc]init];
        
    });
    
    return Game_NetWorkShareInstance;
}

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

- (void)initManager
{
    mCloudService = CloudService;
   
    
    if ([mCloudService rangeOfString:@"https"].location != NSNotFound)
    {
        manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:mCloudService]];
    }
    else
    {
        manager = [AFHTTPSessionManager manager];
    }
    
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setHTTPShouldHandleCookies:NO];
    [manager.requestSerializer setHTTPShouldUsePipelining:NO];
    manager.responseSerializer.acceptableContentTypes  =  [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",@"application/xml",@"image/png", @"audio/aac", @"text/x-vcard",nil];
    
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", nil];
    // 请求头里添加版本号
    //[manager.requestSerializer setValue:@"1.0" forHTTPHeaderField:@"rc-sdk"];
    //[manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"rc-platform"]; //iOS 1 安卓0
    
//    NSString *version = [NSString stringWithFormat:@"v%@", [IPhoneInfoAndToolsManager appVersion]];
//    NSString *uuid    = [IPhoneInfoAndToolsManager phoneDeviceUuid];
//    [manager.requestSerializer setValue:version forHTTPHeaderField:@"versionName"];
//    [manager.requestSerializer setValue:uuid forHTTPHeaderField:@"devicesId"];
//    [manager.requestSerializer setValue:@"4" forHTTPHeaderField:@"client"];
    
    if ([mCloudService rangeOfString:@"https"].location != NSNotFound)
    {
        //[manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    
    // 客户端是否信任非法证书
//    manager.securityPolicy.allowInvalidCertificates = YES;
//     // 是否在证书域字段中验证域名
//    [manager.securityPolicy setValidatesDomainName:NO];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//    manager.securityPolicy.allowInvalidCertificates = YES; //还是必须设成YES
    
    // 设置超时时间(设置有效)
    //[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30;
    //[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
}


#pragma - mark 证书相关
//- (AFSecurityPolicy*)customSecurityPolicy
//{
//    // /先导入证书
//    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"ca" ofType:@"cer"];//证书的路径
//
//    if ([@"https://client.androidscloud.com" isEqualToString:RC_Game_SDK_CloudService])
//    {
//        cerPath = [[NSBundle mainBundle] pathForResource:@"release" ofType:@"cer"];//证书的路径
//    }
//
//
//    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
//
//    // AFSSLPinningModeCertificate 使用证书验证模式、、、//AFSSLPinningModeNone  不使用SSLPinning  //AFSSLPinningModeCertificate  使用SSLPinning
//    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//
//    if ([@"https://test.androidscloud.com" isEqualToString:RC_Game_SDK_CloudService])
//    {
//        securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//    }
//
//
//    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
//    // 如果是需要验证自建证书，需要设置为YES
//    securityPolicy.allowInvalidCertificates = YES;
//
//    //validatesDomainName 是否需要验证域名，默认为YES；
//    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
//    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
//    //如置为NO，建议自己添加对应域名的校验逻辑。
//    securityPolicy.validatesDomainName = NO;
//
//    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:certData, nil];
//
//    return securityPolicy;
//}



#pragma mark  afnetwork  post 请求
- (void)CommonPostCallBackCode:(NSString*)code  Parameters:(NSDictionary*)dict success:(netWork_Success)success failure:(netWork_Faild)failure
{
    
    NSString *curServer = mCloudService;
    
    HLog(@"地址：%@ \n接口名称：%@,\n 参数:%@\n",curServer,code,dict);
    
    NSString *url = [NSString stringWithFormat:@"%@%@",curServer,code];
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
    {// 无网络状态
        NSDictionary *responseObject = @{@"code" : @(-999), @"msg" : @"当前网络不可用", @"data" : @""};
        mainBlock(^{
            success(responseObject);
        });
        return;
    }
    
    
    [manager POST:url parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        HLog(@"接口名称：%@ 接口返回：%@,\n ",code,responseObject);
        
        success(responseObject);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
        failure(error);
        HLog(@"%@", error);
    }];
}


#pragma mark afnetwork  get 请求
- (void)CommonGetWithCallBackCode:(NSString *)code Parameters:(NSDictionary *_Nullable)dic success:(netWork_Success)success failure:(netWork_Faild)faildStr
{
    
    NSString *curServer = mCloudService;

    NSString *url = [NSString stringWithFormat:@"%@%@",curServer,code];
    
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
    {// 无网络状态
        NSDictionary *responseObject = @{@"status" : @(-999), @"msg" : @"当前网络不可用", @"data" : @""};
        success(responseObject);
        return;
    }
    
    HLog(@"地址：%@%@,\n 参数:%@\n",curServer,code,dic);
    
    [manager GET:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        HLog(@"接口名称：%@,返回：%@,\n ",code,responseObject);
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
        faildStr(error);
        HLog(@"%@", error);
    }];
}

@end
