//
//  BRNetworkMgr.m
//  TestHttpRequest
//
//  Created by JianjiYuan on 14-11-21.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "BRNetworkMgr.h"
#import "LoginViewController.h"
#import <AFNetworkReachabilityManager.h>
#import "Reachability.h"

@interface BRNetworkMgr () < UIAlertViewDelegate >
{
    NSOperation *currentOperation;
}

@end

@implementation BRNetworkMgr

+ (BRNetworkMgr *)getInstance
{
    BRNetworkMgr *instance = [[BRNetworkMgr alloc] init];
    instance.operationQueue = [AFHTTPRequestOperationManager manager].operationQueue;
    return instance;
}

- (void)addObserverForQueueProgress
{
    [self.operationQueue addObserver:self
                          forKeyPath:@"operationCount"
                             options:0
                             context:nil];
}

- (void)removeObserverForQueueProgress
{
    [self.operationQueue removeObserver:self forKeyPath:@"operationCount"];
}

//KVO,观察parseQueue是否执行完
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (object == self.operationQueue
        && [keyPath isEqualToString:@"operationCount"]) {
        if (0 == self.operationQueue.operationCount) {
            [self operationQueueDidFished:self.operationQueue];
        }
        
    }else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

- (AFHTTPRequestOperation *)operationWithURL:(NSString *)strURL
                                   interface:(NSString *)interface
                                      params:(NSDictionary *)params
                                    dataType:(BRNetMgrDataType)type
                                      method:(BRNetMgrMethod)method
{
    NSString *legalStrURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DLog(@"legalStrURL  %@\n params %@", legalStrURL, params);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manager.requestSerializer.timeoutInterval = 15;
    switch (type) {
        case BRNetMgrDataTypeJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case BRNetMgrDataTypeXML:
        case BRNetMgrDataTypeSoap:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
    }

    AFHTTPRequestOperation *operation = nil;
    switch (method) {
        case BRNetMgrMethodGet:
        {
            operation = [manager GET:legalStrURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
                [self operationDidSucceed:operation result:responseObject];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self operationDidFailed:operation result:error];
            }];
        }
            
            break;
        case BRNetMgrMethodPost:
        {
            operation = [manager POST:legalStrURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
                [self operationDidSucceed:operation result:responseObject];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self operationDidFailed:operation result:error];
            }];
        }

            break;
        default:
            break;
    }    
    [operation setUserInfo:@{@"interface":interface, kDealExtraWhenErrorOcur:@NO}];
    
    [self.operationQueue setSuspended:YES];
    [operation pause];
    
    return operation;
}

- (AFHTTPRequestOperation *)operationUploadWithURL:(NSString *)strURL
                                         interface:(NSString *)interface
                                            params:(NSDictionary *)params
                                          dataType:(BRNetMgrDataType)type
                                          fileType:(BRNetMgrFileType)fileType
                                             files:files
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 60;
    switch (type) {
        case BRNetMgrDataTypeJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case BRNetMgrDataTypeXML:
        case BRNetMgrDataTypeSoap:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
    }
    
    NSString *legalStrURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DLog(@"legalStrURL  %@\n params %@", legalStrURL, params);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]
                                    multipartFormRequestWithMethod:@"POST"
                                    URLString:legalStrURL
                                    parameters:params
                                    constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                        
                                        for (NSDictionary *dictFiles in files) {
                                            NSString *mimeType = nil;
                                            if (fileType == BRNetMgrFileTypePng) {
                                                mimeType = @"image/png";
                                            }else if (fileType == BRNetMgrFileTypeJpeg) {
                                                mimeType = @"image/jpeg";
                                            }
                                            
                                            UIImage* img = [UIImage imageWithContentsOfFile:dictFiles[kFilePath]];
                                            
                                            [formData appendPartWithFileData:[self compressImage:img toMaxFileSize:204000] name:dictFiles[kFileKeyName] fileName:[dictFiles[kFilePath] lastPathComponent] mimeType:mimeType];
//                                            [formData appendPartWithFileURL:[NSURL fileURLWithPath:dictFiles[kFilePath]]
//                                                                       name:dictFiles[kFileKeyName]
//                                                                   fileName:[dictFiles[kFilePath] lastPathComponent]
//                                                                   mimeType:mimeType error:nil];
                                        }
                                    } error:nil];
    
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject){
        [self operationDidSucceed:operation result:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self operationDidFailed:operation result:error];
    }];
    
    [operation setUserInfo:@{@"interface":interface, kDealExtraWhenErrorOcur:@NO}];
    [self.operationQueue addOperation:operation];
    [self.operationQueue setSuspended:YES];
    [operation pause];
    return operation;
}


- (void)operationDidSucceed:(AFHTTPRequestOperation *)operation result:(id)responseObject
{
    DLog(@"operationDidSucceed %@  responseObject  %@", operation.description, responseObject);
    
    if ([self checkResultValid:responseObject] || [operation.userInfo[kDealExtraWhenErrorOcur] boolValue]) {
        if (_delegate
            && [_delegate respondsToSelector:@selector(httpOperationSuccess:result:)]) {
            [_delegate httpOperationSuccess:operation result:responseObject];
        }
    }
    [UIApplication hideLoadingView];
  
}

