//
//  DebugView.m
//  Unity-iPhone
//
//  Created by duowan123 on 2021/12/22.
//

#import "DebugView.h"
#import "pub.h"
@interface DebugView ()
/*****测试*******/
@property (nonatomic,strong)UILabel * testLabel;//调试框
@property (nonatomic,strong)UIButton * uploadButton;//上传
@property (nonatomic,strong)UIButton * clearnButton;//上传

//当前的时间戳+丢包
@property (nonatomic,strong)NSString * tempStepString;//剑波要的字符串数据 缓存plist
@property(nonatomic,assign) int currentTS;//颖嘉要的测试数据

@property (nonatomic,strong)NSString *current_game_date;

@end

@implementation DebugView
#pragma mark ===============================================>> 静态的初始化方法  init的时候（建立蓝牙中心管理类，设置代理）
//单例静态
static DebugView* instance = nil;
+(instancetype)sharedInstance{
//    NSLog(@"创建单例一次 1");
     return [[self alloc] init];
    
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
//    NSLog(@"创建单例一次 2");
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
      instance = [super allocWithZone:zone];
  });
  return instance;
}

- (instancetype)init{
//    NSLog(@"创建单例一次 3");
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super init];
    });
    return instance;
}

#pragma mark ===============================================>> DEBUG
-(void)notificationStartGame{
    
//    //建立socket链接
//    SocketRocketUtility * install = [SocketRocketUtility sharedInstance];
//    [install SRWebSocketOpen];
    
    //初始化实时时间戳
    self.currentTS = -1;

    if (self.testLabel!=nil){
        [self.testLabel removeFromSuperview];
    }
    
    if (self.uploadButton!=nil){
        [self.uploadButton removeFromSuperview];
    }
    
    if (self.clearnButton!=nil){
        [self.clearnButton removeFromSuperview];
    }
    
    self.clearnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clearnButton.frame = CGRectMake(30, SCREEN_HEIGHT-40-10, SCALEoefficient(60), SCALEoefficient(25));
    self.clearnButton.backgroundColor = [UIColor redColor];
    [self.clearnButton addTarget: self action: @selector (button1BackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
    [self.clearnButton addTarget: self action: @selector (button1BackGroundNormal:) forControlEvents:UIControlEventTouchUpInside];
    [self.clearnButton setFont: [UIFont boldSystemFontOfSize:SCALEoefficient(13)]];
    [self.clearnButton setTitle:@"清理缓存" forState:UIControlStateNormal];
    [self.clearnButton addTarget:self action:@selector(clearCacheWithFilePath) forControlEvents:UIControlEventTouchUpInside];
    
    self.uploadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.uploadButton.frame = CGRectMake(30+SCALEoefficient(60)+20, SCREEN_HEIGHT-40-10, SCALEoefficient(60), SCALEoefficient(25));
    self.uploadButton.backgroundColor = [UIColor redColor];
    [self.uploadButton addTarget:self action:@selector(button1BackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
    [self.uploadButton addTarget:self action:@selector(button1BackGroundNormal:) forControlEvents:UIControlEventTouchUpInside];
    [self.uploadButton setFont: [UIFont boldSystemFontOfSize:SCALEoefficient(13)]];
    [self.uploadButton setTitle:@"上传" forState:UIControlStateNormal];
    [self.uploadButton addTarget:self action:@selector(uploadpPlistFile) forControlEvents:UIControlEventTouchUpInside];
    
    self.testLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCALEoefficient(20), -20, [UIScreen mainScreen].bounds.size.width-100, SCALEoefficient(140))];
    self.testLabel.textColor = [UIColor redColor];
    self.testLabel.font = [UIFont boldSystemFontOfSize:SCALEoefficient(14)];
    self.testLabel.backgroundColor = [UIColor clearColor];
    self.testLabel.textAlignment = NSTextAlignmentLeft;
    self.testLabel.numberOfLines = 0;

    //
    if ([UIApplication sharedApplication].keyWindow != nil){
//        [[UIApplication sharedApplication].keyWindow addSubview:self.clearnButton];
//        [[UIApplication sharedApplication].keyWindow addSubview:self.uploadButton];
//        [[UIApplication sharedApplication].keyWindow addSubview:self.testLabel];
    }
    
    //jb
//    [self clearCacheWithFilePath];
    
    //缓存当局游戏的起始时间
    self.current_game_date = [self getNowTime];

}

//button普通状态下的背景色
- (void )button1BackGroundNormal:(UIButton *)sender
{
     sender.backgroundColor = [UIColor redColor];
}
 
//  button高亮状态下的背景色
- (void )button1BackGroundHighlighted:(UIButton *)sender
{
     sender.backgroundColor = [UIColor orangeColor];
}

#pragma mark ===============================================>> 存储和上传数据
//清理缓存
- (void)clearCacheWithFilePath{
    
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Log"];
    NSError *error = nil;
    //删除子文件夹
    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    if (error){
        NSLog(@"清理缓存失败 %@",error);
        [PopupView showCusHUDA:@"清理失败"];
    }else{
        NSLog(@"清理缓存成功");
        [PopupView showCusHUDA:@"清理成功"];
    }
    
}

//数据写入沙河
-(void)writeFileToplist{
    
       NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Log"];
       NSFileManager *fileManager = [NSFileManager defaultManager];
       BOOL isDirExist = [fileManager fileExistsAtPath:path];
       if(!(isDirExist)){//文件夹不存在
           
          BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
          if(!bCreateDir){
              NSLog(@"文件夹不存在，创建文件夹失败！");
          }else{
              NSLog(@"文件夹不存在，创建文件夹成功，文件路径%@",path);
          }
           
       }else{//文件夹存在
           
           NSString * filePath = [[path stringByAppendingPathComponent:self.current_game_date] stringByAppendingPathExtension:@"txt"];
//           NSLog(@"-------文件夹存在件---------- 文件路径%@",path);
           if ([fileManager fileExistsAtPath:filePath]){
//           NSLog(@"-------文件存在，追加文件---------- 文件路径%@",filePath);

               NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
               [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
               NSData* stringData  = [self.tempStepString dataUsingEncoding:NSUTF8StringEncoding];
               [fileHandle writeData:stringData]; //追加写入数据
               [fileHandle closeFile];
               
           }else{
               
               NSLog(@"-------文件不存在，第一次写入文件---------- 文件路径%@",filePath);

               NSError *error;
               if([self.tempStepString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]){
                   NSLog(@"------写入文件------success");
               }else{
                    NSLog(@"------写入文件------fail,error==%@",error);
               };
               
           }
      
       }
    
}

-(void)uploadpPlistFile{
    
    //这个方法获取出的结果是一个数组.因为有可以搜索到多个路径.
    NSString *documentsDirectory = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Log"];
    //拼接文件路径
    NSString *filePathName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",self.current_game_date]];
    //如果保存的是一个数组.那就通过数组从文件当中加载.
    NSString *string = [NSString stringWithContentsOfFile:filePathName encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@",string);
    //4.设置请求体
    NSData *upData = [string dataUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"uploadpPlistFile upData = %@",upData);
    if (upData==nil){
        return;
    }
    //
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval=15;
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/javascript",@"image/jpeg",@"image/png",@"application/octet-stream",@"application/x-www-form-urlencoded", nil];
    //    NSLog(@"请求URL ===================>> %@",urlString);
    NSLog(@"******************* 请求头参数 = %@ ***************************",manager.requestSerializer.HTTPRequestHeaders);
    NSString * gameType;
    NSString * bundleIdentifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    if ([bundleIdentifier isEqualToString:@"com.Oujia.Run"]){
        gameType = @"run";
    }else if ([bundleIdentifier isEqualToString:@"com.Oujia.Dance"]){
        gameType = @"Dance";
    }else{
        gameType = @"Tricycle";
    }
    
    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:nil];
    [sessionManager POST:@"http://172.16.14.127:8080/upload" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){

        [formData  appendPartWithFileData:upData name:@"file" fileName:[NSString stringWithFormat:@"ios_%@_%s_%@_%@.txt",gameType,GAME_VERSION,[AlgorithmTool returnTimestamp],LEManager.peripheral.name] mimeType:@"text/plain"];

        }progress:^(NSProgress * _Nonnull uploadProgress){
            NSLog(@"测试数据 上传进度 = %@",uploadProgress);

        }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
            NSLog(@"测试数据 上传成功");

        }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){

            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(@"测试数据 上传失败 ===>> %@",errorObject);
                    if (errorObject !=nil && [errorObject isKindOfClass:[NSDictionary class]]){
                        NSString * result = errorObject[@"result"];
                        if ([result intValue] ==1){
                            [PopupView showCusHUDA:@"测试数据 上传成功"];
                        }
                        
                    }

                }
                
          }
            
    }];
 
}


