//
//  ICRHTTPController.m
//  Cruiser
//
//  Created by Xummer on 3/26/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRHTTPController.h"
//#import "ICRUserUtil.h"
#import "AFNetworking.h"
#import "Base64.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "NSDate+FormatterAdditions.h"

#import "IBTModel.h"
#import "ICRAttachment.h"
#import "ICRAnnouncement.h"
#import "ICRUtilsMacro.h"
#import "IBTCommon.h"
#import "VankeCommonModel.h"
#import "ICRDataBaseController.h"
#import "VankeConfig.h"
//#import "ICRStoreResult.h"

#define MAX_CONCURRENCY_UPLOAD      1
#define MAX_CONCURRENCY_DOWNLOAD    3
#define HTTP_REST_API_BASE_URL  @"http://218.244.151.129:8281/cruiser-server/rest"

#define ERROR_PARAMETER             @"Error: Bad Parameter(s)"

NSString * const ICRHTTPErrorDomain = @"ICRHTTPErrorDomain";

typedef NS_ENUM(NSUInteger, ICRHTTPAction) {
    kICRHTTP_Dummy = 0,
    // User
    kICRHTTP_UserLogin,
    kICRHTTP_UserResetPassword,
    
    // Data
    kICRHTTP_StoreQuery,
    kICRHTTP_CurrentOrg,
    
    // Board
    kICRHTTP_BoardQuery,
    kICRHTTP_ReadBoard,
    
    // Patrol
    kICRHTTP_PatrolQuery,
    kICRHTTP_AnswerStoreResult,
    kICRHTTP_PatrolAnswer,
    kICRHTTP_PatrolOneAnswer,
    
    // Task
    kICRHTTP_MyTaskQuery,
    kICRHTTP_TaskNew,
    kICRHTTP_TaskResult,
    
    // Signup
    kICRHTTP_SignUp,
    
    // Attachment
    kICRHTTP_AttachmentAdd,
    kICRHTTP_AttachmentList,
    kICRHTTP_AttachmentDownload,
    kICRHTTP_AttachmentAddDirect,
    kICRHTTP_AttachmentDownloadDirect,
    
    // Version
    kICRHTTP_VersionFetch,
    
    //Person
    kICRHTTP_PersonQuery
};

static NSString * const ICRHTTPInterface[] = {
    [ kICRHTTP_Dummy ]                      = @"",
    
    // User
    [ kICRHTTP_UserLogin ]                  = @"user/login",
    [ kICRHTTP_UserResetPassword ]          = @"user/change_password",
    
    // Data
    [ kICRHTTP_StoreQuery ]                 = @"mdata/store/download",
    [ kICRHTTP_CurrentOrg ]                 = @"data/organization/currentOrg",
    
    // Board
    [ kICRHTTP_BoardQuery ]                 = @"affiche/download",
    [ kICRHTTP_ReadBoard ]                  = @"board/read",
    
    
    
    
    // Patrol
    [ kICRHTTP_PatrolQuery ]                = @"patrol/plan/download",
    [ kICRHTTP_AnswerStoreResult ]          = @"patrol/plan/get_store_result",
    [ kICRHTTP_PatrolAnswer ]               = @"patrol/plan/submit_result",
    [ kICRHTTP_PatrolOneAnswer ]            = @"patrol/oneAnswer",
    
    // Task
    [ kICRHTTP_MyTaskQuery ]                  = @"task/task/downloadForProcessor",
    [ kICRHTTP_TaskNew ]                    = @"task/task/submit",
    [ kICRHTTP_TaskResult ]                 = @"task/task",
    
    // Signup
    [ kICRHTTP_SignUp ]                     = @"signin",
    
    // Attachment
    [ kICRHTTP_AttachmentAdd ]              = @"attachment/upload",
    [ kICRHTTP_AttachmentList ]             = @"attachment/list",
    [ kICRHTTP_AttachmentDownload ]         = @"attachment/download",
    [ kICRHTTP_AttachmentAddDirect ]        = @"attachment/addDirect",
    [ kICRHTTP_AttachmentDownloadDirect ]   = @"attachment/downloadDirect",
    
    // Version
    [ kICRHTTP_VersionFetch ]               = @"version/fetch",
    
    //Person
    [kICRHTTP_PersonQuery]                  =  @"user/download",
};

