//
//  RCTool.m
//  Demo
//
//  Created by 余衡武 on 2024/10/5.
//

#import "RCTool.h"

@implementation RCTool

+ (NSString *)timeStamp {
   NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
   [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
   NSString *date =  [formatter stringFromDate:[NSDate date]];
   NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date];
    return timeLocal;
}

/// 解析预览图
+ (UIImage *)getPreviewImageWebSocketData:(NSData *)data {
    const uint8_t *bytes = [data bytes];
    NSUInteger length = [data length];
    
    if (length < 7) { // 至少需要帧头、帧长度、帧类型、帧尾这些基础字段
        NSLog(@"数据长度不足，无法解析");
        return nil;
    }
    
    // 1. 检查帧头
    if (bytes[0] != 0xC8) {
        NSLog(@"帧头不匹配，解析失败");
        return nil;
    }
    
    // 2. 读取帧长度（帧数据部分的长度）
    uint32_t frameLength = 0;
    for (int i = 1; i < 5; i++) {
        frameLength = (frameLength << 8) | bytes[i];
    }
    
//    NSLog(@"帧数据长度：%u 字节", frameLength);
    
    // 3. 检查总长度是否合理
    if (frameLength + 7 != length) {  // 总长度应该是帧头 + 长度字段 + 帧类型 + 帧数据 + 帧尾
        NSLog(@"数据长度不匹配，解析失败");
        return nil;
    }
    
    // 4. 读取帧类型
    uint8_t frameType = bytes[5];
    if (frameType != 0x01) {  // 0x01 表示图片帧
        NSLog(@"不是图片帧，帧类型: 0x%x", frameType);
        return nil;
    }
    
    // 5. 读取帧数据（图片二进制数据）
    NSData *imageData = [NSData dataWithBytes:&bytes[6] length:frameLength];
    
    // 6. 检查帧尾
    if (bytes[6 + frameLength] != 0xC9) {
        NSLog(@"帧尾不匹配，解析失败");
        return nil;
    }
    
    // 7. 将图片数据转换为UIImage并展示
    UIImage *image = [UIImage imageWithData:imageData];
    if (image) {
//        NSLog(@"图片帧解析成功");
    } else {
        NSLog(@"图片数据无效，无法解析为UIImage");
    }
    
    return image;
}

+ (UIColor *)hwColor:(id)object{
    //16进制字符串
    if ([object isKindOfClass:[NSString class]]){
        return [self hwColorWithString:(NSString *)object];
    }
    //UIColor
    else if ([object isKindOfClass:[UIColor class]]){
        return (UIColor *)object;
    }
    
    return [UIColor blackColor];
}

+ (UIColor *)hwColorWithString:(NSString *)string{
    //删除字符串中的空格
    NSString *cString = [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    //长度是 6 或 8
    if ([cString length] < 6){
        return [UIColor clearColor];
    }
    
    //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
    if ([cString hasPrefix:@"0X"] || [cString hasPrefix:@"0x"]){
        cString = [cString substringFromIndex:2];
    }
    
    //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
    if ([cString hasPrefix:@"#"]){
        cString = [cString substringFromIndex:1];
    }
    
    if ([cString length] != 6){
        return [UIColor blackColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float)r / 255.0f)
                           green:((float)g / 255.0f)
                            blue:((float)b / 255.0f)
                           alpha:1.0];
}

/*颜色设置 可调整透明度*/
+ (UIColor *)hwColor:(id)object alpha:(CGFloat)dAlpha{
    //16进制字符串
    if ([object isKindOfClass:[NSString class]]){
        return [self hwColorWithString:(NSString *)object alpha:dAlpha];
    }
    //UIColor
    else if ([object isKindOfClass:[UIColor class]]){
        return (UIColor *)object;
    }
    
    return [UIColor blackColor];
}

+ (UIColor *)hwColorWithString:(NSString *)string alpha:(CGFloat)dAlpha{
    //删除字符串中的空格
    NSString *cString = [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    //长度是 6 或 8
    if ([cString length] < 6){
        return [UIColor clearColor];
    }
    
    //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
    if ([cString hasPrefix:@"0X"] || [cString hasPrefix:@"0x"]){
        cString = [cString substringFromIndex:2];
    }
    
    //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
    if ([cString hasPrefix:@"#"]){
        cString = [cString substringFromIndex:1];
    }
    
    if ([cString length] != 6){
        return [UIColor blackColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float)r / 255.0f)
                           green:((float)g / 255.0f)
                            blue:((float)b / 255.0f)
                           alpha:dAlpha];
}


/// 字典转JSON字符串
+ (NSString *)getJSONStringFrom:(NSDictionary *)dict {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

/// JSON字符串转字典
+ (NSDictionary *)getDictFromJSONString:(NSString *)json {
    NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    return dict;
}


@end
