#import "ICRHTTPController.h"
#import "ICRUserUtil.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"

#import "IBTModel.h"
#import "ICRStoreResult.h"
#import "GTOPatrolTemplate.h"
#import "ICRPostAttachment.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,
    kICRHTTP_PostQuery,
    
    // Board
    kICRHTTP_BoardQuery,
    kICRHTTP_FetchBoard,
    kICRHTTP_ReadBoard,
    
    // Patrol
    kICRHTTP_PatrolQuery,
    kICRHTTP_AnswerStoreResult,
    kICRHTTP_PatrolAnswer,
    kICRHTTP_PatrolOneAnswer,
    
    // Task
    kICRHTTP_TaskQuery,
    kICRHTTP_TaskNew,
    kICRHTTP_TaskResult,
    
    // Signup
    kICRHTTP_SignUp,
    
    // Attachment
    kICRHTTP_AttachmentAdd,
    kICRHTTP_AttachmentList,
    kICRHTTP_AttachmentDownload,
    kICRHTTP_AttachmentAddDirect,
    kICRHTTP_AttachmentDownloadDirect,
    
    // Version
    kICRHTTP_VersionFetch,
    
    //中化道达尔
    //user
    kGTOHTTP_UserLogin,
    //门店
    kGTOHTTP_PatrolStore,
    //巡检任务
    kGTOHTTP_PatrolQuery,
    //  Patrol
    kGTOHTTP_AnswerStoreResult,
    //提交巡检结果
    kGTOHTTP_SubmitPatrolAnswer,
    //2.1	下载巡检模板
    kGTOHTTP_PatrolTemplate,
    //4.1获取报修单列表
    kGTOHTTP_RepairQuery,
    kGTOHTTP_RepairItems,
    kGTOHTTP_RepairApplication,
    kGTOHTTP_RepairFinish,
    //5
    kGTOHTTP_LicenceSaveResult,
    kGTOHTTP_LicenceSubmitResult,
    kGTOHTTP_LicenceQuery,
    kGTOHTTP_LicenceItems,
    kGTOHTTP_LicenceRemove,
    kGTOHTTP_LicenceReject,
    kGTOHTTP_LicenceApprove,
    kGTOHTTP_LicenceAskForApprove,
    kGTOHTTP_LicenceClose,
    kGTOHTTP_LicenceGetLogs,
    //6.1 保存拓站（写）
    kGTOHTTP_PioneeringSaveResult,
    //6.2 提交拓站（写）
    kGTOHTTP_PioneeringSubmitResult,
    //6.3 获取拓站列表（读）
    kGTOHTTP_PioneeringQuery,
    //6.3 获取拓站明细（读）
    kGTOHTTP_PioneeringItems,
    kGTOHTTP_PioneeringRemove,
    
    kGTOHTTP_AttachmentUpload,
    kGTOHTTP_AttachmentUploadByFile,
    kGTOHTTP_AttachmentGetUrls,
    kGTOHTTP_AttachmentDel,
    //版本更新
    XFFHttp_getVersionId,
   //签到
    XFFHttp_getSignin,
    kGTOHTTP_nearStore,
};

