//
//  HttpClient.m
//  zhuxun
//
//  Created by 张建伟 on 15/4/7.
//  Copyright (c) 2015年 张建伟. All rights reserved.
//

#import "HttpClient.h"
#import "NSObject+Common.h"
//导入安全相关库
#import "MD5.h"
#import "DES.h"
#import "AFNetworkReachabilityManager.h"
#import "Utils.h"
#import "AFNetworking.h"

@implementation HttpClient



+ (HttpClient *)sharedJsonClient {

    HttpClient *httpclient = [[HttpClient alloc]init];
    
    return httpclient;
}


- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(id)params
                 withMethodType:(int)NetworkMethod
                       andBlock:(void (^)(id data, NSError *error))block{
    //log请求数据

    NSLog(@"Params:  %@",params);
#warning  安全改造--加密请求  完成前不要取消下面注释
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.securityPolicy.allowInvalidCertificates = YES;

    mgr.requestSerializer.timeoutInterval = 10;
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", @"text/html",nil];
    [mgr.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
 
    [mgr.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@",[DES returnKeyValue]]forHTTPHeaderField:@"Authorization"];
    NSLog(@"aPath:  - / - / -  aPath: %@ aPath: - / - / -",aPath);
    
    //新增无网络不处理请求,直接return
//    [Utils netWorkType:^AFNetworkReachabilityStatus status) {
    
        
        //发起请求
        switch (NetworkMethod) {
            case Get:{
                
                [mgr GET:aPath parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                    //
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    //
                    if ([task.originalRequest.URL.path isEqualToString:@"/v1/servers"]) {
                        
                        block(responseObject, nil);
                        return ;
                        
                    }
                    
                    id error = [self handleResponse:responseObject];
                    if (error) {
                        block(nil, error);
                    }else{
                        block(responseObject, nil);
                    }
                    
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    //
                    block(nil, error);
                    
                    [self showError:error];
                }];
                
//                [self GET:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
//                    id error = [self handleResponse:responseObject];
//                    if (error) {
//                        block(nil, error);
//                    }else{
//                        block(responseObject, nil);
//                    }
//                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, error);
//                    [self showError:error];
//                    block(nil, error);
//                }];
                break;
            }
            case Post:{
                //通过服务器获取数据
                [mgr POST:aPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    id error = [self handleResponse:responseObject];
                    if (error) {
                        
                        
                        block(nil, error);
                    }else{

                        block(responseObject, nil);
                    }

                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    [self showError:error];
                    block(nil, error);
                    
                }];
//                [self POST:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                    
//                    
//                    
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
//                    
//                    
//                    NSLog(@"\n===========responseMessage===========\n%@",responseObject[@"message"]);
//                    
//                    id error = [self handleResponse:responseObject];
//                    if (error) {
//                        
//                        
//                        block(nil, error);
//                    }else{
//                        //                    if ([aPath isEqualToString:kNetPath_Code_Login]) {
//                        //                        [CodingNetAPIClient saveCookieData];
//                        //                    }
//                        block(responseObject, nil);
//                    }
//                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, error);
//                    [self showError:error];
//                    block(nil, error);
//                }];
                break;
            }
            case Put:{
                
                [mgr PUT:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    id error = [self handleResponse:responseObject];
                    if (error) {
                        block(nil, error);
                    }else{
                        block(responseObject, nil);
                    }
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    [self showError:error];
                    block(nil, error);
                }];
                
//                [self PUT:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
//                    id error = [self handleResponse:responseObject];
//                    if (error) {
//                        block(nil, error);
//                    }else{
//                        block(responseObject, nil);
//                    }
//                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, error);
//                    [self showError:error];
//                    block(nil, error);
//                }];
                break;
            }
            case Delete:{
                
                [mgr DELETE:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    id error = [self handleResponse:responseObject];
                    if (error) {
                        block(nil, error);
                    }else{
                        block(responseObject, nil);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    [self showError:error];
                    
                    block(nil, error);
                }];
                
//                [self DELETE:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
//                    id error = [self handleResponse:responseObject];
//                    if (error) {
//                        block(nil, error);
//                    }else{
//                        block(responseObject, nil);
//                    }
//                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                    NSLog(@"\n===========response===========\n%@:\n%@", aPath, error);
//                    [self showError:error];
//                    
//                    block(nil, error);
//                }];
            }
            default:
                break;
        }

        
//    } fail:^{
//        //
//        
//        return ;
//    }];
    
//    AFNetworkReachabilityStatus status = [userInfo[AFNetworkingReachabilityNotificationStatusItem] integerValue];
    
//    if (status == AFNetworkReachabilityStatusNotReachable) {//未连接
//        //这是在手机的顶部出现的提示
//        [weakself showStatusBarNetError:[NSError errorWithDomain:@"NETWOR" code:-1 userInfo:@{@"NSLocalizedDescription":@"您的手机目前没有连接网络,请进行网络确认"}]];
//        //                [self socketDisConnect];
//        [weakself disConnect];
//    }else if(status==AFNetworkReachabilityStatusReachableViaWWAN||status==AFNetworkReachabilityStatusReachableViaWiFi)
//    {
//        //连接到主机
//        //                [self connect:_ipAddress port:_port];
//        [weakself startConnect];
//        //状态栏显示连接状态
//        [weakself showStatusBarNetReconnected];
//        
//    }
    
   
}