static NSString * const ICRAttachmentTypeValue[] = {
    [ kAttachmentBoard ]                    = @"board",
    [ kAttachmentAnswer ]                   = @"answer",
    [ kAttachmentTask ]                     = @"task",
};

@interface ICRHTTPController ()
/**
 *  The upload operation queue on which upload request operations are scheduled and run.
 */
@property (nonatomic, strong) NSOperationQueue *uploadOperationQueue;

/**
 *  The download operation queue on which download request operations are scheduled and run.
 */
@property (nonatomic, strong) NSOperationQueue *downloadOperationQueue;

@end

@implementation ICRHTTPController

#pragma mark - Class Method

+ (instancetype)sharedController {
    static ICRHTTPController *_sharedController = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedController = [[self alloc] init];
    });
    
    return _sharedController;
}

+ (NSString *)UrlForPluginHTTPAction:(ICRHTTPAction)action {
    return [HTTP_REST_API_BASE_URL stringByAppendingFormat:@"/%@", ICRHTTPInterface[ action ]];
}

+ (NSError *)ErrorWithMsg:(NSString *)nsErrorMsg code:(NSInteger)uiCode {
    NSDictionary *userInfo =
    nsErrorMsg ? @{ NSLocalizedFailureReasonErrorKey : nsErrorMsg } : nil;
    
    NSError *error =
    [[NSError alloc] initWithDomain:ICRHTTPErrorDomain
                               code:uiCode userInfo:userInfo];
    
    return error;
}

+ (id)GetErrorMsgFromOperation:(AFHTTPRequestOperation *)operation error:(NSError *)error
{
    id data = operation.responseObject;
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSString *errorMsg = data[ @"message" ];
        return [[self class] ErrorWithMsg:errorMsg code:[[operation response] statusCode]];
    }
    else {
        return error;
    }
}


#pragma mark - Life Cycle
- (id)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    self.uploadOperationQueue = [[NSOperationQueue alloc] init];
    [self.uploadOperationQueue setMaxConcurrentOperationCount:MAX_CONCURRENCY_UPLOAD];
    
    self.downloadOperationQueue = [[NSOperationQueue alloc] init];
    [self.downloadOperationQueue setMaxConcurrentOperationCount:MAX_CONCURRENCY_DOWNLOAD];
    
    return self;
}

#pragma mark - Private Method
- (AFJSONRequestSerializer *)requestNeedToken:(BOOL)bIsNeedToken
                               acceptTypeJson:(BOOL)bAcceptJson
                                      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
//    User *model = [[VankeCommonModel sharedInstance] currentUser];
    
    //    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    //    if (bIsNeedToken) {
    //        if ([model.token length] > 0) {
    //            if (!requestSerializer.HTTPRequestHeaders[ @"token" ]) {
    //                [requestSerializer setValue:user.token forHTTPHeaderField:@"token"];
    //            }
    //        }
    //        else {
    //            NSDictionary *userInfo = @{ NSLocalizedFailureReasonErrorKey : @"The authorization must not be nil." };
    //            NSError *error = [[NSError alloc] initWithDomain:ICRHTTPErrorDomain code:0 userInfo:userInfo];
    //            fail(nil, error);
    //        }
    //    }
    
    if (bAcceptJson) {
        if (!requestSerializer.HTTPRequestHeaders[ @"Accept" ]) {
            [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        }
    }
    [requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField: @"Content-Type"];
    //请求头添加enterprise参数
    
    Enterpirse *ent = [[VankeCommonModel sharedInstance] currentEnt];
    if(ent.uuid != NULL)
    {
        [requestSerializer setValue:ent.uuid forHTTPHeaderField:@"enterprise"];
    }
    //    [requestSerializer setValue:user.authorization forHTTPHeaderField:@"Authorization"];
    
    return requestSerializer;
}

- (void)GET:(NSString *)urlStr
 parameters:(id)parameters
  needToken:(BOOL)bIsNeedToken
