//
//  RDSDemoApiHelper.m
//  singleProduct
//
//  Created by coderYK on 2018/4/28.
//  Copyright © 2018年 RDIOT. All rights reserved.
//

#import "RDSDemoApiHelper.h"
#import <AFNetworking.h>
#import "NSDictionary+WiFiInfo.h"
#import "NSString+convert.h"
#import "NSDate+currentDate.h"
#import "NSMutableDictionary+addObj.h"


/**定义请求成功的block*/
typedef void(^requestSuccess)( NSDictionary * responseObject);
/**定义请求失败的block*/
typedef void(^requestFailure)( NSError *error);
/**定义上传进度block*/
typedef void(^uploadProgress)(float progress);
/**定义下载进度block*/
typedef void(^downloadProgress)(float progress);

@interface RDSDemoApiHelper ()

@property (nonatomic, weak) AFHTTPSessionManager *netManager;
@property (nonatomic, strong) NSDateFormatter *formatter;
@property (nonatomic, strong) NSString *appHeader;
@end

@implementation RDSDemoApiHelper

DEF_SINGLETON(RDSDemoApiHelper)

- (NSDateFormatter *)formatter {
    if (_formatter == nil) {
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"yyyyMMddHHmmss";
    }
    return _formatter;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.netManager = [AFHTTPSessionManager manager];
        //        self.netManager.requestSerializer = [AFJSONRequestSerializer serializer];
        //        self.netManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [self.netManager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html", nil]];
        
        [self netWorkStart];
        
        // 默认生产环境
        self.baseUrlHost = kBaseUrlHost;
        self.baseUrlHeadImg = kBaseUrlHeadImg;
        self.isTest = 0;
        
        self.isTest = @(TheDataManager.isTest).integerValue;
    }
    return self;
}

- (void)netWorkStart{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                DDLog(@"网络状态：未知网络");
                self.netWorkState = @"未知网络";
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                DDLog(@"网络状态：没有联网");
                self.netWorkState = @"没有联网";
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                DDLog(@"网络状态：蜂窝数据");
                self.netWorkState = @"蜂窝数据";
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                DDLog(@"网络状态：WIFI %@",[NSDictionary rds_fetchSSIDInfo][@"SSID"]);
                self.netWorkState = @"WIFI";
                break;
        }
    }];
    
    // 3.开始监控
    [manager startMonitoring];
    
}

- (NSString *)netWorkState{
    if (_netWorkState == nil) {
        _netWorkState = @"";
    }
    return _netWorkState;
}

// 设置生产、测试环境
- (void)setIsTest:(NSInteger)isTest{
    _isTest = isTest;
    
    if(isTest == 1){
        _baseUrlHost = kBaseUrlHost_test;
        _baseUrlHeadImg = kBaseUrlHeadImg_test;
    }else{
        _baseUrlHost = kBaseUrlHost;
        _baseUrlHeadImg = kBaseUrlHeadImg;
    }
}



+ (void)rds_appVersionCheckSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *param = @{
        @"version" : currentVersion,
        @"platform" : @"IOS",// 平台
    };
    NSDictionary *header = @{
        @"X-YX-APP":TheApiHelper.appHeader
    };
    [RDSDemoApiHelper postWithUrlString:@"check_version"
                              paraments:param
                                headers:header
                                success:success
                                   fail:failure
                               progress:nil];
}

+ (void)rds_appInitSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *header = @{
        @"X-YX-APP":TheApiHelper.appHeader
    };
    [RDSDemoApiHelper postWithUrlString:@"init"
                              paraments:nil
                                headers:header
                                success:success
                                   fail:failure
                               progress:nil];
}

#pragma mark - 注册登录

+ (void)rds_getVerifyCodePhone:(NSString *)phone type:(int)type success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"tel" : phone,
        @"bzty" : @(type),
        @"resend_limit"  : @60, // 重发限制时间（秒数，默认60秒）
        @"expired"  : @9999999,     // 失效时间（秒数，默认5分钟）
    };
    NSDictionary *header = @{
        @"X-YX-APP":TheApiHelper.appHeader
    };
    [RDSDemoApiHelper postWithUrlString:@"login/code"
                              paraments:param
                                headers:header
                                success:success
                                   fail:failure
                               progress:nil];
}


+ (void)rds_loginWithVerifyCodePhone:(NSString *)phone code:(NSString *)code success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"phone" : phone,
        @"code" : code,
    };
    NSDictionary *hearder = @{
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"login/sms"
                              paraments:param
                                headers:hearder
                                success:success
                                   fail:failure
                               progress:nil];
}