static NSString * const ICRHTTPInterface[] = {
    [ kICRHTTP_Dummy ]                      = @"",
    
    // User
    [ kICRHTTP_UserLogin ]                  = @"user/login",
    [ kICRHTTP_UserResetPassword ]          = @"user/change_password",
    
    // Data
    [ kICRHTTP_StoreQuery ]                 = @"data/store/query",
    [ kICRHTTP_CurrentOrg ]                 = @"data/organization/currentOrg",
    [ kICRHTTP_PostQuery ]                  = @"data/post/query",
    
    // Board
    [ kICRHTTP_BoardQuery ]                 = @"affiche/download",
    [ kICRHTTP_FetchBoard ]                 = @"affiche/get",
    [ kICRHTTP_ReadBoard ]                  = @"affiche/read",
    
    // Patrol
    [ kICRHTTP_PatrolQuery ]                = @"patrol/query",
    [ kICRHTTP_AnswerStoreResult ]          = @"patrol/answer/storeResult",
    [ kICRHTTP_PatrolAnswer ]               = @"patrol/answer",
    [ kICRHTTP_PatrolOneAnswer ]            = @"patrol/oneAnswer",
    
    // Task
    [ kICRHTTP_TaskQuery ]                  = @"task/query",
    [ kICRHTTP_TaskNew ]                    = @"task/new",
    [ kICRHTTP_TaskResult ]                 = @"task/result",
    
    // Signup
    [ kICRHTTP_SignUp ]                     = @"signup/signup",
    
    // Attachment
    [ kICRHTTP_AttachmentAdd ]              = @"attachment/add",
    [ kICRHTTP_AttachmentList ]             = @"attachment/list",
    [ kICRHTTP_AttachmentDownload ]         = @"attachment/download",
    [ kICRHTTP_AttachmentAddDirect ]        = @"attachment/addDirect",
    [ kICRHTTP_AttachmentDownloadDirect ]   = @"attachment/downloadDirect",
    
    // Version
    [ kICRHTTP_VersionFetch ]               = @"version/fetch",
    
    
    //中化道达尔
    // User
    [ kGTOHTTP_UserLogin ]                  = @"user/login",
    //门店
    [kGTOHTTP_PatrolStore]              = @"mdata/store/download",
    //巡检任务
    [kGTOHTTP_PatrolQuery]       =  @"patrol/plan/download",
    //提交巡检结果
    [kGTOHTTP_SubmitPatrolAnswer] = @"patrol/plan/submit_result",
    //下载结果
   [ kGTOHTTP_AnswerStoreResult] =  @"patrol/plan/get_store_result",
    //2.1	下载巡检模板
    [kGTOHTTP_PatrolTemplate]    = @"patrol/template/download",
    
   [ kGTOHTTP_RepairQuery] = @"repair/query",
   [ kGTOHTTP_RepairItems] = @"repair/get",
    [kGTOHTTP_RepairFinish] =@"repair/finish",
    [kGTOHTTP_RepairApplication] = @"repair/application",
    [kGTOHTTP_LicenceSaveResult] = @"licence/save",
    [kGTOHTTP_LicenceSubmitResult] = @"licence/submit",
    [kGTOHTTP_LicenceQuery] = @"licence/query",
    [kGTOHTTP_LicenceItems] = @"licence/get",
    [kGTOHTTP_LicenceRemove] = @"licence/remove",
    [kGTOHTTP_LicenceReject] = @"licence/reject",
    [kGTOHTTP_LicenceApprove] = @"licence/approve",
    [kGTOHTTP_LicenceAskForApprove] = @"licence/askforapprove",
    [kGTOHTTP_LicenceClose] = @"licence/finish",
    [kGTOHTTP_LicenceGetLogs] = @"licence/get_logs",

    //6.1 保存拓站（写）
    [kGTOHTTP_PioneeringSaveResult] = @"pioneering/save",
    //6.2 提交拓站（写）
    [kGTOHTTP_PioneeringSubmitResult] = @"pioneering/submit",
    //6.3 获取拓站列表（读）
    [kGTOHTTP_PioneeringQuery] = @"pioneering/query",
    [kGTOHTTP_PioneeringItems] = @"pioneering/get",
    [kGTOHTTP_PioneeringRemove] = @"pioneering/remove",
    
    [kGTOHTTP_AttachmentUpload] = @"attachment/upload",
    
    [kGTOHTTP_AttachmentUploadByFile]=@"attachment/upload_by_file",
    [kGTOHTTP_AttachmentGetUrls] = @"attachment/get_urls",
    [ kGTOHTTP_AttachmentDel] = @"attachment/remove_uuids",
    //版本更新
    [XFFHttp_getVersionId]                  =@"ipapk",
    [XFFHttp_getSignin]                 =@"signin",
    [kGTOHTTP_nearStore] = @"mdata/store/location",
};

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];
    if (bIsNeedToken) {
        
        ICRUserUtil *user = [ICRUserUtil sharedInstance];
        
        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"];
    
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    //请求头添加enterprise参数
    if(user.f_enterprise_uuid != NULL)
    {
        [requestSerializer setValue:user.f_enterprise_uuid forHTTPHeaderField:@"enterprise"];
    }
    [requestSerializer setValue:user.f_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;
    
    // 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;
    
    // The request add in operation
    [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];
            BOOL condition =
            (![userUtil.f_user_loginName isEqualToString:nsUserName])
            || (![userUtil.f_authenticode isEqualToString:nsRegisterCode]);
//            || !userUtil.f_authenticode
//            || !userUtil.f_user_loginName;
            NSString *archivePath = [IBTCommon archivePathForCurrentUser];
//            CLog(@"path = %@",archivePath);
            if (condition) {

                NSFileManager *fileMgr = [NSFileManager defaultManager];
                BOOL bRet = [fileMgr fileExistsAtPath:archivePath];
                if (bRet) {
                    NSError *err;
                    BOOL rig = [fileMgr removeItemAtPath:archivePath error:&err];
                    [ICRDataBaseController attemptDealloc];
                    //ICRDataBaseController *sharedController = nil;
                    NSLog(@"%d",rig);
                }
            }
            userUtil.f_authenticode = nsRegisterCode;
            userUtil.f_user_password = nsPassword;
            userUtil.f_user_loginName = nsUserName;
            userUtil.f_user_code = dictResult[ @"user_code" ];
            userUtil.f_user_name = dictResult[ @"user_name" ];
            userUtil.f_user_uuid = dictResult[ @"user_uuid" ];
            userUtil.orgCode = dictResult[ @"org_code" ];
            userUtil.orgName = dictResult[ @"org_name" ];
            userUtil.orguuid = dictResult[ @"org_uuid" ];
            userUtil.position = dictResult[@"position"];
            userUtil.f_enterprise_code = dictResult[ @"enterprise_code" ];
            userUtil.f_enterprise_name = dictResult[ @"enterprise_name" ];
            userUtil.f_enterprise_uuid = dictResult[ @"enterprise_uuid" ];
            userUtil.f_permissions = dictResult[ @"permissions" ];
            userUtil.position = dictResult[@"position"];
            userUtil.hasAffichePermission = [GTOCommonTools hasPermissionWithPermissionId:500601] || [GTOCommonTools hasPermissionWithPermissionId:500602];
            userUtil.hasProjectPatrolPermission = [GTOCommonTools hasPermissionWithPermissionId:500101] || [GTOCommonTools hasPermissionWithPermissionId:500102];
            userUtil.hasHSEPatrolPermission = [GTOCommonTools hasPermissionWithPermissionId:500201] || [GTOCommonTools hasPermissionWithPermissionId:500202];
            userUtil.hasLicencePermission = [GTOCommonTools hasPermissionWithPermissionId:500403] || [GTOCommonTools hasPermissionWithPermissionId:500404] ;

            [userUtil saveArchive];
            
            if (succ) {
                succ( dictResult );
            }
        
           
        }
        else {
             [IBTLoadingView hideHUDWithText:responseObject[@"message"]];
//            if (fail) {
//                fail( nil )
//            }
        }
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@",error);
        if (fail) {
            fail( error );
        }
    };
    
    
    NSDictionary *dictParametes =
    @{ @"password" : [nsPassword uppercaseMD5String],
       @"authenticode" : nsRegisterCode,
       };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_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 );
        }
    };
    
    NSDictionary *dictParametes =
    @{ @"oldPassword" : nsPassword,
       @"newPassword" : nsNewPassword,
       };
    
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_UserResetPassword] stringByAppendingFormat:@"/%@?time=%@&operId=%@&operName=%@",userU.f_user_uuid,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //url 中 含有中文
    [self POST:encodeStr
    parameters:dictParametes
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}


