//
//  ICRHTTPController.m
//  XFFruit
//
//  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 "ICRStoreResult.h"

#define MAX_CONCURRENCY_UPLOAD      1
#define MAX_CONCURRENCY_DOWNLOAD    3

#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,
    
    //行情
    XFFHttp_SurveySave,
    XFFHttp_QuerySurvey,
    XFFHttp_GetSurvey,
    XFFHttp_GetProduct,
    XFFHttp_GetUser,
    XFFHttp_SurveyFinish,
    //行情反馈图片
    XFFHttp_ResultChart,
    XFFHttp_GetResults
};

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",
    //行情调研
    [XFFHttp_SurveySave]                    = @"survey/save_survey",
    [XFFHttp_QuerySurvey]                   = @"survey/query_survey",
    [XFFHttp_GetSurvey]                    = @"survey/get_survey",
    [XFFHttp_GetProduct]                    = @"mdata/product/download",
    [XFFHttp_GetUser]                       = @"user/download",
    [XFFHttp_SurveyFinish]                  = @"survey/finish",
    //行情反馈生成图片
    [XFFHttp_ResultChart]                   = @"survey/resultchart",
    [XFFHttp_GetResults]                   = @"survey/get_results"
};

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];
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    if (bIsNeedToken) {
        if ([user.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参数
    if(user.orgId != NULL)
    {
        [requestSerializer setValue:user.orgId forHTTPHeaderField:@"enterprise"];
    }
    [requestSerializer setValue:user.authenticode 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.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
       [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];
}

#pragma mark - User
- (void)doLoginWithUserName:(NSString *)nsUserName
                   password:(NSString *)nsPassword
               registerCode:(NSString *)nsRegisterCode
                    success:(void (^)(id data))succ
                    failure:(void (^)(id data))fail
{
    if (!nsUserName || !nsPassword || !nsRegisterCode) {
        if (fail) {
            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
        }
        return;
    }
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        CLog(@"%@",responseObject);
        
        id dictResult = responseObject[ @"data" ];
        if (dictResult) {
            
            ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
            userUtil.userName = nsUserName;
            userUtil.password = nsPassword;
            userUtil.registerCode = nsRegisterCode;
            userUtil.displayName = dictResult[ @"user_name" ];
            userUtil.userCode =dictResult[ @"user_code" ];
            userUtil.userId = dictResult[ @"user_uuid" ];
            userUtil.orgCode = dictResult[ @"enterprise_code" ];
            userUtil.orgName = dictResult[ @"enterprise_name" ];
            userUtil.orgId = dictResult[ @"enterprise_uuid" ];
            userUtil.authenticode = dictResult[@"authenticode"];
            [userUtil saveArchive];
            if (succ) {
                succ( dictResult );
            }
        }
        else {
            if (fail) {
                fail( nil );
            }
        }
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        CLog(@"%@",error);
        if (fail) {
            fail( error );
        }
    };
    
    NSDictionary *dictParametes =
    @{ @"password" : nsPassword,
       @"authenticode" : nsRegisterCode,
      };
    
    NSLog(@"%@",dictParametes);
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_UserLogin] stringByAppendingFormat:@"/%@", nsUserName];
    [self POST:urlStr
    parameters:dictParametes
     needToken:NO
acceptTypeJson:YES
       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) {
        CLog(@"%@", responseObject);
        if (succ) {
            succ( responseObject );
        }
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
//http://.../XFFruit-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 - Data
- (void)doGetStoreListFromUpdateTime:(NSTimeInterval)updateTime
                            position:(NSUInteger)uiPosition
                                size:(NSUInteger)uiSize
                             success:(void (^)(id data))succ
                             failure:(void (^)(id data))fail
{
    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 );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"ICRStore" )
                        deleteLocal:YES
                         handleData:NULL
                         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 );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_StoreQuery] stringByAppendingFormat:@"?start_date=%@&page_number=%@&page_size=%@", [[NSDate dateWithTimeIntervalSince1970:updateTime] httpParameterString],@(uiPosition),@(uiSize)];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters:NULL
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

- (void)doGetCurrentOrgWithSuccess:(void (^)(id data))succ
                           failure:(void (^)(id data))fail
{
    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_StoreQuery];
    [self GET:urlStr
   parameters:nil
    needToken:YES
acceptTypeJson:YES
      success:success
      failure:failure];
}

