
//
//  HTTPDataProcession.m
//  Unity-iPhone
//
//  Created by leon on 2021/2/2.
//

#import "HTTPDataProcession.h"

@interface HTTPDataProcession ()<NSURLSessionDataDelegate>
@end

@implementation HTTPDataProcession

#pragma mark - 网络请求数据
+ (void)getHTTPDataProcession:(NSString*)urlString token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
    
    // 1.创建url
    // 请求一个网页
//    NSString *urlString = @"http://test-shoes-api.hiyd.com/forum/friends?limit=1000";
    // 一些特殊字符编码
    urlString =  [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    
    // 2.创建请求 并：设置缓存策略为每次都从网络加载 超时时间30秒
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    //2.创建一个 NSMutableURLRequest 添加 header
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:token forHTTPHeaderField:@"token"];
    [mutableRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //3.把值覆给request
    request = [mutableRequest copy];
    
    // 3.采用苹果提供的共享session
    NSURLSession *sharedSession = [NSURLSession sharedSession];

    // 4.由系统直接返回一个dataTask任务
    NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){

        if (data && (error == nil)){
      
            // 网络请求完成之后就会执行，NSURLSession自动实现多线程
            successBlock(data);
            
        } else {//
            // 网络访问失败
            for (NSString * key  in error.userInfo){
                
                if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
                    
                    id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1  error:nil];
                    
                    NSLog(@"错误信息 ERROR =========== >>> %@",error);
                    failBlock(errorObject);

                }
                
            }

        }
        
    }];
    // 5.每一个任务默认都是挂起的，需要调用 resume 方法
    [dataTask resume];
    
}

+ (void)postHTTPDataProcession:(NSString *)urlString  withParams:(NSDictionary *)params token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
    
      NSURL *url = [NSURL URLWithString:urlString];
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
      request.HTTPMethod = @"POST";
      request.timeoutInterval = 10.0f;
      
      NSString *keyValueBody = [self getKeyValueStringWithDictionary:params];
      request.HTTPBody = [keyValueBody dataUsingEncoding:NSUTF8StringEncoding];
    
      NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
      sessionConfiguration.HTTPAdditionalHeaders = @{@"Content-Type":@"application/x-www-form-urlencoded;charset=utf-8",@"token":token};
      
      NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
    
      NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
          
          if (data && (error == nil)){
        
              // 网络请求完成之后就会执行，NSURLSession自动实现多线程
              successBlock(data);
              
          }else{
              
              // 网络访问失败
              for (NSString * key  in error.userInfo){
                  
                  if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
                      
                      id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1  error:nil];
                                            
                      failBlock(errorObject);

                  }
                  
              }

          }
          
      }];
      
      //发送请求
      [dataTask resume];
        
}

//字典转json字符串
+(NSString*)getKeyValueStringWithDictionary:(NSDictionary*)dic{
    
    if (!dic||dic.count==0){
        return @"";
    }
    
    NSString *result = @"";
    NSArray *theAllKeys = [dic allKeys];
    for (int i=0; i<theAllKeys.count; i++){
        NSString *theKey = [theAllKeys objectAtIndex:i];
        NSString *theValue = [dic objectForKey:theKey];
        if (i==0){
            NSString *temp = [NSString stringWithFormat:@"%@=%@", theKey, theValue];
            result = [result stringByAppendingString:temp];
        }else {
            NSString *temp = [NSString stringWithFormat:@"&%@=%@", theKey, theValue];
            result = [result stringByAppendingString:temp];
        }
    }
    NSLog(@"json = %@",result);

    return result;
    
}


#pragma mark --------- request
+(void)getFriendsList:(UserFriendsDataBlock)userFriendsDataBlock{
    
    NSString *urlString =  [NSString stringWithFormat:@"%@&limit=%@&v=%@&os=%@",GAME_FRIENDS,@"1000",CFBundleVersion,OS];
    NSLog(@"urlString = %@",urlString);
    [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken]  success:^(id data){
            // 网络访问成功
//            NSLog(@"data=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            NSError * error;
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        
//                NSLog(@"gameFriends dictionary === %@ ",dictionary);

            if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
                
                int code = [dictionary[@"code"] intValue];

                if (code==0){//
                    
                    NSDictionary * dict = dictionary[@"data"];
                    NSArray * arr = dict[@"list"];
                    if (arr == nil || [arr isKindOfClass:[NSNull class]]) {
                        return;
                    }
                    
                    NSMutableArray * jsonArr = [NSMutableArray new];//存储数据

                    for (NSDictionary * object in arr){
                        
                        NSDictionary * socialInfo = object[@"socialInfo"];
                        UserFriendsModel * model = [UserFriendsModel new];
                        model.code = 0;
                        [model setValuesForKeysWithDictionary:socialInfo];
                        
    //                NSLog(@"model =========== >>> %d %@ %@ %d %@ %@",model.trans_id,model.nickname,model.city,model.gender,model.status,model.avatar);
                        
                        NSMutableDictionary * gameFriends = [NSMutableDictionary new];
                        
                        NSMutableDictionary * userInfo = [NSMutableDictionary new];
                        [userInfo setObject:[NSNumber numberWithInt:model.trans_id] forKey:@"id"];
                        [userInfo setValue:model.nickname forKey:@"nickname"];
                        [userInfo setObject:[NSNumber numberWithInt:model.gender] forKey:@"gender"];
                        [userInfo setValue:model.city forKey:@"city"];
                        [userInfo setValue:model.avatar forKey:@"avatar"];
                        
                        [gameFriends setValue:model.status forKey:@"status"];
                        [gameFriends setValue:userInfo forKey:@"user"];
                        [jsonArr addObject:gameFriends];
                        //                        NSLog(@"gameFriends =========== >>>%@",gameFriends);

                    }
                    
                    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArr options:NSJSONWritingPrettyPrinted error:nil];
                    
                    NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                    
//                    NSLog(@"GetUserFriends ==>> unity 请求好友列表  %@ ",jsonString);
                    
                    const char * cusChar =[jsonString UTF8String];
                    
                    userFriendsDataBlock(code,cusChar,jsonArr);
                    
                 }
                
              }
            
            }fail:^(id errorDes){
                                    
    }];
    
}