-(void)debugMessage:(NSString*)message shoesInfo:(ShoesInfo*)shoesInfo{

    if (message.length <1){
        return;
    }
       
    /********************调试窗数据 *****************/
    NSArray *aArray = [message componentsSeparatedByString:@","];
    if (aArray == nil || [aArray isKindOfClass:[NSNull class]] || aArray.count<30){
        return;
    }
    
    //上传即使动作数据
//    [[SocketRocketUtility sharedInstance] sendData:nil withRequestURI:message];
    if (LEManager.RSSI == nil){
        LEManager.RSSI = @0;
    }
    //缓存动作数据plist文件
     message = [NSString stringWithFormat:@"%@,%@",message,LEManager.RSSI];
    self.tempStepString = [NSString stringWithFormat:@"%@\n",message];
    if (self.tempStepString!=nil && self.tempStepString.length>1){
        [self writeFileToplist];
    }
    
//    NSLog(@"aArray == %@",aArray);
//    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.testLabel!=nil){
            self.testLabel.text = [NSString stringWithFormat:@"right:[%@,%@,%@] [%@,%@,%@] [%@,%@,%@] [%@,%@,%@] \nleft:[%@,%@,%@] [%@,%@,%@] [%@,%@,%@] [%@,%@,%@]  \nrssi:[%@ %@] ts:%@ \n步数:[%@ %@][%d %d] \n步频:[%d：%d  %d：%d] \nsdk版本:%s ",aArray[0],aArray[1],aArray[2],aArray[3],aArray[4],aArray[5],aArray[6],aArray[7],aArray[8],aArray[9],aArray[10],aArray[11],aArray[12],aArray[13],aArray[14],aArray[15],aArray[16],aArray[17],aArray[18],aArray[19],aArray[20],aArray[21],aArray[22],aArray[23],LEManager.RSSI,aArray[26],aArray[27],aArray[28],aArray[29],shoesInfo.rightStepCount,shoesInfo.leftStepCount,shoesInfo.rightStepStatus,shoesInfo.rightStepFreq,shoesInfo.leftStepStatus,shoesInfo.leftStepFreq,GAME_VERSION];
        }