- (void)doGetPersonListFromUpdateTime:(NSString *)updateTime
                           position:(NSUInteger)uiPosition
                               size:(NSUInteger)uiSize
                            success:(void (^)(id data))succ
                            failure:(void (^)(id data))fail
{
    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 );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"ICRPerson" )
                        deleteLocal:YES
                         handleData:NULL
                           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 );
        }
    };
    //http://.../XFFruit-server/rest/user/download?start_date=? &page_number=?&page_size=?
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_PersonQuery] stringByAppendingFormat:@"?start_date=%@&page_number=%@&page_size=%@",updateTime ? : [[NSDate dateWithTimeIntervalSince1970:0] httpParameterString],@( uiPosition ),@( uiSize )];
    NSString * encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"=======>>>>>>>>>>>>>>>%@",encodeUrlStr);
    [self POST:encodeUrlStr
    parameters:NULL
     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) {
        CLog(@"%@", 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) {
        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_BoardQuery] stringByAppendingFormat:@"/%@?start_date=%@&page_number=%@&page_size=%@",[[ICRUserUtil sharedInstance] userId],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) {
        CLog(@"%@", 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) {
        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
//    http://.../XFFruit-server/rest/affiche/download/{affiche_uuid}
//    http://218.244.151.129:8280/XFFruit-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 - Patrol
- (void)doGetMyPatrolFromUpdateTime:(NSString *)updateTime
                           position:(NSUInteger)uiPosition
                               size:(NSUInteger)uiSize
                            success:(void (^)(id data))succ
                            failure:(void (^)(id data))fail
{
    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 );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"ICRPatrolPlan" )
                        deleteLocal:YES
                         handleData:NULL
                           complete:complete
                               fail:fail];
      };
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction: kICRHTTP_PatrolQuery]
        stringByAppendingFormat:@"/%@?&start_date=%@&page_number=%@&page_size=%@",[[ICRUserUtil sharedInstance] userId],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)doGetStoreResultWithPlanID:(NSString *)planID
                           storeID:(NSString *)storeID
                           success:(void (^)(id data))succ
                           failure:(void (^)(id data))fail
{
    if (!planID || !storeID) {
        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) {
                ICRStoreResult *sR = model;
                sR.uuid = planID;
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntity:responseObject[ @"data" ]
                      objectClass:NSClassFromString( @"ICRStoreResult" )
                       handleData:dataHandle
                         complete:complete fail:fail];
        };

        if (succ) {
            succ( responseObject );
        }
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
//    请求URL：http://.../XFFruit-server/rest/patrol/plan/get_store_result/{plan_uuid}?store_uuid
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_AnswerStoreResult] stringByAppendingFormat:@"/%@?store_uuid=%@", planID, storeID];
    NSLog(@"%@",urlStr);
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];

}

- (void)doAnswerPatrolPlanWithID:(NSString *)planID
                        infoData:(id)data
                         success:(void (^)(id data))succ
                         failure:(void (^)(id data))fail
{
    if (!planID || !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===>>>%@",data);
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_PatrolAnswer] stringByAppendingFormat:@"/%@", planID];
    NSLog(@"%@",urlStr);
    [self POST:urlStr
    parameters:dictParametes
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

- (void)doAnswerOnePatrolResultWithID:(NSNumber *)resultID
                             infoData:(id)data
                              success:(void (^)(id data))succ
                              failure:(void (^)(id data))fail
{
    if (!resultID || !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;
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_PatrolOneAnswer] stringByAppendingFormat:@"/%@", resultID];
    [self POST:urlStr
    parameters:dictParametes
     needToken:YES
acceptTypeJson:YES
       success:success
       failure:failure];
}