//邀请好友
+ (void)inviteFriends:(int)friendid inviteInfo:(NSString*)inviteInfo inviteDataBlock:(InviteDataBlock)inviteDataBlock{
    
    NSString * invite_user_id = [NSString stringWithFormat:@"%d",friendid];
    NSString *urlString = [NSString stringWithFormat:@"%@&invite_user_id=%@&invite=%@&game_id=%@",GAME_INVITE,invite_user_id,inviteInfo,[CacheTool getGameId]];
    NSLog(@"InviteFriend urlString ===>> %@",urlString);

    [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken]  success:^(id data){
        
            NSError * error;
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
//                NSLog(@"gameFriends dictionary === %@ ",dictionary);

        if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
                
                int code = [dictionary[@"code"] intValue];

                if (code==0){//
                    
                    inviteDataBlock(@"邀请成功");
                    
                 }
                
              }
        
            }fail:^(id errorDes){
                
    }];
    
}

//获取排行榜
+ (void)GetRank:(int)type rankDataBlock:(RankDataBlock)rankDataBlock{

    NSString * scoreType;
    if (type ==0){
        scoreType = @"world";
    }else{
        scoreType = @"friend";
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@&game_id=%@&scope=%@",GAME_RANK,[CacheTool getGameId],scoreType];

    NSLog(@"urlString == %@",urlString);
    
    [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken]  success:^(id data){

            NSError * error;
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        
//            NSLog(@"GetRank dictionary === %@ ",dictionary);
        
        if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){

                int code = [dictionary[@"code"] intValue];

                if (code==0){//

//                    NSLog(@"榜单数据 ====>> %@",dictionary);
                    
                    if (dictionary!=nil){
                        
                        int code = [dictionary[@"code"] intValue];

                        if (code==0){//
                            
                            NSDictionary * dict = dictionary[@"data"];
                            NSArray * arr = dict[@"records"];
                            if (arr == nil || [arr isKindOfClass:[NSNull class]]) {
                                return;
                            }
                            NSMutableArray * userArr = [NSMutableArray new];//存储数据
                            
                            NSMutableDictionary * list = [NSMutableDictionary new];

                            int rank_i = 0;
                            
                            for (NSDictionary * object in arr){
                                
                            rank_i++;
                                
                            RankModel * model = [RankModel new];
//                            model.code = 0;
                            [model setValuesForKeysWithDictionary:object];
                                                        
                            NSMutableDictionary * rank = [NSMutableDictionary new];

//                            [gameFriends setValue:model.status forKey:@"status"];
                            NSMutableDictionary * user = [NSMutableDictionary new];
                            [user setObject:[NSNumber numberWithInt:model.user_id] forKey:@"id"];
                            [user setValue:model.user_name forKey:@"nickname"];
                            [user setObject:[NSNumber numberWithInt:model.user_gender] forKey:@"gender"];
                            [user setValue:@"" forKey:@"address"];
                            [user setValue:model.user_avatar forKey:@"avatar"];
                            
                            [rank setObject:user forKey:@"user"];
                            [rank setObject:[NSNumber numberWithInt:model.score] forKey:@"score"];
                            [rank setObject:[NSNumber numberWithInt:rank_i] forKey:@"rank"];
                                
                            [userArr addObject:rank];
                                
                            [list setObject:userArr forKey:@"list"];

                            }
                            
//                            NSLog(@"榜单数据 list ====>> %@",list);
                            
                            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:list options:NSJSONWritingPrettyPrinted error:nil];
                            
                            NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                            
//                            NSLog(@"HTTPDataProcession 请求榜单列表 GetRank 异步回调 ==>> %@ ",jsonString);
                            
                            const char * cusChar =[jsonString UTF8String];
                            
                            rankDataBlock(cusChar);

                          }

                      }

                  }

              }
        
            }fail:^(id errorDes){
               NSLog(@"HTTPDataProcession 获取榜单数据 错误 ====>> %@",errorDes);
    }];
    
}