acceptTypeJson:(BOOL)bAcceptJson
    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))succ
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    AFJSONRequestSerializer *requestSerializer =
    [self requestNeedToken:bIsNeedToken acceptTypeJson:bAcceptJson failure:fail];
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        succ(operation, responseObject);
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(operation, [[self class] GetErrorMsgFromOperation:operation error:error]);
    };
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    NSLog(@"headers=======>>>>>>>>>%@",[manager.requestSerializer HTTPRequestHeaders]);
    // The request add in operation
    
    
    // The request add in operation
    [manager GET:urlStr
      parameters:parameters
         success:success
         failure:failure];
}

- (void)POST:(NSString *)urlStr
  parameters:(id)parameters
   needToken:(BOOL)bIsNeedToken
acceptTypeJson:(BOOL)bAcceptJson
     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))succ
     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    AFJSONRequestSerializer *requestSerializer =
    [self requestNeedToken:bIsNeedToken acceptTypeJson:bAcceptJson failure:fail];
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        succ(operation, responseObject);
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(operation, [[self class] GetErrorMsgFromOperation:operation error:error]);
    };
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    [manager POST:urlStr
       parameters:parameters
          success:success
          failure:failure];
}

- (void)PATCH:(NSString *)urlStr
   parameters:(id)parameters
    needToken:(BOOL)bIsNeedToken
acceptTypeJson:(BOOL)bAcceptJson
      success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))succ
      failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    AFJSONRequestSerializer *requestSerializer =
    [self requestNeedToken:bIsNeedToken acceptTypeJson:bAcceptJson failure:fail];
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        succ(operation, responseObject);
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(operation, [[self class] GetErrorMsgFromOperation:operation error:error]);
    };
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    
    
    // The request add in operation
    [manager PATCH:urlStr
        parameters:parameters
           success:success
           failure:failure];
}

- (void)DELETE:(NSString *)urlStr
    parameters:(id)parameters
     needToken:(BOOL)bIsNeedToken
acceptTypeJson:(BOOL)bAcceptJson
       success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))succ
       failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    AFJSONRequestSerializer *requestSerializer =
    [self requestNeedToken:bIsNeedToken acceptTypeJson:bAcceptJson failure:fail];
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        succ(operation, responseObject);
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(operation, [[self class] GetErrorMsgFromOperation:operation error:error]);
    };
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    
    // The request add in operation
    [manager DELETE:urlStr
         parameters:parameters
            success:success
            failure:failure];
}

- (void)doChangePassword:(NSString *)nsPassword
             newPassword:(NSString *)nsNewPassword
                 success:(void (^)(id data))succ
                 failure:(void (^)(id data))fail
{
    //    if (!nsPassword || !nsNewPassword) {
    //        if (fail) {
    //            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
    //        }
    //        return;
    //    }
    //
    //    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
    //        NSLog(@"%@", responseObject);
    //        if (succ) {
    //            succ( responseObject );
    //        }
    //    };
    //
    //    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
    //        NSLog(@"%@", error);
    //        if (fail) {
    //            fail( error );
    //        }
    //    };
    ////http://.../cruiser-server/rest/user/change_password/{user_uuid}?time={time}&operator.id={operatorId}&operator.operName={operatorName}&enterprise={enterprise}
    ////    请求参数：
    //
    //    NSDictionary *dictParametes =
    //    @{ @"oldPassword" : nsPassword,
    //       @"newPassword" : nsNewPassword,
    //       };
    //
    //    NSString *currentTime = [[NSDate date] httpParameterString];
    //    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    //    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_UserResetPassword] stringByAppendingFormat:@"/%@?time=%@&operator.id=%@&operator.operName=%@&enterprise=%@",userUtil.userId,currentTime,userUtil.userCode,userUtil.displayName,userUtil.orgId];
    //    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//对url进行utf-8编码,否则不合法
    //    CLog(@"%@",encodeUrlStr);
    //    [self POST:encodeUrlStr
    //    parameters:dictParametes
    //     needToken:NO
    //acceptTypeJson:YES
    //       success:success
    //       failure:failure];
}

