//
//  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 = 30.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
              withRequestType:(NetworkRequestType) requestType
                withParameter:(JSONModel *) jastorobject
         withReturnValueBlock:(ReturnValueBlock) successBlock
             withFailureBlock:(FailureBlock) failureBlock
{
    AFHTTPSessionManager *manager = [self baseHttpRequest];
    if (requestType == 0) {
        
        NSLog(@"%@",[[jastorobject toDictionary] toJSONString]);
        [manager POST:requestURLString parameters:[jastorobject toDictionary] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            @try {
                //登陆超时
                if ([responseObject[@"code"] isEqualToNumber:@1]) {
//                    [XBLoadingView hideHUDViewWithDefault];
//                    [Notification postNotificationName:LOGINTIMEOUT object:nil];
                    //调用自动登录
                    [self automaticLoginWithReturnValueBlock:^(id returnValue) {
                        [self networkRequestWithURL:requestURLString withRequestType:requestType withParameter:jastorobject withReturnValueBlock:^(id returnValue) {
                            successBlock(returnValue);
                        } withFailureBlock:^(NSError *error) {
                            failureBlock(error);
                        }];
                        
                    } withFailureBlock:^(NSError *error) {
                        failureBlock(error);
                    }];
                }else{
                    successBlock(responseObject);
                }
            } @catch (NSException *exception) {
                NSLog(@"解析错误");
                successBlock(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock(error);
        }];
        
    }else if (requestType == 1){
        
        NSLog(@"%@",[[jastorobject toDictionary] toJSONString]);
        [manager GET:requestURLString parameters:[jastorobject toDictionary] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            @try {
                //登陆超时
                if ([responseObject[@"code"] isEqualToNumber:@1]) {
//                    [XBLoadingView hideHUDViewWithDefault];
//                    [Notification postNotificationName:LOGINTIMEOUT object:nil];
                    //调用自动登录
                    [self automaticLoginWithReturnValueBlock:^(id returnValue) {
                        [self networkRequestWithURL:requestURLString withRequestType:requestType withParameter:jastorobject withReturnValueBlock:^(id returnValue) {
                            successBlock(returnValue);
                        } withFailureBlock:^(NSError *error) {
                            failureBlock(error);
                        }];
                        
                    } withFailureBlock:^(NSError *error) {
                        failureBlock(error);
                    }];
                }else{
                    successBlock(responseObject);
                }
            } @catch (NSException *exception) {
                NSLog(@"解析错误");
                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
                            withRequestType:(NetworkRequestType) requestType
                              withParameter:(NSDictionary *) parameter
                       withReturnValueBlock:(ReturnValueBlock) successBlock
                           withFailureBlock:(FailureBlock) failureBlock
{
    NSLog(@"%@",requestURLString);
    AFHTTPSessionManager *manager = [self baseHttpRequest];
    if (requestType == POST) {
        [manager POST:requestURLString parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            @try {
                //登陆超时
                if ([responseObject[@"code"] isEqualToNumber:@1]) {
//                    [XBLoadingView hideHUDViewWithDefault];
//                    [Notification postNotificationName:LOGINTIMEOUT object:nil];
                    //自动登录
                    [self automaticLoginWithReturnValueBlock:^(id returnValue) {
                        [self networkWithDictionaryRequestWithURL:requestURLString withRequestType:requestType withParameter:parameter withReturnValueBlock:^(id returnValue) {
                            successBlock(returnValue);
                        } withFailureBlock:^(NSError *error) {
                            NSLog(@"%@", responseObject);
                            failureBlock(error);
                        }];
                        
                    } withFailureBlock:^(NSError *error) {
                        NSLog(@"%@", responseObject);
                        failureBlock(error);
                    }];
                }else{
                    NSLog(@"%@", responseObject);
                    successBlock(responseObject);
                }
            } @catch (NSException *exception) {
                NSLog(@"解析错误");
                successBlock(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock(error);
        }];
        
    }else if (requestType == GET){
        [manager GET:requestURLString parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            @try {
                //登陆超时
                if ([responseObject[@"code"] isEqualToNumber:@1]) {
//                    [XBLoadingView hideHUDViewWithDefault];
//                    [Notification postNotificationName:LOGINTIMEOUT object:nil];
                    //自动登录
                    [self automaticLoginWithReturnValueBlock:^(id returnValue) {
                        [self networkWithDictionaryRequestWithURL:requestURLString withRequestType:requestType withParameter:parameter withReturnValueBlock:^(id returnValue) {
                            successBlock(returnValue);
                        } withFailureBlock:^(NSError *error) {
                            failureBlock(error);
                        }];
                        
                    } withFailureBlock:^(NSError *error) {
                        NSLog(@"error");
                        failureBlock(error);
                    }];
                }else{
                    NSLog(@"%@", responseObject);
                    successBlock(responseObject);
                }
            } @catch (NSException *exception) {
                NSLog(@"解析错误");
                successBlock(responseObject);
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock(error);
        }];
    }else if (requestType == NetworkRequestWithDELETE){
        [manager DELETE:requestURLString parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            @try {
                //登陆超时
                if ([responseObject[@"code"] isEqualToNumber:@1]) {
//                    [XBLoadingView hideHUDViewWithDefault];
//                    [Notification postNotificationName:LOGINTIMEOUT object:nil];
                    //自动登录
                    [self automaticLoginWithReturnValueBlock:^(id returnValue) {
                        [self networkWithDictionaryRequestWithURL:requestURLString withRequestType:requestType withParameter:parameter withReturnValueBlock:^(id returnValue) {
                            successBlock(returnValue);
                        } withFailureBlock:^(NSError *error) {
                            failureBlock(error);
                        }];
                        
                    } withFailureBlock:^(NSError *error) {
                        NSLog(@"%@", error);
                        failureBlock(error);
                    }];
                }else{
                    NSLog(@"%@", responseObject);
                    successBlock(responseObject);
                }
            } @catch (NSException *exception) {
                NSLog(@"解析错误");
                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
               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"];
    //构造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 *homepath = [kPathCaches stringByAppendingPathComponent:[NSString stringWithFormat:@"PPT/%@",[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
          withFailureBlock:(FailureBlock) failureBlock
{
    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);
    }];
}


    
/**
 自动登录

 @param successBlock 登录成功
 @param failureBlock 登录失败
 */
- (void)automaticLoginWithReturnValueBlock:(ReturnValueBlock)successBlock
                          withFailureBlock:(FailureBlock)failureBlock
{
    LoginInfo *login = [[LoginInfo alloc]init];
    login.username = [Shoppersmanager manager].userNameString;
    login.password = [Shoppersmanager manager].passWordString;
    [XBLoadingView showHUDViewWithDefault];
    [self networkRequestWithURL:SERVERREQUESTURL(LOGIN)  withRequestType:ZERO withParameter:login withReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            LoginResult *result = [[LoginResult alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [Shoppersmanager manager].shoppers = result;
            successBlock(result);
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
        failureBlock(error);
    }];
}






@end