////下载
//- (void)p_postDownInfoWithHasUuid: (BOOL)hasUuid
//                      ClassString: (NSString *)classStr
//                     pluginHTTPAction: (NSUInteger)httpAction
//                            startTime: (NSString *)start_time
//
//                           pageNumber:(NSUInteger)page_number
//                             pageSize:(NSUInteger)page_size
//                              success:(void (^)(id))succ
//                              failure:(void (^)(id))fail {
//下载
- (void)p_postDownInfoWithUrlString: (NSString *)urlStr
                      ClassString: (NSString *)classStr
                          success:(void (^)(id))succ
                          failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
     
//        CLog(@"%@", responseObject);
        //         void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        if (succ) {
            succ( responseObject );
        }


//                if (IsDictObject(responseObject)) {
//                    void (^complete)(void) = ^(void){
//                        if (succ) {
//                            [IBTCommon runOnMainThreadWithoutDeadlocking:^{
//                                succ( responseObject );
//                            }];
//                        }
//                    };
//                    CLog(@"%@",responseObject[ @"data" ][ @"records" ]);
//                    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
//                    [dbCtrl storageEntities:responseObject[ @"data" ][ @"records" ]
//                                objectClass:NSClassFromString( classStr )
//                                deleteLocal:NO
//                                 handleData:NULL
//                                   complete:complete
//                                       fail:fail];
//                };
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    
//    NSString *urlStr ;
//    if (hasUuid) {
//        urlStr =   [[[self class] UrlForPluginHTTPAction: httpAction]
//                      stringByAppendingFormat:@"/%@?&start_date=%@&page_number=%@&page_size=%@",[[ICRUserUtil sharedInstance] f_user_code],[[NSDate date]httpParameterString] ,@( page_number ),@( page_size )];//@"2015-06-16 21:48:2"2015-05-04  updateTime ? :
//    } else {
//        urlStr =   [[[self class] UrlForPluginHTTPAction: httpAction]
//                    stringByAppendingFormat:@"?&start_date=%@&page_number=%@&page_size=%@",[[NSDate date]httpParameterString] ,@( page_number ),@( page_size )];//@"2015-06-16 21:48:2"2015-05-04  updateTime ? :
//    }

    
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    CLog(@"%@",encodeUrlStr);//402851814e20d2d9014e20d2e9180031
    [self POST:encodeUrlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}