/**
 开始游戏
*/
+(void)gameStart{

    NSString *urlString = [NSString stringWithFormat:@"%@&id=%@",GAME_START,[CacheTool getGameId]];
    [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken]  success:^(id data){
        
            NSError * error;
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
//                NSLog(@"gameFriends dictionary === %@ ",dictionary);

        if (!error && dictionary!=nil && ![dictionary isKindOfClass:[NSNull class]]){
                
                int code = [dictionary[@"code"] intValue];

                if (code==0){//
                    
                NSLog(@"gameStart 上传成功  ==>> %@",dictionary[@"message"]);
                    
                 }
                
              }
        
            }fail:^(id errorDes){
                
                NSLog(@"gameStart 上传失败  ==>> %@",errorDes);

    }];
    
}


/**
 结束游戏
*/
+(void)gameEnd{
    
    NSString *urlString = [NSString stringWithFormat:@"%@&id=%@",GAME_END,[CacheTool getGameId]];
    [HTTPDataProcession getHTTPDataProcession:urlString token:[CacheTool getToken]  success:^(id data){
        
            NSError * error;
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
//                NSLog(@"gameFriends dictionary === %@ ",dictionary);

        if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){
                
                int code = [dictionary[@"code"] intValue];

                if (code==0){//
                    
                    NSLog(@"gameEnd 上传成功  ==>> %@",dictionary[@"message"]);
                    
                 }
                
              }
        
            }fail:^(id errorDes){
                
                NSLog(@"gameEnd 上传失败  ==>> %@",errorDes);

    }];
    
}

/**
 上传运动数据
*/
+(void)postGameRecord:(int)level
                score:(double)score
               record:(int)record
                 mode:(int)mode
           opponentId:(int)opponentId
     gameEndDataBlock:(GameEndDataBlock)gameEndDataBlock{
    
    NSMutableDictionary * gameRecord = [NSMutableDictionary new];
    //缓存的token、game_id
    NSString * game_id = [CacheTool getGameId];
    [gameRecord setObject:game_id forKey:@"game_id"];//游戏类型
    //预留字段:默认
    [gameRecord setObject:@0 forKey:@"distance"];//废弃
    [gameRecord setObject:@0 forKey:@"is_cancel"];//是否正常停止游戏 正常0 不正常1
    //unity回调数据
    [gameRecord setObject:[NSNumber numberWithDouble:score] forKey:@"score"];
    [gameRecord setObject:[NSNumber numberWithInt:mode] forKey:@"mode"];
   
    //缓存的动作数据和持续时间
    NSDictionary * movements = [IOS_NSUSERDEFAULT objectForKey:IOSSDK_MOTIONCOUNT];
    if (movements!=nil){
        NSDictionary * sub = movements[@"movements"];
       NSData * jsonData = [NSJSONSerialization dataWithJSONObject:sub options:NSJSONWritingPrettyPrinted error:nil];
       NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [gameRecord setObject:jsonString forKey:@"movements"];
        [gameRecord setObject:movements[@"duration"] forKey:@"duration"];
        [gameRecord setObject:movements[@"play_group"] forKey:@"play_group"];
    }
    
//    NSLog(@"gameRecord = %@",gameRecord);

    [HTTPDataProcession postHTTPDataProcession:GAME_RECORD withParams:gameRecord  token:[CacheTool getToken] success:^(id data){
        NSError * error;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        if (!error && dictionary!=nil &&![dictionary isKindOfClass:[NSNull class]]){

            int code = [dictionary[@"code"] intValue];

            if (code==0){
                
                NSDictionary * data = dictionary[@"data"];
                if (data!=nil) {
                    NSDictionary * record = data[@"record"];
                    if (record!=nil) {
                        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:record options:NSJSONWritingPrettyPrinted error:nil];
                        NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                        const char * cusChar =[jsonString UTF8String];
                        gameEndDataBlock(cusChar);
                        NSLog(@"gameRecord 上传成功 %@",record);
                    }
                }

                
            }else{
                NSLog(@"gameRecord 请求错误 =========== >>> %@",dictionary[@"msg"]);
             }
            
        }
        
    }fail:^(id errorDes){
        
        NSLog(@"gameRecord 请求失败 =========== >>> %@",errorDes);

    }];
    
    
}

//
+(NSString*)getBaseUrl{
    NSString * baseUrl;
    int isdebug = [[CacheTool getGameDebug] intValue];
    if (isdebug == 1){//测试环境
        baseUrl = @"https://test-shoes-api.funfet.com";
    }else{
        baseUrl = @"https://shoes-api.funfet.com";
    }
    return baseUrl;
}


@end