//    });
    
    /********************颖嘉+的ts丢包数据 *****************/
    NSString * tsString =  aArray[27];
//    NSLog(@"剑波 getGameDataStr 时间戳 ==============>> %@\n",tsString);
    int tsInt = [tsString  intValue];
    int total;
    if (self.currentTS != -1){//颖嘉初始值未知 ios初始值==1000
        //1....255
        if (tsInt > self.currentTS){
             total = tsInt - self.currentTS - 1;
        }
        //255...1
        if (tsInt < self.currentTS){
            if (tsInt ==0){
                total = (255-self.currentTS) + tsInt + 1 - 1;
            }else{
                total = (255-self.currentTS) + tsInt - 1;
            }
        }
        if (total > 30){
            NSLog(@"getGameDataStr 丢包 ================================>> %d",total);
            dispatch_async(dispatch_get_main_queue(), ^{
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//                [PopupView showCusHUDA:[NSString stringWithFormat:@"丢包数: %d",total]];
            });
        }
    }
//    NSLog(@"tsInt = %d  currentTS = %d total = %d",tsInt,self.currentTS,total);
    self.currentTS = tsInt;
    
}



// 返回时间戳
-(NSString *)getNowTime{

    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY_MM_dd_HH_mm_ss"];//设定时间格式,这里可以设置成自己需要的格式
    NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串
    return dateString;

}
   
@end