- (void)getStoreWithStartTime:(NSString *)start_time pageNumber:(NSUInteger)page_number pageSize:(NSUInteger)page_size success:(void (^)(id))succ failure:(void (^)(id))fail {
    NSString *urlStr =   [[[self class] UrlForPluginHTTPAction: kGTOHTTP_PatrolStore]
                stringByAppendingFormat:@"?&start_date=%@&page_number=%@&page_size=%@",start_time ,@( page_number ),@( page_size )];
    [self p_postDownInfoWithUrlString:urlStr ClassString:@"GTOStore" success:succ failure:fail];
//   [self p_postDownInfoWithHasUuid:NO ClassString:@"GTOStore" pluginHTTPAction:kGTOHTTP_PatrolStore startTime:start_time   pageNumber:page_number pageSize:page_size success:succ failure:fail];
    
    
}
- (void)getMyPatrolWithCategory: (NSString *)category
                              startTime:(NSString *)start_time
                         dateType:(NSString *)date_type
                  pageNumber:(NSUInteger)page_number
                    pageSize:(NSUInteger)page_size
                     success:(void (^)(id data))succ
                     failure:(void (^)(id data))fail;
{
    NSString *urlStr =   [[[self class] UrlForPluginHTTPAction: kGTOHTTP_PatrolQuery]
                          stringByAppendingFormat:@"/%@?&start_date=%@&date_type=%@&page_number=%@&page_size=%@&category=%@",[[ICRUserUtil sharedInstance] f_user_uuid],start_time ,date_type,@( page_number ),@( page_size ),category];
    [self p_postDownInfoWithUrlString:urlStr ClassString:@"GTOPatrolPlan" success:succ failure:fail];
//       [self p_postDownInfoWithHasUuid:YES ClassString:@"GTOPatrolPlan" pluginHTTPAction:kGTOHTTP_PatrolQuery startTime:start_time endTime:nil pageNumber:page_number pageSize:page_size success:succ failure:fail];

}


//1.4   下载 门店
- (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 );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_AnswerStoreResult] stringByAppendingFormat:@"/%@?store_uuid=%@", planID, storeID];
    NSLog(@"%@",urlStr);
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
    
}
//2.1 下载巡检模板

//UseUuid: (NSString *)userUuid
                          // startTime:(NSString *)start_time
- (void)getPatrolTemplateWithPurpose: ( NSString *)purpose
                          pageNumber:(NSUInteger)page_number
                            pageSize:(NSUInteger)page_size
                             success:(void (^)(id data))succ
                             failure:(void (^)(id data))fail {

    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
         [IBTLoadingView hideHUDWithText:nil];
        if (IsDictObject(responseObject)) {
            void (^complete)(void) = ^(void){
                if (succ) {
                    [IBTCommon runOnMainThreadWithoutDeadlocking:^{
                        succ( responseObject );
                    }];
                }
            };
//            CLog(@"%@",responseObject[ @"data" ][ @"records" ]);
            //for(NSDictionary *dict in responseObject[ @"data" ][ @"records" ]) {
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl storageEntities: responseObject[ @"data" ][ @"records" ]
                        objectClass:NSClassFromString( @"GTOPatrolTemplate")
                        deleteLocal:YES
                         handleData:NULL
                           complete:complete
                               fail:fail];
        };
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
         [IBTLoadingView hideHUDWithText:nil];
//        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };



    NSString *urlStr =   [[[self class] UrlForPluginHTTPAction: kGTOHTTP_PatrolTemplate]
                    stringByAppendingFormat:@"?start_date=%@&purpose=%@&page_number=%@&page_size=%@",
                    [[NSDate date] httpParameterString],
                    purpose,@( page_number ),@( page_size )];//@"2015-06-16 21:48:2"2015-05-04  updateTime ? :
  //  [[NSDate dateWithTimeIntervalSince1970:0]httpParameterString]

    
    
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   // CLog(@"%@",encodeUrlStr);//402851814e20d2d9014e20d2e9180031
    [self POST:encodeUrlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
    

}
- (void)doSubmitAnswerPatrolPlanWithID:(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:kGTOHTTP_SubmitPatrolAnswer] stringByAppendingFormat:@"/%@", planID];
//    NSLog(@"%@",urlStr);

    [self POST:urlStr
    parameters:dictParametes
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}
- (void)p_getListWithData:(id)data
               httpAction:(ICRHTTPAction )httpAction
                  success:(void (^)(id))succ
                  failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    NSDictionary *dict = data;
    NSString *urlStr = [[self class] UrlForPluginHTTPAction:httpAction];
    
    [self POST:urlStr
    parameters:dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}
//列表明细获取
- (void)p_getEntityItemsWithURL: (NSString *)urlStr
                        success:(void (^)(id))succ
                        failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];


}
- (void)p_doPostActionWithEncodeURL: (NSString *)encodeUrlStr
                               data:(id)data
                  success:(void (^)(id))succ
                  failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };

    if (data ) {
        NSDictionary *dict = (NSDictionary *)data;
        [self POST:encodeUrlStr
        parameters:dict
         needToken:NO
    acceptTypeJson:YES
           success:success
           failure:failure];
    } else {
        [self POST:encodeUrlStr
        parameters:nil
         needToken:NO
    acceptTypeJson:YES
           success:success
           failure:failure];
    }
    
}
//4.1获取报修单列表（读）
- (void)getRepairListWithData:(id)data
                      success:(void (^)(id))succ
                      failure:(void (^)(id))fail {
    [self p_getListWithData:data httpAction:kGTOHTTP_RepairQuery success:succ failure:fail];
}
//4.2 报修单明细（读）
- (void)getRepairItemsWithRepairUuid:(NSString *)repairUuid
                             success:(void (^)(id))succ
                             failure:(void (^)(id))fail {
     NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_RepairItems] stringByAppendingFormat:@"/%@",repairUuid];
    [self p_getEntityItemsWithURL:urlStr success:succ failure:fail];
}
//4.3 结束报修单（写））
- (void)dorepairApplicationWithRepairUuid:(NSString *)repairUuid
                                  version: (NSInteger)version
                                  success:(void (^)(id))succ
                                  failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_RepairApplication] stringByAppendingFormat:@"/%@?version=%ld&time=%@&operId=%@&operName=%@",repairUuid,version,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}