+ (void)rds_loginWithPwdPhone:(NSString *)phone password:(NSString *)password success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"phone" : phone,
        @"password" : password,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"login/password"
                              paraments:param
                                headers:hearder
                                success:success
                                   fail:failure
                               progress:nil];
}


+ (void)rds_setPassword:(NSString *)password success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    // token参数前面加Bearer+空格
    
    NSDictionary *param = @{
        @"password" : password,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper putWithUrlString:@"login/set_password"
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
    
}


+ (void)rds_resetPwdPhone:(NSString *)phone password:(NSString *)password code:(NSString *)code success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"phone" : phone,
        @"new_password" : password,
        @"code" : code,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper putWithUrlString:@"login/update_pass"
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_refreshTokenSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper putWithUrlString:@"login/refresh/token"
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}


+ (void)rds_logoutSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"login/exit"
                              paraments:nil
                                headers:hearder
                                success:success
                                   fail:failure
                               progress:nil];
}

+ (void)rds_unsubscribeSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper patWithUrlString:@"login/unsubscribe"
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_getWeatherSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    

    NSDictionary *param = @{
        @"home_id" : TheDataManager.currentUser.default_home_id,
    };
    
    [RDSDemoApiHelper getWithUrlString:@"homepages/weather"
                             paraments:param
                               headers:nil
                               success:success
                                  fail:failure
                              progress:nil];
}

#pragma mark - 用户信息
+ (void)rds_getCurrentUserInfoSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper getWithUrlString:@"users/current"
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
    
}

+ (void)rds_postImage:(UIImage *)image success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    

    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSDictionary *param = @{
        @"file" : @"list",
    };
    
    [RDSDemoApiHelper postImage:image
                      urlString:@"files"
                      paraments:nil
                        headers:hearder
                        success:success
                           fail:failure
                       progress:nil];
}

+ (void)rds_updateUserInfoChangeUserName:(NSString *)userName photoUrl:(NSString *)photoUrl defaultHomeId:(NSString *)homeId isSetPwd:(BOOL)isSetPwd success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if(userName){
        param.rds_addObj(@"user_name",userName);
    }
    if(photoUrl){
        param.rds_addObj(@"photo",photoUrl);
    }
    if(homeId){
        param.rds_addObj(@"default_home_id",homeId);
    }
    if(isSetPwd){
        param.rds_addObj(@"set_password",@(isSetPwd));
    }
    
    NSDictionary *hearder = @{
        @"id" : TheDataManager.currentUser.record_id,
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"users/%@",TheDataManager.currentUser.record_id];
    [RDSDemoApiHelper putWithUrlString:url
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_getDefaultHomeSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper getWithUrlString:@"homes/default"
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_getHomeListIsAdmin:(BOOL)is_admin success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"q" : @"list",
        @"is_admin" : @(is_admin),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper getWithUrlString:@"homes"
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}


+ (void)rds_getHomeDetailWithHomeId:(NSString *)homeId success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    

    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"homes/%@",homeId];
    [RDSDemoApiHelper getWithUrlString:url
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}


+ (void)rds_setDefaultHome:(NSString *)home_id success:(void (^)(id))success failure:(void (^)(NSError *))failure{

    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"family_members/default/%@",home_id];
    [RDSDemoApiHelper putWithUrlString:url
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_updateHomeInfoWithHomeId:(NSString *)record_id name:(NSString *)name city:(NSString *)city success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if(record_id){
        param.rds_addObj(@"record_id",record_id);
    }
    if(name){
        param.rds_addObj(@"name",name);
    }
    if(city){
        param.rds_addObj(@"city",city);
    }
    
    
    NSDictionary *hearder = @{
        @"id" : TheDataManager.currentUser.record_id,
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"homes/%@",record_id];
    [RDSDemoApiHelper putWithUrlString:url
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}


+ (void)rds_addMemberWithHomeId:(NSString *)home_id phone:(NSString *)phone success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"phone" : phone,
        @"home_id" : home_id,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"family_members/invite"
                              paraments:param
                                headers:hearder
                                success:success
                                   fail:failure
                               progress:nil];
}