- (void)cloudStorageRequestJsonDataWithPath:(NSString *)aPath
                                 withParams:(id)params
                             withMethodType:(int)NetworkMethod
                                   andBlock:(void (^)(id data, NSError *error))block
{
    //log请求数据
    
    NSLog(@"Params:  %@",params);
#warning  安全改造--加密请求  完成前不要取消下面注释
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.securityPolicy.allowInvalidCertificates = YES;
    
    mgr.requestSerializer.timeoutInterval = 10;
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", @"text/html",nil];
    [mgr.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSString *auth = [userDefaults objectForKey:@"authorization"];
    
    if (auth) {
        //[DES cloudStorageReturnKeyValue]
        [mgr.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@",auth]forHTTPHeaderField:@"Authorization"];
        
//        [mgr.requestSerializer setValue:[DES cloudStorageReturnKeyValue]forHTTPHeaderField:@"Authorization"];
    }
    
    
    NSLog(@"aPath:  - / - / -  aPath: %@ aPath: - / - / -",aPath);
    
    //新增无网络不处理请求,直接return
    //    [Utils netWorkType:^AFNetworkReachabilityStatus status) {
    
    
    //发起请求
    switch (NetworkMethod) {
        case Get:{
            
            [mgr GET:aPath parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                //
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //
                if ([task.originalRequest.URL.path isEqualToString:@"/v1/servers"]) {
                    
                    block(responseObject, nil);
                    return ;
                    
                }
                
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error);
                }else{
                    block(responseObject, nil);
                }
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //
                block(nil, error);
                
                [self showError:error];
            }];

            break;
        }
        case Post:{
            //通过服务器获取数据
            [mgr POST:aPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                id error = [self handleResponse:responseObject];
                if (error) {
                    
                    
                    block(nil, error);
                }else{
                    
                    block(responseObject, nil);
                }
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self showError:error];
                block(nil, error);
                
            }];

            break;
        }
        case Put:{
            
            [mgr PUT:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error);
                }else{
                    block(responseObject, nil);
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self showError:error];
                block(nil, error);
            }];
            

            break;
        }
        case Delete:{
            
            [mgr DELETE:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error);
                }else{
                    block(responseObject, nil);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self showError:error];
                
                block(nil, error);
            }];

        }
        default:
            break;
    }
    
    
    
    
}

- (void)cloudStorageDownUpJsonDataWithPath:(NSString *)aPath
                                withParams:(id)params
                            withMethodType:(int)NetworkMethod
                                  andBlock:(void (^)(id data, NSError *error))block
{
    
    //log请求数据
    
    NSLog(@"Params:  %@",params);
#warning  安全改造--加密请求  完成前不要取消下面注释
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.securityPolicy.allowInvalidCertificates = YES;
    
    mgr.requestSerializer.timeoutInterval = 10;
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", @"text/html",nil];
    [mgr.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
//    [mgr.requestSerializer setValue:[DES cloudStorageDownUpReturnKeyValue] forHTTPHeaderField:@"Authorization"];
  
    [mgr.requestSerializer setAuthorizationHeaderFieldWithUsername:@"4f860649600a47508379639dba82327d" password:@"f3b58f6b935b4acd9d9e795864ad10d4"];
    
    
    NSLog(@"aPath:  - / - / -  aPath: %@ aPath: - / - / -",aPath);
    
    //新增无网络不处理请求,直接return
    //    [Utils netWorkType:^AFNetworkReachabilityStatus status) {
    
    
    //发起请求
    switch (NetworkMethod) {
        case Get:{
            
            [mgr GET:aPath parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                //
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //
                
                block(responseObject, nil);
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //
                block(nil, error);
                
                [self showError:error];
            }];
            
            break;
        }
        case Post:{
            //通过服务器获取数据
            [mgr POST:aPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
               block(responseObject, nil);
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self showError:error];
                block(nil, error);
                
            }];
            
            break;
        }
        case Put:{
            
            [mgr PUT:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error);
                }else{
                    block(responseObject, nil);
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self showError:error];
                block(nil, error);
            }];
            
            
            break;
        }
        case Delete:{
            
            [mgr DELETE:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error);
                }else{
                    block(responseObject, nil);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self showError:error];
                
                block(nil, error);
            }];
            
        }
        default:
            break;
    }
    
    
    
    
}



//请求用户状态
//-(void)postRequestToUrl:(NSString *)url netWorkMethod:(int)networkMethod aPath:(NSString *)path WithParams:(id)params complete:(void (^)(BOOL, NSDictionary *))complete{
//    
//    //拼接最全路径
//    NSString *aPath = [NSString stringWithFormat:@"%@%@",APP_HOST,path];
//    
//    
//    
//    if (networkMethod == Post) {
//        
//        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:aPath]];
//        
//        //设计请求头
//        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        request.HTTPMethod = @"POST";
//        
//        NSData *data = [NSJSONSerialization dataWithJSONObject:params options:(NSJSONWritingPrettyPrinted) error:nil];
//        //设置发送请求参数
//        request.HTTPBody = data;
//        
//        //发送请求
//        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//            if (data!=nil) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
//                
//                if (complete && !connectionError) {
//                    complete(true,dic);
//                }else{
//                    complete?complete(true,dic):nil;
//                }
//            }else{
//                NSLog(@"请求错误!");
//            }
//            
//            
//        }];
//    }else{
//        
//        NSLog(@"Requested data method is wrong, 'networkMethod' except 'Post' no other way!! ");
//        
//    }
//    
//    
//
//
//
//
//}


@end