//4.4 结束报修单（写））
- (void)dorepairFinishWithRepairUuid:(NSString *)repairUuid
                             version: (NSInteger)version
                        attachmentId: (NSString *)attachmentId
                             success:(void (^)(id))succ
                             failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_RepairFinish] stringByAppendingFormat:@"/%@?version=%ld&attachmentId=%@&time=%@&operId=%@&operName=%@",repairUuid,version,attachmentId,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}

//5.1 保存许可证（写）
- (void)doSaveLicenceResultWithData:(id)data
                            success:(void (^)(id))succ
                            failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction: kGTOHTTP_LicenceSaveResult]
                        stringByAppendingFormat:@"?time=%@&operId=%@&operName=%@",
                        [[NSDate date]httpParameterString] ,
                        userU.f_user_code,userU.f_user_name];
    
    //add this line of code in order to avoid invalid parameter url string
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:data success:succ failure:fail];
}
//5.2 提交许可证（写）
- (void)doSubmitLicenceResultWithData:(id)data
                              success:(void (^)(id))succ
                              failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction: kGTOHTTP_LicenceSubmitResult]
                        stringByAppendingFormat:@"?time=%@&operId=%@&operName=%@",
                        [[NSDate date]httpParameterString] ,
                        userU.f_user_code,userU.f_user_name];
    
    //add this line of code in order to avoid invalid parameter url string
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:data success:succ failure:fail];
}
//5.3 获取许可证列表（读）
- (void)getLicenceListWithData:(id)data
                       success:(void (^)(id))succ
                       failure:(void (^)(id))fail {
    [self p_getListWithData:data httpAction:kGTOHTTP_LicenceQuery success:succ failure:fail];
}
//5.4 许可证明细（读）
- (void)getLicenceItemsWithLicenceUuid:(NSString *)licenceUuid
                                  success:(void (^)(id))succ
                                  failure:(void (^)(id))fail {
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceItems] stringByAppendingFormat:@"/%@?fetch_parts=items",licenceUuid];
    [self p_getEntityItemsWithURL:urlStr success:succ failure:fail];

}

//5.5删除许可证（写）
- (void)doLicenceRemoveWithLicenceUuid:(NSString *)licenceUuid
                               version: (NSInteger)version
                               success:(void (^)(id))succ
                               failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceRemove] stringByAppendingFormat:@"/%@?version=%ld&time=%@&operId=%@&operName=%@",licenceUuid,version,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}
//5.6审批拒绝许可证（写）
- (void)doLicenceRejectWithLicenceUuid:(NSString *)licenceUuid
                               version: (NSInteger)version
                          rejectCausen: (NSString *)cause
                               success:(void (^)(id))succ
                               failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceReject] stringByAppendingFormat:@"/%@?version=%ld&cause=%@&time=%@&operId=%@&operName=%@",licenceUuid,version,cause,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}
//5.7 审批通过许可证（写）
- (void)doLicenceApproveWithLicenceUuid:(NSString *)licenceUuid
                                version: (NSInteger)version
                                success:(void (^)(id))succ
                                failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceApprove] stringByAppendingFormat:@"/%@?version=%ld&time=%@&operId=%@&operName=%@",licenceUuid,version,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}

// 申请审批许可证（写）
- (void)doLicenceAskForApproveWithLicenceUuid:(NSString *)licenceUuid
                                version: (NSInteger)version
                                success:(void (^)(id))succ
                                failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceAskForApprove] stringByAppendingFormat:@"/%@?version=%ld&time=%@&operId=%@&operName=%@",licenceUuid,version,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}

- (void)doLicenceAskForCloseWithLicenceUuid:(NSString *)licenceUuid
                                      version: (NSInteger)version
                                      success:(void (^)(id))succ
                                      failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceClose] stringByAppendingFormat:@"/%@?version=%ld&time=%@&operId=%@&operName=%@",licenceUuid,version,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self p_doPostActionWithEncodeURL:encodeUrlStr data:nil success:succ failure:fail];
}


//5.8许可证操作日志列表（读）
- (void)getLicenceGet_logsWithLicenceUuid:(NSString *)licenceUuid
                                  success:(void (^)(id))succ
                                  failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_LicenceGetLogs] stringByAppendingFormat:@"/%@",licenceUuid];
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
    

}

//6.1 保存拓站（写）
- (void)doSavePioneeringResultWithData:(id)data
                               success:(void (^)(id))succ
                               failure:(void (^)(id))fail;
{
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        [IBTLoadingView hideHUDWithText:nil];
//        CLog(@"%@", responseObject);
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        [IBTLoadingView hideHUDWithText:nil];
//        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    NSDictionary *dict = data;
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction: kGTOHTTP_PioneeringSaveResult]
                        stringByAppendingFormat:@"?time=%@&operId=%@&operName=%@",
                        [[NSDate date]httpParameterString] ,
                        userU.f_user_code,userU.f_user_name];
    
    //add this line of code in order to avoid invalid parameter url string
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters: dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

