//
//  NetworkRequestClassManager.m
//  Lighting
//
//  Created by 曹云霄 on 16/4/28.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "NetworkRequestClassManager.h"
#import "AppDelegate.h"


@implementation NetworkRequestClassManager



static NetworkRequestClassManager *manager = nil;
/**
 *  网络请求单例
 *
 *  @return NetworkRequestClassManager
 */
+ (NetworkRequestClassManager *)Manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NetworkRequestClassManager alloc]init];
    });
    return manager;
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [super allocWithZone:zone];
    });
    return manager;
}

/**
 *  请求实体
 *
 *  @return AFHTTPSessionManager
 */
- (AFHTTPSessionManager *)baseHttpRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10.0f;
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField: @"Content-Type"];
    [manager.requestSerializer setValue:[[[NSBundle mainBundle] infoDictionary]
                                         objectForKey:@"CFBundleShortVersionString"] forHTTPHeaderField: @"version"];
    return manager;
}

/**
 *  网络请求
 *
 *  @param requestURLString     网址
 *  @param requestType          请求类型(POST/GET)
 *  @param parameter            参数
 *  @param sueecssBlock         成功回调
 *  @param errorCodeBlock       错误编码回调
 *  @param failureBlock         失败回调
 */

- (void)NetworkRequestWithURL:(NSString *) requestURLString
                WithCallClass:(BaseViewController *)object
              WithRequestType:(NetworkRequestType) requestType
                WithParameter:(JSONModel *) jastorobject
         WithReturnValueBlock:(ReturnValueBlock) successBlock
           WithErrorCodeBlock:(ErrorCodeBlock) errorCodeBlock
             WithFailureBlock:(FailureBlock) failureBlock

{
    
    AFHTTPSessionManager *manager = [self baseHttpRequest];
    //网络检测
    if (SHARED_APPDELEGATE.Networkstatus == false) {
        
        errorCodeBlock(BROKEN);
        return;
    }
    
    if (requestType == 0) {
        
        [manager POST:requestURLString parameters:[jastorobject toDictionary] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //登陆超时
            if ([responseObject[@"code"] isEqualToNumber:@1]) {
                [object RemoveMBProgressHUDLoding];
                [[NSNotificationCenter defaultCenter] postNotificationName:LOGINTIMEOUT object:nil];
            }else {
               successBlock(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureBlock(error);
            
        }];
        
    }else if (requestType == 1){
        
        [manager GET:requestURLString parameters:[jastorobject toDictionary] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //登陆超时
            if ([responseObject[@"code"] isEqualToNumber:@1]) {
                [object RemoveMBProgressHUDLoding];
                [[NSNotificationCenter defaultCenter] postNotificationName:LOGINTIMEOUT object:nil];
            }else{
                successBlock(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
            failureBlock(error);
            
        }];
    }
}


/**
 *  网络请求
 *
 *  @param requestURLString     网址
 *  @param requestType          请求类型
 *  @param parameter            字典对象
 *  @param sueecssBlock         成功回调
 *  @param errorCodeBlock       错误编码回调
 *  @param failureBlock         失败回调
 */
- (void)NetworkWithDictionaryRequestWithURL:(NSString *) requestURLString
                              WithCallClass:(BaseViewController *)object
                            WithRequestType:(NetworkRequestType) requestType
                              WithParameter:(NSDictionary *) parameter
                       WithReturnValueBlock:(ReturnValueBlock) successBlock
                         WithErrorCodeBlock:(ErrorCodeBlock) errorCodeBlock
                           WithFailureBlock:(FailureBlock) failureBlock
{
    AFHTTPSessionManager *manager = [self baseHttpRequest];
    //网络检测
    if (SHARED_APPDELEGATE.Networkstatus == false) {
        
        errorCodeBlock(BROKEN);
        return;
    }

    if (requestType == 0) {
        
        [manager POST:requestURLString parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //登陆超时
            if ([responseObject[@"code"] isEqualToNumber:@1]) {
                [object RemoveMBProgressHUDLoding];
                [[NSNotificationCenter defaultCenter] postNotificationName:LOGINTIMEOUT object:nil];
            }else {
                successBlock(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureBlock(error);
            
        }];
        
    }else if (requestType == 1){
        
        [manager GET:requestURLString parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //登陆超时
            if ([responseObject[@"code"] isEqualToNumber:@1]) {
                [object RemoveMBProgressHUDLoding];
                [[NSNotificationCenter defaultCenter] postNotificationName:LOGINTIMEOUT object:nil];
            }else{
                successBlock(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureBlock(error);
            
        }];
    }
}




/**
 *  下载PDF
 *
 *  @param requestURLString 网址
 *  @param successBlock     成功回调
 *  @param errorCodeBlock   错误编码回到
 *  @param failureBlock     失败回调
 */
- (void)DownloadPDFdatasWithURL:(NSString *) requestURLString
           WithReturnValueBlock:(ReturnValueBlock) successBlock
             WithErrorCodeBlock:(ErrorCodeBlock) errorCodeBlock
               WithFailureBlock:(FailureBlock) failureBlock
{
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 120.0f;
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField: @"Content-Type"];
    //网络检测
    if (SHARED_APPDELEGATE.Networkstatus == false) {
        
        errorCodeBlock(BROKEN);
        return;
    }
    //构造URL对象
    NSURL *url = [NSURL URLWithString:requestURLString];
    //构造request对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //使用系统类创建downLoad Task对象
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@", downloadProgress);//下载进度
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //返回下载到哪里(返回值是一个路径)
        NSString *homeDictionary = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
        NSString *homepath = [homeDictionary stringByAppendingPathComponent:[response suggestedFilename]];//添加储存的文件名
        return [NSURL fileURLWithPath:homepath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成走这个block
        if (!error)
        {
            successBlock(filePath);
        }else
        {
            failureBlock(error);
        }
    }];
    //开始请求
    [task resume];
}




/**
 *  上传分享图片
 *
 *  @param requestURLString 网址
 *  @param requestType      请求类型
 *  @param parameter        参数
 *  @param successBlock     成功回调
 *  @param errorCodeBlock   错误编码回调
 *  @param failureBlock     失败回调
 */
- (void)UploadImageWithURL:(NSString *) requestURLString
           WithRequestType:(NetworkRequestType) requestType
                    WithImageDatas:(NSData *) imagedata
             WithParameter:(NSDictionary *) parameter
      WithReturnValueBlock:(ReturnValueBlock) successBlock
        WithprogressBlock:(UploadprogressBlock) progressBlock
        WithErrorCodeBlock:(ErrorCodeBlock) errorCodeBlock
          WithFailureBlock:(FailureBlock) failureBlock
{
    
    //网络检测
    if (SHARED_APPDELEGATE.Networkstatus == false) {
        
        errorCodeBlock(BROKEN);
        return;
    }
    AFHTTPSessionManager *manager = [self baseHttpRequest];
    [manager POST:requestURLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imagedata name:@"file" fileName:@"file.png" mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progressBlock(uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failureBlock(error);
    }];
}








@end