#pragma mark - Task
- (void)doGetTaskListFromUpdateTime:(NSString *)updateTime
                           position:(NSUInteger)uiPosition
                               size:(NSUInteger)uiSize
                            success:(void (^)(id data))succ
                            failure:(void (^)(id data))fail
{
    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 );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"ICRTask" )
                          updateNil:NO
                        deleteLocal:YES
                         handleData:NULL
                           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 );
        }
    };
       NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_MyTaskQuery] stringByAppendingFormat:@"?processor=%@&start_date=%@&page_number=%@&page_size=%@",[[ICRUserUtil sharedInstance] userCode],updateTime ? : [[NSDate dateWithTimeIntervalSince1970:0] httpParameterString],@( uiPosition ),@( uiSize )];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",encodeUrlStr);
    [self POST:encodeUrlStr
    parameters:NULL
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

- (void)doCreateNewTaskWithInfo:(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(@"------%@",dictParametes);
    
    NSString *urlStr = [[self class] UrlForPluginHTTPAction:kICRHTTP_TaskNew];
    [self POST:urlStr
    parameters:dictParametes
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

- (void)doUpdateTaskResultID:(NSString *)resultID
                  resultText:(NSString *)resultStr
                 processDate:(NSTimeInterval)processDate
                     success:(void (^)(id data))succ
                     failure:(void (^)(id data))fail
{
    if (!resultStr) {
        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 =
    @{ @"result" : resultStr
       };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_TaskResult] stringByAppendingFormat:@"/%@/process", resultID];
    [self POST:urlStr
    parameters:dictParametes
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

- (void)doSignupWithInfo:(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(@"%@",dictParametes);
    
    NSString *urlStr = [[self class] UrlForPluginHTTPAction:kICRHTTP_SignUp];
    NSLog(@"%@",urlStr);
    [self POST:urlStr
    parameters:dictParametes
     needToken:NO
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
}

#pragma mark - Version
- (void)doFetchVersionWithCurrent:(NSString *)currentVersion
                          success:(void (^)(id))succ
                          failure:(void (^)(id))fail
{
    if (!currentVersion) {
        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_VersionFetch] stringByAppendingFormat:@"/%@",currentVersion];
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}


//添加行情调研单
- (void)saveSurveyWithAuthenticode:(id)data success:(void (^)(id))succ failure:(void (^)(id))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 *dict = data;
    NSString *currentTime = [[NSDate date] httpParameterString];
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:XFFHttp_SurveySave] stringByAppendingFormat:@"?time=%@&operId=%@&operName=%@",currentTime,userUtil.userCode,userUtil.displayName];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters:dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}


//获取行情调研单列表
- (void)querySurveyWithBillData:(id)data
                        success:(void (^)(id))succ
                        failure:(void (^)(id))fail{
    
    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 *dict = data;
    NSString *urlStr = [[self class] UrlForPluginHTTPAction:XFFHttp_QuerySurvey];
    [self POST:urlStr
    parameters:dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}


//获取行情调研详情
- (void)getResultWithSurveyUuid:(NSString *)surveyUuid
                        success:(void (^)(id))succ
                        failure:(void (^)(id))fail{
    if (!surveyUuid) {
        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:XFFHttp_GetSurvey] stringByAppendingFormat:@"/%@",surveyUuid];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
   [self GET:encodeUrlStr
  parameters:nil
   needToken:NO
acceptTypeJson:YES
     success:success
     failure:failure];
}


-(void)getProductWithPage_number:(NSUInteger)page_number
                       page_size:(NSUInteger)page_size
                         success:(void (^)(id))succ
                         failure:(void (^)(id))fail{
    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 );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"Product" )
                        deleteLocal:YES
                         handleData:NULL
                           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 );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:XFFHttp_GetProduct] stringByAppendingFormat:@"?start_date=%@&page_number=%@&page_size=%@", [[NSDate date] httpParameterString],@(page_number),@(page_size)];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters:NULL
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}


- (void)getUserWithPage_number:(NSUInteger)page_number
                     page_size:(NSUInteger)page_size
                       success:(void (^)(id))succ
                       failure:(void (^)(id))fail{
    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 );
                    }];
                }
            };
            
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"User" )
                        deleteLocal:YES
                         handleData:NULL
                           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 );
        }
    };
    NSString *dateStr = @"2015-01-01";
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:XFFHttp_GetUser] stringByAppendingFormat:@"?start_date=%@&page_number=%@&page_size=%@", dateStr,@(page_number),@(page_size)];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters:NULL
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}
- (void)resultChartWithResultUuid:(NSString *)uuid
                            width:(NSNumber *)width
                           height:(NSNumber *)height
                          success:(void (^)(id))succ
                          failure:(void (^)(id))fail{
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        CLog(@"%@", responseObject);
        if (IsDictObject(responseObject)) {
                if (succ) {
                    [IBTCommon runOnMainThreadWithoutDeadlocking:^{
                        succ( responseObject );
                    }];
                }
        }
        else {
            if (fail) {
                fail( nil );
            }
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:XFFHttp_ResultChart] stringByAppendingFormat:@"/%@?width=%@&height=%@",uuid,width,height];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self GET:encodeUrlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}

//结束行情反馈(写)
- (void)surveyFinishWithUuid:(NSString *)uuid
                     success:(void (^)(id))succ
                     failure:(void (^)(id))fail{
    
    if (!uuid) {
        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 *currentTime = [[NSDate date] httpParameterString];
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:XFFHttp_SurveyFinish] stringByAppendingFormat:@"/%@?time=%@&operId=%@&operName=%@",uuid,currentTime,userUtil.userCode,userUtil.displayName];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self GET:encodeUrlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];

}
//获取行情调研单反馈列表
- (void)getResultsWithUuid:(NSString *)uuid
                   success:(void (^)(id))succ
                   failure:(void (^)(id))fail{
    if (!uuid) {
        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:XFFHttp_GetResults] stringByAppendingFormat:@"/%@",uuid];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}


@end