//6.2提交拓站（写）
- (void)doSubmitPioneeringResultWithData:(id)data
                                 success:(void (^)(id))succ
                                 failure:(void (^)(id))fail {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
         [IBTLoadingView hideHUDWithText:nil];
//        CLog(@"%@", responseObject);
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        [IBTLoadingView hideHUDWithText:nil];
//        CLog(@"%@", error);
        if (fail) {
            fail( error );
        }
    };
    NSDictionary *dict = data;

    NSString *urlStr = [[[self class] UrlForPluginHTTPAction: kGTOHTTP_PioneeringSubmitResult]
                        stringByAppendingFormat:@"?time=%@&operId=%@&operName=%@",
                        [[NSDate date]httpParameterString] ,
                        userU.f_user_code,userU.f_user_name];

    //add this line of code in order to avoid invalid parameter url string
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters: dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}



//6.3 获取拓站列表（读）在线更新，不需要存本地
- (void)getPioneeringListWithData:(id)data
                          success:(void (^)(id))succ
                          failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
     
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
         [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    NSDictionary *dict = data;
    NSString *urlStr = [[self class] UrlForPluginHTTPAction:kGTOHTTP_PioneeringQuery];

    [self POST:urlStr
    parameters:dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

//6.4 拓站明细（读）
- (void)getPioneeringItemsWithPioneeringUuid:(NSString *)pioneeringUuid
                                     success:(void (^)(id))succ
                                     failure:(void (^)(id))fail
{
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
 
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_PioneeringItems] stringByAppendingFormat:@"/%@?fetch_parts=items",pioneeringUuid];
    
    [self GET:urlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}
//6.5 删除拓站（写）
- (void)doPioneeringRemoveWithPioneeringUuid:(NSString *)pioneeringUuid
                                     version: (NSInteger)version
                                     success:(void (^)(id))succ
                                     failure:(void (^)(id))fail {
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_PioneeringRemove] stringByAppendingFormat:@"/%@?version=%ld&time=%@&operId=%@&operName=%@",pioneeringUuid,version,[[NSDate date] httpParameterString],userU.f_user_code,userU.f_user_name];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}

// 上传附件
- (void)doAttachmentUploadWithData:(id)data
                            success:(void (^)(id))succ
                            failure:(void (^)(id))fail {
    
   
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    NSDictionary *dict = data;
     NSString *urlStr = [[self class] UrlForPluginHTTPAction: kGTOHTTP_AttachmentUpload];
    
    [self POST:urlStr
    parameters:dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

//// 上传多个附件
//- (void)doAttachmentUploadByFile:(NSString*)entity_uuid type:(NSString*)entity_type dicArray: (id)data
//                           success:(void (^)(id))succ
//                           failure:(void (^)(id))fail {
//    
//    
//    //    NSString *urlStr = [[self class] UrlForPluginHTTPAction: kGTOHTTP_AttachmentUpload];
//    //
//    //
//    //    //add this line of code in order to avoid invalid parameter url string
//    //    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    //    [self p_doPostActionWithEncodeURL:urlStr data:data success:succ failure:fail];
//    
//    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
//        [IBTLoadingView  hideHUDWithText:nil];
//        if (succ) {
//            succ( responseObject );
//            
//        }
//    };
//    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
//        [IBTLoadingView  hideHUDWithText:nil];
//        if (fail) {
//            fail( error );
//        }
//    };
////    NSDictionary *dict = data;
//    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_AttachmentUploadByFile] stringByAppendingFormat:@"?entity_type=%@&entity_uuid=%@",entity_type ,entity_uuid] ;
//    [self POST:urlStr
//    parameters:data
//     needToken:NO
//acceptTypeJson:YES
//       success:success
//       failure:failure];
//}


///7.6 取得附件列表路径
- (void)getAttachmentUrlsWithEntityType:(NSString *)entityType
                          andEntityUuid:(NSString *)entityUuid
                                     success:(void (^)(id))succ
                                     failure:(void (^)(id))fail
{
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
        [IBTLoadingView  hideHUDWithText:nil];
        if (succ) {
            succ( responseObject );
            
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);
        [IBTLoadingView  hideHUDWithText:nil];
        if (fail) {
            fail( error );
        }
    };
    
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_AttachmentGetUrls] stringByAppendingFormat:@"?entity_type=%@&entity_uuid=%@",entityType,entityUuid];
    
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}