- (void)operationDidFailed:(AFHTTPRequestOperation *)operation result:(NSError *)error
{
    DLog(@"operationDidFailed %@  error  %@", operation.description, error);
    if (_delegate
        && [_delegate respondsToSelector:@selector(httpOperationFailed:error:)]) {
        [_delegate httpOperationFailed:operation error:error];
    }
    [UIApplication hideLoadingView];
    
    [UIApplication showToastViewMessage:kRequestFailedMessage];
}

- (void)operationQueueDidFished:(NSOperationQueue *)queue
{
    DLog(@"operationQueueDidFished %@", queue.description);
    if (_delegate
        && [_delegate respondsToSelector:@selector(networkQueueComplete:)]) {
        [_delegate networkQueueComplete:queue];
    }
    [UIApplication hideLoadingView];
}

- (void)startOperation:(AFHTTPRequestOperation *)operation
{
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        currentOperation = operation;
        
        [UIApplication showAlertViewWithTitle:@"提示"
                                      message:@"无法连接服务器，请检查网络连接。"
                                     delegate:self
                                          tag:200
                            cancelButtonTitle:@"重试" otherButtonTitles:@"取消", nil];
        
    }else {
        [self.operationQueue setSuspended:NO];
        [operation resume];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 200) {
        if (buttonIndex == 0) {
            [self startOperation:currentOperation];
        }
        if (buttonIndex == 1) {
//            LoginViewController* vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
//            vcLogin.isPresented = YES;
//            BaseNavigationController *navLogin = [[BaseNavigationController alloc] initWithRootViewController:vcLogin];
////            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:navLogin animated:YES completion:nil];
//            [UIApplication sharedApplication].keyWindow.rootViewController = navLogin;
            
            NSNotification *notification =[NSNotification notificationWithName:@"noNetwork" object:nil userInfo:nil];
            //通过通知中心发送通知
            [[NSNotificationCenter defaultCenter] postNotification:notification];
        }
    }
}


- (BOOL)checkResultValid:(NSDictionary *)dictResult
{
    NSString *message = @"";
    if ([dictResult[@"resultCode"] isEqualToString:@"01"]) {
        return YES;
    }else if ([dictResult[@"resultCode"] isEqualToString:@"02"]) {
       // message = @"用户名密码错误";
        message=@"登录失败,用户名或密码错误";
    }else if ([dictResult[@"resultCode"] isEqualToString:@"03"]) {
        message = @"服务器错误";
    }else if ([dictResult[@"resultCode"] isEqualToString:@"04"]) {
        message = @"登录超时,请重新登陆";
        LoginViewController* vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        vcLogin.isPresented = YES;
        BaseNavigationController *navLogin = [[BaseNavigationController alloc] initWithRootViewController:vcLogin];
        [[UIApplication sharedApplication].keyWindow.rootViewController
         presentViewController:navLogin
         animated:YES completion:nil];
    }else if ([dictResult[@"resultCode"] isEqualToString:@"05"]) {
        //message = @"此版本不存在";
    }else if ([dictResult[@"resultCode"] isEqualToString:@"06"]) {
        return NO;
    }else if ([dictResult[@"resultCode"] isEqualToString:@"07"]) {
        message=@"活动或任务已被删除";
        if ([[DataMgr getInstance].roleId isEqualToString:@"daqufuzeren"]) {
            BaseNavigationController *baseNav = (BaseNavigationController*)[UIApplication sharedApplication].keyWindow.rootViewController;
//            [[UIApplication sharedApplication].keyWindow.rootViewController
//             presentViewController:navLogin
//             animated:YES completion:nil];
            for (UIViewController *controller in baseNav.viewControllers) {
                if ([controller isKindOfClass:NSClassFromString(@"BATaskListViewController")]) {
                    [baseNav popToViewController:controller animated:YES];
                }
            }
        }
        if ([[DataMgr getInstance].roleId isEqualToString:@"xiaoqufuzeren"]) {
            BaseNavigationController *baseNav = (BaseNavigationController*)[UIApplication sharedApplication].keyWindow.rootViewController;
            //            [[UIApplication sharedApplication].keyWindow.rootViewController
            //             presentViewController:navLogin
            //             animated:YES completion:nil];
            for (UIViewController *controller in baseNav.viewControllers) {
                if ([controller isKindOfClass:NSClassFromString(@"SATaskListViewController")]) {
                    [baseNav popToViewController:controller animated:YES];
                }
            }
        }
        if ([[DataMgr getInstance].roleId isEqualToString:@"guanliyuan"]) {
            BaseNavigationController *baseNav = (BaseNavigationController*)[UIApplication sharedApplication].keyWindow.rootViewController;
            //            [[UIApplication sharedApplication].keyWindow.rootViewController
            //             presentViewController:navLogin
            //             animated:YES completion:nil];
            for (UIViewController *controller in baseNav.viewControllers) {
                if ([controller isKindOfClass:NSClassFromString(@"TaskListViewController")]) {
                    [baseNav popToViewController:controller animated:YES];
                }
            }
        }
        [UIApplication saveObject:@YES type:Number key:kShouldRequestDataWhenBack];
    }
    [UIApplication showToastViewMessage:message];
    return NO;
}

- (NSData *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize
{
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    return imageData;
}

@end
