//
//  OffcnBaseNetworking.m
//  OffcnIMSDKiOS
//
//  Created by vockey on 2018/7/25.
//  Copyright © 2018年 中公教育. All rights reserved.
//

#import "OffcnBaseNetworking.h"
#import "NSString+MD5.h"
#import "ZYJRealReachability.h"
#import "NSDictionary+NullReplacement.h"
#import "SDGeneralTool.h"
#import "SDConfigrationNetwork.h"
#import "ZYJMJExtension.h"
#import "SDGeneralDefine.h"
#import "ZYJOSSUtil.h"

static OffcnBaseNetworking *baseNetWorkApi;

@implementation OffcnBaseNetworking
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        baseNetWorkApi = [[OffcnBaseNetworking alloc]init];

        [GLobalRealReachability startNotifier];

    });
    return baseNetWorkApi;
}

+(NSString *)get_BASEURL{
    NSInteger type = [OffcnBaseNetworking sharedInstance].serviceType;
    if (type == 1) {
        return DEV_BASEURL;
    }else if (type == 2) {
        return TEST_BASEURL;
    }else if (type == 3) {
        return PRO_BASEURL;
    }
    return PRO_BASEURL;
}
//h5服务器
+(NSString *)get_h5live{
    NSInteger type = [OffcnBaseNetworking sharedInstance].serviceType;
    if (type == 1) {
        return DEV_h5live;
    }else if (type == 2) {
        return TEST_h5live;
    }else if (type == 3) {
        return PRO_h5live;
    }
    return PRO_h5live;
}
//call_server_topic服务器
+(NSString *)get_call_server_topic{
    NSInteger type = [OffcnBaseNetworking sharedInstance].serviceType;
    if (type == 1) {
        return DEV_call_server_topic;
    }else if (type == 2) {
        return TEST_call_server_topic;
    }else if (type == 3) {
        return PRO_call_server_topic;
    }
    return PRO_call_server_topic;
}
//图片服务器
+(NSString *)get_ImageBaseUrl{
    return [OffcnBaseNetworking sharedInstance].imageBaseUrl;
}
+ (void)configureHttpHeaderWithDict:(NSDictionary *)dict
{
    ZYJAFHTTPSessionManager *manager = [OffcnBaseNetworking sharedInstance].manager;
    NSArray *allKeyArray = dict.allKeys;
    for (int i = 0; i < [allKeyArray count]; i ++) {
        if (dict[allKeyArray[i]]) {
            [manager.requestSerializer setValue:dict[allKeyArray[i]] forHTTPHeaderField:allKeyArray[i]];
        }
    }
}

- (void)cancelAllOperations {
    ZYJAFHTTPSessionManager *manager = [OffcnBaseNetworking sharedInstance].manager;
    [manager.operationQueue cancelAllOperations];
}

/**
 *  处理接口返回字段为 null 问题
 *  @return 用“”替换“null”后的数据结果
 */
+ (id)replaceNullsWithBlanksWithResponseObject:(id)responseObject
{
    if ([responseObject isKindOfClass:[NSArray class]]) {
        responseObject = [responseObject arrayByReplacingNullsWithBlanks];
    }
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        responseObject = [responseObject dictionaryByReplacingNullsWithBlanks];
    }
    return responseObject;
}