//// 上传多个附件
- (void)multiPartUploadWithEntityType:(NSString *)entityType
                           entityUuid:(NSString *)entityUuid
                 arrayPostAttachments: (NSArray *)array
                              success:(void (^)(id))succ
                              failure:(void (^)(id))fail{
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//    
//    // Set some text to show the initial status.
//    hud.labelText = @"图片上传中…";
    // Will look best, if we set a minimum size.
//    hud.minSize = CGSizeMake(150.f, 100.f);
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_AttachmentUploadByFile] stringByAppendingFormat:@"?entity_type=%@&entity_uuid=%@",entityType,entityUuid];
//    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        for(ICRPostAttachment *attachment in array) {
//            [formData appendPartWithFileURL:[NSURL fileURLWithPath:attachment.filePath] name:@"file" fileName:attachment.fileName mimeType:@"image/jpeg" error:nil];
//        }
//        
//    } error:nil];
    
    [[AFHTTPSessionManager manager] POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        for(ICRPostAttachment *attachment in array) {
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:attachment.filePath] name:@"file" fileName:attachment.fileName mimeType:@"image/jpeg" error:nil];
        }
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        succ(responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        fail(error);
    }];
    
    
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//    
//    NSProgress *progress = nil;
//    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
////        [hud removeFromSuperview];
//        if (error) {
//            [IBTLoadingView hideHUDWithText:nil];
//            NSLog(@"Error: %@", error);
//            fail(error);
//        } else {
//            [IBTLoadingView hideHUDWithText:nil];
//            NSLog(@"%@ %@", response, responseObject);
//            succ(responseObject);
//        }
//    }];
//    [uploadTask resume];
    //监视进度条变化 progress的fractionCompleted属性就是当前的进度
//    [progress addObserver:self
//               forKeyPath:@"fractionCompleted"
//                  options:NSKeyValueObservingOptionNew
//                  context:NULL];
}

#pragma mark - 拿到文件上传进度
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
//    //拿到进度
//    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
//        NSProgress *progress = (NSProgress *)object;
//        NSLog(@"Progress is %f", progress.fractionCompleted);
//        MBProgressHUD *hud = [MBProgressHUD HUDForView:[UIApplication sharedApplication].keyWindow];
//        hud.mode = MBProgressHUDModeDeterminate;
//        hud.progress = progress.fractionCompleted;
//        
//        if (progress.fractionCompleted == 1) {
//            [hud removeFromSuperview];
//            [progress removeObserver:self forKeyPath:@"fractionCompleted"];
//        }
//    }else{
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
//    
//}


//// 上传多个附件： 带有删除的图片
- (void)multiPartUploadWithEntityType:(NSString *)entityType
                           entityUuid:(NSString *)entityUuid
                          deleteUuids: (NSString *)delUuids
                 arrayPostAttachments: (NSArray *)array
                              success:(void (^)(id))succ
                              failure:(void (^)(id))fail{
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_AttachmentUploadByFile] stringByAppendingFormat:@"?entity_type=%@&entity_uuid=%@&uuids=%@",entityType,entityUuid,delUuids];
        NSDictionary *dict = @{@"uuids":delUuids};

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        for(ICRPostAttachment *attachment in array) {
            if (attachment.is_localPhoto) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:attachment.filePath] name:@"file" fileName:attachment.fileName mimeType:@"image/jpeg" error:nil];
            } else {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:attachment.fileUrl] name:@"file" fileName:attachment.fileName mimeType:@"image/jpeg" error:nil];
            }
        }
        
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            [IBTLoadingView hideHUDWithText:nil];
            NSLog(@"Error: %@", error);
            fail(error);
        } else {
            [IBTLoadingView hideHUDWithText:nil];
            NSLog(@"%@ %@", response, responseObject);
            succ(responseObject);
        }
    }];
    
    [uploadTask resume];

//    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:kGTOHTTP_AttachmentUploadByFile] stringByAppendingFormat:@"?entity_type=%@&entity_uuid=%@&uuids=%@",entityType,entityUuid,delUuids];
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept" ];
//    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type" ];
//    [manager POST:urlStr parameters:nil success:success failure:failure];
    
//    NSDictionary *dict = @{@"uuids":delUuids};
//    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"%@",encodeUrlStr);
//    [self POST:encodeUrlStr
//    parameters:dict
//     needToken:NO
//acceptTypeJson:YES
//       success:success
//       failure:failure];
}


//删除附件
- (void)deleteAttachments: (NSString *)delStr
                  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 );
        }
    };
    
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kGTOHTTP_AttachmentDel] stringByAppendingFormat:@"?uuids=%@",delStr];
    [self POST:urlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}




//公告管理

//	下载附件，直接下载方式
+ (NSString *)AttachmentUrlWithID:(id)attachmentID {
    
    if (!attachmentID) {
        return nil;
    }
    
    return [[[self class] UrlForPluginHTTPAction:kICRHTTP_AttachmentDownloadDirect]stringByAppendingFormat:@"/%@",attachmentID];
}

// Board
/* 公告列表（读）
 获得公告列表
 */