#pragma mark - Board
- (void)doGetBoardListFromUpdateTime:(NSString *)updateTime
                            position:(NSUInteger)uiPosition
                                size:(NSUInteger)uiSize
                                type:(ICRAnnouncementType)eType
                         deleteLocal:(BOOL)bDeleteLocal
                             success:(void (^)(id data))succ
                             failure:(void (^)(id data))fail
{
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@", responseObject);
        
        if (IsDictObject(responseObject)) {
            void (^complete)(void) = ^(void){
                if (succ) {
                    [IBTCommon runOnMainThreadWithoutDeadlocking:^{
                        succ( responseObject );
                    }];
                }
            };
            
            void(^dataHandle)(id<IBTDatabaseObject>) = ^(id<IBTDatabaseObject> model) {
                ICRAnnouncement *ann = model;
                ann.priority = eType;
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"ICRAnnouncement" )
                        deleteLocal:bDeleteLocal
                         handleData:dataHandle
                           complete:complete
                               fail:fail];
        }
        else {
            if (fail) {
                fail( nil );
            }
        }
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_BoardQuery] stringByAppendingFormat:@"/%@?start_date=%@&page_number=%@&page_size=%@",[[VankeCommonModel sharedInstance] currentUser].uuid ,updateTime ? : [[NSDate dateWithTimeIntervalSince1970:0] httpParameterString],@( uiPosition ),@( uiSize )];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",encodeUrlStr);
    [self POST:encodeUrlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

- (void)doGetBoardWithID:(NSNumber *)boardID
                 success:(void (^)(id data))succ
                 failure:(void (^)(id data))fail
{
    if (!boardID) {
        if (fail) {
            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
        }
        return;
    }
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@", responseObject);
        if (IsDictObject(responseObject)) {
            void (^complete)(void) = ^(void){
                if (succ) {
                    [IBTCommon runOnMainThreadWithoutDeadlocking:^{
                        succ( responseObject );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntity:responseObject[ @"data" ]
                      objectClass:NSClassFromString( @"ICRAnnouncement" )
                       handleData:NULL
                         complete:complete
                             fail:fail];
            
        };
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
    //    http://.../cruiser-server/rest/affiche/download/{affiche_uuid}
    //    http://218.244.151.129:8280/cruiser-server/rest/affiche/download/5a7417014eb34067014eb4fea404003e
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_BoardQuery] stringByAppendingFormat:@"/%@", boardID];
    NSLog(@"%@",urlStr);
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}

- (void)doReadBoardWithID:(NSNumber *)boardID
                  success:(void (^)(id data))succ
                  failure:(void (^)(id data))fail
{
    //    if (!boardID) {
    //        if (fail) {
    //            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
    //        }
    //        return;
    //    }
    //
    //    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
    //        CLog(@"%@", responseObject);
    //        if (succ) {
    //            succ( responseObject );
    //        }
    //    };
    //
    //    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
    //        CLog(@"%@", error);
    //        if (fail) {
    //            fail( error );
    //        }
    //    };
    //
    //    NSDictionary *dictParametes =
    //    @{ @"readTime" : [[NSDate date] httpParameterString],
    //       };
    //
    //    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_ReadBoard] stringByAppendingFormat:@"/%@", boardID];
    //    [self POST:urlStr
    //    parameters:dictParametes
    //     needToken:YES
    //acceptTypeJson:YES
    //       success:success
    //       failure:failure];
}


#pragma mark - Attachment
- (void)doAddAttachment:(id)data
                success:(void (^)(id data))succ
                failure:(void (^)(id data))fail
{
    //    if (!data) {
    //        if (fail) {
    //            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
    //        }
    //        return;
    //    }
    //
    //    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
    //        CLog(@"%@", responseObject);
    //        if (succ) {
    //            succ( responseObject );
    //        }
    //    };
    //
    //    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
    //        CLog(@"%@", error);
    //        if (fail) {
    //            fail( error );
    //        }
    //    };
    //
    //    NSDictionary *dictParametes = data;
    //    NSLog(@"%@",data);
    //
    //    NSString *urlStr = [[self class] UrlForPluginHTTPAction:kICRHTTP_AttachmentAdd];
    //     NSLog(@"%@",urlStr);
    //    [self POST:urlStr
    //    parameters:dictParametes
    //     needToken:NO
    //acceptTypeJson:YES
    //       success:success
    //       failure:failure];
}

- (void)doGetAttachmentListWithType:(ICRAttachmentType)eType
                              objID:(NSString *)objID
                            success:(void (^)(id data))succ
                            failure:(void (^)(id data))fail;
{
    //    if (eType >= kAttachmentTypeCount || !objID) {
    //        if (fail) {
    //            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
    //        }
    //        return;
    //    }
    //
    //    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
    //        CLog(@"%@", responseObject);
    //
    //        if (IsDictObject(responseObject)) {
    //            void (^complete)(void) = ^(void){
    //                if (succ) {
    //                    [IBTCommon runOnMainThreadWithoutDeadlocking:^{
    //                        succ( responseObject );
    //                    }];
    //                }
    //            };
    //
    //            void(^dataHandle)(id<IBTDatabaseObject>) = ^(id<IBTDatabaseObject> model) {
    //                ICRAttachment *att = model;
    //                att.objectId = objID;
    //            };
    //
    //            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    //            [dbCtrl storageEntities:responseObject[ @"result" ]
    //                        objectClass:NSClassFromString( @"ICRAttachment" )
    //                        deleteLocal:NO
    //                         handleData:dataHandle
    //                           complete:complete
    //                               fail:fail];
    //        }
    //        else {
    //            if (fail) {
    //                fail( nil );
    //            }
    //        }
    //    };
    //
    //    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
    //        CLog(@"%@", error);
    //        if (fail) {
    //            fail( error );
    //        }
    //    };
    //    NSDictionary *dictParametes =
    //    @{ @"type" : ICRAttachmentTypeValue[ eType ],
    //       @"objectId" : objID
    //       };
    //
    //    NSString *urlStr = [[self class] UrlForPluginHTTPAction:kICRHTTP_AttachmentList];
    //    [self POST:urlStr
    //    parameters:dictParametes
    //     needToken:YES
    //acceptTypeJson:YES
    //       success:success
    //       failure:failure];
}

- (void)doDownloadAttachmentWithID:(NSNumber *)attachmentID
                           success:(void (^)(id data))succ
                           failure:(void (^)(id data))fail
{
    //    if (!attachmentID) {
    //        if (fail) {
    //            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
    //        }
    //        return;
    //    }
    //
    //    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
    //        CLog(@"%@", responseObject);
    //        if (succ) {
    //            succ( responseObject );
    //        }
    //    };
    //    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
    //        CLog(@"%@", error);
    //        if (fail) {
    //            fail( error );
    //        }
    //    };
    //    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_AttachmentDownload] stringByAppendingFormat:@"/%@",attachmentID];
    //    [self GET:urlStr
    //    parameters:nil
    //     needToken:YES
    //acceptTypeJson:YES
    //       success:success
    //       failure:failure];
}

- (void)doAddDirectAttachment:(id)data
                      success:(void (^)(id))succ
                      failure:(void (^)(id))fail
{
    //TODO
}

+ (NSString *)AttachmentUrlWithID:(id)attachmentID {
    
    if (!attachmentID) {
        return nil;
    }
    
    return [[[self class] UrlForPluginHTTPAction:kICRHTTP_AttachmentDownloadDirect]stringByAppendingFormat:@"/%@",attachmentID];
}

- (void)doDownloadDirectAttachment:(NSString *)attachmentId
                           success:(void (^)(id))succ
                           failure:(void (^)(id))fail
{
    // TODO
}


- (void)postUrl:(NSString *)url params:(id)params success:(void (^)(id data))succ failure:(void (^)(id data))fail {
    
    NSString *requestUrl =  [VANKE_SERVER_BASE_URL stringByAppendingFormat:@"/%@", url];
    
    [self POST:requestUrl parameters:params needToken:YES acceptTypeJson:YES success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        succ(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        fail(error);
    }];
}

- (void)getUrl:(NSString *)url params:(id)params success:(void (^)(id data))succ failure:(void (^)(id data))fail {
    
    NSString *requestUrl =  [VANKE_SERVER_BASE_URL stringByAppendingFormat:@"/%@", url];
    
    [self GET:requestUrl parameters:params needToken:YES acceptTypeJson:YES success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        succ(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        fail(error);
    }];
    
    
}

@end