+ (void)rds_delMemberWithHomeId:(NSString *)home_id user_id:(NSString *)user_id success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"user_id" : user_id,
        @"home_id" : home_id,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper deleteWithUrlString:@"family_members"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_addHomeWithName:(NSString *)name isDefault:(BOOL)is_default city:(NSString *)city success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param.rds_addObj(@"name",name);
    param.rds_addObj(@"user_id",TheDataManager.currentUser.record_id);
    param.rds_addObj(@"is_default",@(is_default));
    
    if(city){
        param.rds_addObj(@"city",city);
    }

    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"homes"
                              paraments:param
                                headers:hearder
                                success:success
                                   fail:failure
                               progress:nil];
}

+ (void)rds_delHomeWithHomeId:(NSString *)home_id success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"homes/%@",home_id];
    [RDSDemoApiHelper deleteWithUrlString:url
                                paraments:nil
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}
#pragma mark - 房间管理
+ (void)rds_getRoomListSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    
    NSDictionary *param = @{
        @"q" : @"list",
        @"home_id" : TheDataManager.current_home_id,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper getWithUrlString:@"rooms"
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_getDeviceTypeListSuccess:(void (^)(id))success failure:(void (^)(NSError *))failure {
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper getWithUrlString:@"device_types"
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_addRoomName:(NSString *)name control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"name" : name,
        @"control_number" : control_number,
        @"home_id" : TheDataManager.current_home_id,
        //@"is_master" : @2,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"rooms"
                              paraments:param
                                headers:hearder
                                success:success
                                   fail:failure
                               progress:nil];
}


+ (void)rds_deleteRoomsRecord_ids:(NSArray *)record_ids success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"record_ids" : record_ids,
        @"home_id" : TheDataManager.current_home_id,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper deleteWithUrlString:@"rooms"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_updateRoomName:(NSString *)name record_id:(NSString *)record_id home_id:(NSString *)home_id success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"name" : name,
        @"home_id" : home_id,
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"rooms/%@",record_id];
    [RDSDemoApiHelper putWithUrlString:url
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

+ (void)rds_getRoomDetailRecord_id:(NSString *)record_id success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    NSDictionary *hearder = @{
        @"id" : TheDataManager.currentUser.record_id,
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    NSString *url = [NSString stringWithFormat:@"rooms/%@",record_id];
    [RDSDemoApiHelper getWithUrlString:url
                             paraments:nil
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}


+ (void)rds_getRoomStatusWithControl_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
    };
    
    [RDSDemoApiHelper getWithUrlString:@"rooms/status"
                             paraments:param
                               headers:hearder
                               success:success
                                  fail:failure
                              progress:nil];
}

#pragma mark - 设备控制

+ (void)rds_setTemp:(int)temp control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"temp" : @(temp),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/temp"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_setMode:(int)mode control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"mode" : @(mode),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/mode"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_setSpeed:(int)speed control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"speed" : @(speed),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/speed"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_setTimer:(NSNumber *)timer onOff:(BOOL)onOff control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"timer" : timer,
        @"timer_status" : @(onOff),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/timer"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_setPower:(int)power control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"power" : @(power),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/power"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_setNewFanPower:(int)power control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"power" : @(power),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/new_fan"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}

+ (void)rds_setSubDevPower:(int)power control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"power" : @(power),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/fan_power"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}


+ (void)rds_setSubDevSpeed:(int)speed control_number:(NSString *)control_number success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    NSDictionary *param = @{
        @"gateway" : TheDataManager.gateway,
        @"control_number" : control_number,
        @"fan_value" : @(speed),
    };
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        @"X-YX-APP": TheApiHelper.appHeader
    };
    
    [RDSDemoApiHelper postWithUrlString:@"control/fan_value"
                                paraments:param
                                  headers:hearder
                                  success:success
                                     fail:failure
                                 progress:nil];
}


- (NSString *)appHeader{
    
    UIDevice *device = [UIDevice currentDevice];
    NSDictionary *dicInfo = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [dicInfo objectForKey:@"CFBundleShortVersionString"];
    
    NSDictionary *app = @{
        @"screen_width": @(SCREEN_WIDTH),
        @"device_id": @"demoString",
        @"os": @"iOS",
        @"net_type": @"demoString",
        @"os_version": device.systemVersion,
        @"channel": @"iOS",
        @"device_type": @"iPhone",
        @"phone_brand": @"Apple",
        @"source": @"App Store",
        @"version": appVersion,
        @"uuid": @"demoString",
        @"phone_model": @"demoString",
        @"screen_height": @(SCREEN_HEIGHT),
        @"user_type": @"demoString",
        @"user_id": TheDataManager.currentUser.record_id,
        @"mqtt_token": @"demoString",
        @"location": @"demoString",
        @"timestamp": [NSDate rds_getTimestamp:[NSDate date]],
    };
    
    NSString *appString = [NSString rds_dicToJson:app];
    
    return appString;
}