#pragma mark - Board
- (void)doGetBoardListWithType:(ICRAnnouncementReadType)eType
                            pageNumber:(NSUInteger)page_number
                                pageSize:(NSUInteger)page_size
                             success:(void (^)(id data))succ
                             failure:(void (^)(id data))fail
{
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
//        CLog(@"%@", responseObject);
//        NSArray *arr = responseObject[ @"data" ][ @"records" ];
        if (IsDictObject(responseObject)) {
                if (succ) succ( responseObject );
        }
        else {
            if (fail) {
                fail( nil );
            }
        }
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
//        CLog(@"%@", error);

//        if (fail) {
//            fail( error );
//        }
    };

    NSString *typeStr;
    if (eType) {
        typeStr = @"true";
    } else {
        typeStr = @"false";
    }
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_BoardQuery]
                        stringByAppendingFormat:@"/%@?read=%@&page_number=%@&page_size=%@",[[ICRUserUtil sharedInstance] f_user_uuid],typeStr,@(page_number),@(page_size)];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",encodeUrlStr);
    [self POST:encodeUrlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}

/* 读取公告（读）
 读取单个公告
 */
- (void)doGetBoardWithID:(NSString *)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 );
        }
    };
    
    //    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_FetchBoard] stringByAppendingFormat:@"/%@", boardID];
    NSLog(@"%@",urlStr);
    [self GET:urlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}

/* 提交公告已读状态（写）*/
- (void)doReadBoardWithID:(NSString *)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];
    NSString *urlStr = [[[self class] UrlForPluginHTTPAction:kICRHTTP_ReadBoard] stringByAppendingFormat:@"/%@?user_uuid=%@&read_time=%@",boardID,[[ICRUserUtil sharedInstance] f_user_uuid], [[NSDate date] httpParameterString]];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self POST:encodeUrlStr
    parameters:nil
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];
}

//版本更新
- (void)getVeisionIdWithType:(NSString *)type
                     success:(void (^)(id))succ
                     failure:(void (^)(id))fail
{
    
    if (!type) {
        if (fail) {
            fail( [[self class] ErrorWithMsg:ERROR_PARAMETER code:0] );
        }
        return;
    }
    
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        if (succ) {
            succ( responseObject );
        }
    };
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        if (fail) {
            fail( error );
        }
    };
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@?type=%@",HTTP_REST_API_BASE_URL,ICRHTTPInterface[XFFHttp_getVersionId],type];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self GET:encodeUrlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
    
}
//8.1 获取当前位置附近的油站(读)
- (void)getNearStoreWithLongitude:(NSString *)longitude
                      andLatitude: (NSString *)latitude
                          success:(void (^)(id))succ
                          failure:(void (^)(id))fail {
    if (!longitude || !latitude) {
        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 );
            }
        };
    
    NSTimeInterval nowInterl = [[NSDate date]timeIntervalSince1970];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@/?longitude=%@&latitude=%@",HTTP_REST_API_BASE_URL,ICRHTTPInterface[kGTOHTTP_nearStore],longitude,latitude];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self GET:encodeUrlStr
   parameters:nil
    needToken:NO
acceptTypeJson:YES
      success:success
      failure:failure];
}
//9.1	签到
- (void)getSignInIdWithDictionary:(NSDictionary *)dict
                     success:(void (^)(id))succ
                     failure:(void (^)(id))fail
{
    
    if (!dict) {
        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 = [NSString stringWithFormat:@"%@/%@",HTTP_REST_API_BASE_URL,ICRHTTPInterface[XFFHttp_getSignin]];
    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self POST:encodeUrlStr
    parameters:dict
     needToken:NO
acceptTypeJson:YES
       success:success
       failure:failure];

}
//	天气
- (void)getWeatherInfoWithCityName:(NSString *)cityName
                           success:(void (^)(id))succ
                           failure:(void (^)(id))fail {
    if (!cityName) {
        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 );
//        }
//    };
    
//    NSDate *nowDate = [NSDate date];
//    NSTimeInterval  nowInterl = [nowDate timeIntervalSince1970];
//    NSString *urlStr = [NSString stringWithFormat:@"%@%@.html",HTTP_WEATHER_URL,cityCode];
////    NSString *encodeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
////    [self GET:urlStr parameters:nil needToken:NO acceptTypeJson:YES success:success failure:failure];
//    
//    
//    NSURL *URL = [NSURL URLWithString:urlStr];
//    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    op.responseSerializer = [AFJSONResponseSerializer serializer];
//    op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",nil];
//    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"JSON: %@", responseObject);
//        if (succ) {
//            succ( responseObject );
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"Error: %@", error);
//        if (fail) {
//            fail( error );
//        }
//    }];
//    [[NSOperationQueue mainQueue] addOperation:op];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"f92286d16c5ba938b364a6c7389096a8" forHTTPHeaderField:@"apikey"];
    NSDictionary *parameters = @{@"city":[self removeLastOneChar:cityName]};
    [manager GET:HTTP_WEATHER_URL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        if (succ) {
            succ( responseObject );
        }
        //NSLog(@"d");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        if (fail) {
            fail( error );
        }
    }];
}

//去掉字符串最后一个字符
- (NSString*) removeLastOneChar:(NSString*)origin
{
    NSString* cutted;
    if([origin length] > 0){
        cutted = [origin substringToIndex:([origin length]-1)];// 去掉最后一个","
    }else{
        cutted = origin;
    }
    return cutted;
}

@end