+ (void)getFromURL:(NSString *)URLString
            params:(NSDictionary *)params
          finished:(NetworkCallBack)finished
{
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    ZYJAFHTTPSessionManager *manager = [OffcnBaseNetworking sharedInstance].manager;
    
    NSLog(@"---->%@",manager.requestSerializer.HTTPRequestHeaders);
    
    [manager GET:URLString parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        responseObject = [self replaceNullsWithBlanksWithResponseObject:responseObject];
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:responseObject error:nil];
        finished(apiObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:nil error:error];
        [apiObject checkNotReachability];
        
        finished(apiObject);
        //tokenid失效返回code 然后弹出登录
//        if (apiObject.code == KtokenCode) {
//            [[CommonManager shareInstance]didLoginout];
//            [[CommonManager shareInstance]isShowLoginVCinSuccess:nil];
//        }
    }];
}
+ (void)postToURL:(NSString *)URLString
       bodyParams:(id)bodyParams
         finished:(NetworkCallBack)finished
{
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    ZYJAFHTTPSessionManager *manager = [OffcnBaseNetworking sharedInstance].manager;
    NSLog(@"---->%@",manager.requestSerializer.HTTPRequestHeaders);
    
    [manager POST:URLString parameters:bodyParams progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        responseObject = [self replaceNullsWithBlanksWithResponseObject:responseObject];
        
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:responseObject error:nil];
        finished(apiObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:nil error:error];
        
        [apiObject checkNotReachability];
        finished(apiObject);
        //tokenid失效返回code 然后弹出登录
//        if (apiObject.code == KtokenCode) {
//            [[CommonManager shareInstance]didLoginout];
//            [[CommonManager shareInstance]isShowLoginVCinSuccess:nil];
//        }
    }];
}
+ (void)putToURL:(NSString *)URLString
       bodyParams:(id)bodyParams
         finished:(NetworkCallBack)finished
{
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    ZYJAFHTTPSessionManager *manager = [OffcnBaseNetworking sharedInstance].manager;
    [manager PUT:URLString parameters:bodyParams success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [self replaceNullsWithBlanksWithResponseObject:responseObject];
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:responseObject error:nil];
        finished(apiObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:nil error:error];
        [apiObject checkNotReachability];
        finished(apiObject);
        //tokenid失效返回code 然后弹出登录
        //        if (apiObject.code == KtokenCode) {
        //            [[CommonManager shareInstance]didLoginout];
        //            [[CommonManager shareInstance]isShowLoginVCinSuccess:nil];
        //        }
    }];
}
+ (void)deleteToURL:(NSString *)URLString
      bodyParams:(id)bodyParams
        finished:(NetworkCallBack)finished
{
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    ZYJAFHTTPSessionManager *manager = [OffcnBaseNetworking sharedInstance].manager;
    [manager DELETE:URLString parameters:bodyParams success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        responseObject = [self replaceNullsWithBlanksWithResponseObject:responseObject];
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:responseObject error:nil];
        finished(apiObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BaseResponse *apiObject = [[BaseResponse alloc]initWithTask:task responseObject:nil error:error];
        [apiObject checkNotReachability];
        finished(apiObject);
        //tokenid失效返回code 然后弹出登录
        //        if (apiObject.code == KtokenCode) {
        //            [[CommonManager shareInstance]didLoginout];
        //            [[CommonManager shareInstance]isShowLoginVCinSuccess:nil];
        //        }
    }];
}
+ (void)setHttpCommonHeader:(ZYJAFHTTPSessionManager *)manager{
    
    [manager.requestSerializer setValue:KCustomerAPPKEY forHTTPHeaderField:@"appkey"];
    //随机数（最大长度128个字符）
    NSString *nonceStr = [SDGeneralTool getNowSSSTimeTimestamp];
    [manager.requestSerializer setValue:nonceStr forHTTPHeaderField:@"nonce"];
    //当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
    NSString *curtimeStr = [SDGeneralTool getNowSSTimeTimestamp];
    [manager.requestSerializer setValue:curtimeStr forHTTPHeaderField:@"curtime"];
    //SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
    NSString *margeStr = [NSString stringWithFormat:@"%@%@%@",KCustomerSecre,nonceStr,curtimeStr];
    NSString *checksumStr = [ZYJOSSUtil sha1WithString:margeStr];
    checksumStr = [checksumStr lowercaseString];
    [manager.requestSerializer setValue:checksumStr forHTTPHeaderField:@"checksum"];
}

- (ZYJAFHTTPSessionManager *)manager
{
    if (!_manager) {
        ZYJAFHTTPSessionManager *sessionManager = [ZYJAFHTTPSessionManager manager];
        sessionManager.requestSerializer = [ZYJAFJSONRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        ZYJAFJSONResponseSerializer *responseSerializer = [ZYJAFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        sessionManager.responseSerializer = responseSerializer;
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",@"text/html",@"text/json",@"text/plain",@"text/javascript",@"text/xml",@"image/*",@"application/x-www-form-urlencoded"]];
        sessionManager.operationQueue.maxConcurrentOperationCount = 3;
        
        [sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        sessionManager.requestSerializer.timeoutInterval = 15.f;
        [sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        _manager = sessionManager;
    }
//    [OffcnBaseNetworking configureHttpHeaderWithDict:self.httpHeaderDic];
    [OffcnBaseNetworking setHttpCommonHeader:_manager];
    
    return _manager;
}
@end

@implementation BaseResponse

- (instancetype)initWithTask:(NSURLSessionDataTask *)task responseObject :(id)responseObject error :(NSError *) error{
    self = [super init];
    if (self) {
        self.url = task.originalRequest.URL.absoluteString;
        self.httpCode = [[task.response valueForKey:@"statusCode"] integerValue];
        self.code = [responseObject[@"code"] integerValue];
        self.responseObject = responseObject[@"data"];
        
        _task = task;
        if (self.httpCode == 200) {
            if (self.code == 200 || self.code == 0) {
                self.isSuccess = YES;
            }else{
                self.isSuccess = NO;
                self.errorMessage = responseObject[@"msg"];
                self.error = error;
            }
        }else{
            self.isSuccess = NO;
            int code;
            self.errorMessage = [self getErrorMessage:error code:&code];
            self.code = code;
            self.error = error;
        }
    }
    return self;
}

-(NSString *)getErrorMessage:(NSError *)error code:(int *)code
{
    NSString *errorMessage = nil;
    for (id data in error.userInfo.allValues) {
        if ([data isKindOfClass:[NSData class]]) {
            //            NSString * totalString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            errorMessage = dic[@"message"];
            *code = [dic[@"code"] intValue];
        }
        if ([data isKindOfClass:[NSError class]]) {
            errorMessage = [self getErrorMessage:data code:code];
        }
    }
    if (errorMessage == nil || [errorMessage isKindOfClass:[NSNull class]]) {
        NSLog(@"%@",error.userInfo[@"NSLocalizedDescription"]);
        return @"请求失败";
//        return error.userInfo[@"NSLocalizedDescription"];
    }
    return @"请求失败";
}

-(BaseResponse *)checkNotReachability{
    if (self.httpCode == 500 ||self.httpCode == 400) {
        return self;
    }
    
    NSInteger status = [ZYJRealReachability sharedInstance].currentReachabilityStatus;
    if (status == RealStatusNotReachable) {
        self.isSuccess = NO;
        self.httpCode = KNoNetWorkCode;
        self.code = KNoNetWorkCode;
        self.errorMessage = @"网络不给力，请稍后重试";
    }
    return self;
}

@end