#pragma mark - post

+ (void)postWithUrlString:(NSString *)urlString paraments:(id)params headers:(id)header success:(requestSuccess)successBlock fail:(requestFailure)failBlock progress:(downloadProgress)progress{
    
    NSString *reqUrl = [NSString stringWithFormat:@"%@/%@", TheApiHelper.baseUrlHost, urlString];
    DDLog(@"req URL: %@", reqUrl);
    DDLog(@"req para:%@",params);
    
    NSDate *d1 = [NSDate date];
    
    NSDictionary *dic = params;
    NSString *str = @"";
    if (dic && [dic isKindOfClass:[NSDictionary class]]) {
        str = [NSString rds_dicToJson:dic];
    }else{
        str = @"格式错误！";
    }
    
    
    [[RDSDemoApiHelper sharedInstance].netManager POST:reqUrl parameters:params headers:header progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (progress) {
            progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *str = @"";
        if (dic && [dic isKindOfClass:[NSDictionary class]]) {
            str = [NSString rds_dicToJson:dic];
        }else{
            str = @"格式错误！";
        }
        
        NSDate *d2 = [NSDate date];
        NSTimeInterval time = [d2 timeIntervalSinceDate:d1];
        //简单计算耗时
        
        DDLog(@"%@-Post请求耗时:%f秒 结果：%@", reqUrl, time, str);
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
        DDLog(@"%@-Error结果：%@",reqUrl, error);
    }];
}




#pragma mark - get

+ (void)getWithUrlString:(NSString *)urlString paraments:(id)params headers:(id)header success:(requestSuccess)successBlock fail:(requestFailure)failBlock progress:(downloadProgress)progress{
    
    NSString *reqUrl = [NSString stringWithFormat:@"%@/%@", TheApiHelper.baseUrlHost, urlString];
    DDLog(@"req URL: %@", reqUrl);
    DDLog(@"req para:%@",params);
    
    [[RDSDemoApiHelper sharedInstance].netManager GET:reqUrl parameters:params headers:header progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (progress) {
            progress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = responseObject;
        NSString *str = @"";
        if (dic && [dic isKindOfClass:[NSDictionary class]]) {
            str = [NSString rds_dicToJson:dic];
        }else{
            str = @"格式错误！";
        }
        
        DDLog(@"%@-Get请求结果：%@",reqUrl, str);
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failBlock) {
            failBlock(error);
        }
        DDLog(@"%@-Error结果：%@",reqUrl, error);
    }];
    

}

#pragma mark - put

+ (void)putWithUrlString:(NSString *)urlString paraments:(id)params headers:(id)header success:(requestSuccess)successBlock fail:(requestFailure)failBlock progress:(downloadProgress)progress{
    
    NSString *reqUrl = [NSString stringWithFormat:@"%@/%@", TheApiHelper.baseUrlHost, urlString];
    DDLog(@"req URL: %@", reqUrl);
    DDLog(@"req para:%@",params);
    
    [[RDSDemoApiHelper sharedInstance].netManager PUT:reqUrl parameters:params headers:header success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DDLog(@"%@-PUT请求结果：%@",reqUrl, responseObject);
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failBlock) {
            failBlock(error);
        }
        DDLog(@"%@-Error结果：%@",reqUrl, error);
    }];
    
}

#pragma mark - PAT

+ (void)patWithUrlString:(NSString *)urlString paraments:(id)params headers:(id)header success:(requestSuccess)successBlock fail:(requestFailure)failBlock progress:(downloadProgress)progress{
    
    NSString *reqUrl = [NSString stringWithFormat:@"%@/%@", TheApiHelper.baseUrlHost, urlString];
    DDLog(@"req URL:%@", reqUrl);
    DDLog(@"req para:%@",params);
    
    [[RDSDemoApiHelper sharedInstance].netManager PATCH:reqUrl parameters:params headers:header success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DDLog(@"%@-PATCH请求结果：%@",reqUrl, responseObject);
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
        DDLog(@"%@-Error结果：%@",reqUrl, error);
    }];
    
}


#pragma mark - DELETE

+ (void)deleteWithUrlString:(NSString *)urlString paraments:(id)params headers:(id)header success:(requestSuccess)successBlock fail:(requestFailure)failBlock progress:(downloadProgress)progress{
    
    NSString *reqUrl = [NSString stringWithFormat:@"%@/%@", TheApiHelper.baseUrlHost, urlString];
    DDLog(@"req URL: %@", reqUrl);
    DDLog(@"req para:%@",params);
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain", nil];
    
    // 设置请求头
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //[manager.requestSerializer setValue:api_key forHTTPHeaderField:@"api_key"];
    [manager DELETE:reqUrl parameters:params headers:header success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DDLog(@"%@-DELETE请求结果：%@",reqUrl, responseObject);
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failBlock) {
            failBlock(error);
        }
        DDLog(@"%@-Error结果：%@",reqUrl, error);
        
    }];
    
    
}

#pragma mark - 上传头像
- (NSURLSessionUploadTask *)rds_uploadTaskWithImage:(UIImage *)image completion:(void (^)(NSURLResponse *, id, NSError *))completionBlock{
    
    NSError *error = NULL;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/files",TheApiHelper.baseUrlHost];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    
    NSDictionary *hearder = @{
        @"Authorization" : TheDataManager.token,
        //@"X-YX-APP": TheApiHelper.appHeader
    };
    
    RDS_WEAKSELF(weakSelf)
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST"
                                                                    URLString:urlStr
                                                                   parameters:hearder
                                                    constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                                        
                                                        NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
                                                        NSString *str = [weakSelf.formatter stringFromDate:[NSDate date]];
                                                        NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
                                                        [formData appendPartWithFileData:imageData
                                                                                    name:@"image"
                                                                                fileName:fileName
                                                                                mimeType:@"image/jpg"];
                                                    } error:&error];
    // 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        [RDSHudShower showWithStatus:@"正在上传" autoDismiss:NO];
    } completionHandler:completionBlock];
    
    return uploadTask;
}

+ (void)postImage:(UIImage *)image urlString:(NSString *)urlString paraments:(id)params headers:(id)header success:(requestSuccess)successBlock fail:(requestFailure)failBlock progress:(downloadProgress)progress{
    
    NSString *reqUrl = [NSString stringWithFormat:@"%@/%@", TheApiHelper.baseUrlHost, urlString];
    DDLog(@"req URL: %@", reqUrl);
    DDLog(@"req para:%@",params);
    
    NSDate *d1 = [NSDate date];
    
    NSDictionary *dic = params;
    NSString *str = @"";
    if (dic && [dic isKindOfClass:[NSDictionary class]]) {
        str = [NSString rds_dicToJson:dic];
    }else{
        str = @"格式错误！";
    }
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    
    [[RDSDemoApiHelper sharedInstance].netManager POST:reqUrl parameters:nil headers:header constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
        [formData appendPartWithFileData:imageData
                                    name:@"file" //file为后台接收的字段或参数
                                fileName:fileName
                                mimeType:@"image/jpg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        NSString *str = @"";
        if (dic && [dic isKindOfClass:[NSDictionary class]]) {
            str = [NSString rds_dicToJson:dic];
        }else{
            str = @"格式错误！";
        }
        
        NSDate *d2 = [NSDate date];
        NSTimeInterval time = [d2 timeIntervalSinceDate:d1];
        //简单计算耗时
        
        DDLog(@"%@-Post请求耗时:%f秒 结果：%@", reqUrl, time, responseObject);
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
        DDLog(@"%@-Error结果：%@",reqUrl, error);
    }];
}
#pragma mark - 文件下载

/**
 *  文件下载
 *
 *  @param operations   文件下载预留参数---视具体情况而定 可移除
 *  @param savePath     下载文件保存路径
 *  @param urlString        请求的url
 *  @param successBlock 下载文件成功的回调
 *  @param failureBlock 下载文件失败的回调
 *  @param progress     下载文件的进度显示
 */

+(void)downLoadFileWithOperations:(NSDictionary *)operations withSavaPath:(NSString *)savePath withUrlString:(NSString *)urlString withSuccessBlock:(void (^)(id))successBlock withFailureBlock:(void (^)(NSError *))failureBlock withDownLoadProgress:(void (^)(float))progress{
    
    NSString* encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]] progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (progress) {
            progress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        }
        DDLog(@"下载进度:%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        [[NSFileManager defaultManager] moveItemAtURL:targetPath toURL:[NSURL fileURLWithPath:savePath] error:nil];
        
        if (successBlock) {
            successBlock(nil);
        }
        return  [NSURL URLWithString:savePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (error && failureBlock) {
            failureBlock(error);
        }
    }];
    
    //开启下载任务
    [downloadTask resume];
}
@end
