//
//  SMBase.m
//  SkinMagnifier
//
//  Created by nana on 2020/11/4.
//

#import "SMBase.h"
#import <objc/runtime.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <SystemConfiguration/CaptiveNetwork.h>




@implementation SMBase

UIColor *rgba(int r,int g ,int b ,CGFloat a) {
    return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
}
NSAttributedString *createAttString(NSString *str,CGFloat fontSize,UIColor *color) {
    return [[NSAttributedString alloc] wb_initWithString:str FontSize:fontSize TextColor:color];
}
CGSize biliSize(CGFloat w,CGFloat h) {
    static CGSize bSize;
    if (!bSize.width) {
        bSize = [UIScreen mainScreen].bounds.size;
    }
    CGFloat bliw = bSize.width / 375.0;
    CGFloat blih = bSize.height /667.0;
    return  CGSizeMake(w * bliw, h * blih);
}

CGFloat safaTop(CGFloat top) {
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    UIEdgeInsets e =  window.safeAreaInsets;
    return  top + e.top - 20;
}
CGFloat safaBottom(CGFloat bottoom) {
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    UIEdgeInsets e =  window.safeAreaInsets;
    return bottoom - e.bottom;
}

NSString *encryptAES128(NSString *value, NSString *key) {
    char keyPtr[kCCKeySizeAES128+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
//    char ivPtr[kCCBlockSizeAES128 + 1];
//    bzero(ivPtr, sizeof(ivPtr));
//    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    NSData* xData = [value dataUsingEncoding:NSUTF8StringEncoding];

    
    NSUInteger dataLength = [xData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,/*ivPtr*/
                                          [xData bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *rData = [NSData dataWithBytes:buffer length:numBytesEncrypted];
        free(buffer);
        return dataToHexString(rData);
    }
    free(buffer);
    return nil;
}
NSString *decryptAES128(NSString *value, NSString *key) {
    
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
//    char ivPtr[kCCBlockSizeAES128 + 1];
//    bzero(ivPtr, sizeof(ivPtr));
//    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    
    NSData *xData = hexStringToData(value);
    
    NSUInteger dataLength = [xData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,/*ivPtr*/
                                          [xData bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *rData = [NSData dataWithBytes:buffer length:numBytesDecrypted];
        
        free(buffer);
        return [[NSString alloc] initWithData:rData encoding:NSUTF8StringEncoding];
    }
    free(buffer);
    return nil;
}
NSString *md5String(NSString *value) {
    const char *cStr = [value UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

NSData *hexStringToData(NSString *hexString) {
    if (!hexString || [hexString length] == 0) {
          return nil;
      }
      
      NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:20];
      NSRange range;
      if ([hexString length] % 2 == 0) {
          range = NSMakeRange(0, 2);
      } else {
          range = NSMakeRange(0, 1);
      }
      for (NSInteger i = range.location; i < [hexString length]; i += 2) {
          unsigned int anInt;
          NSString *hexCharStr = [hexString substringWithRange:range];
          NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
          
          [scanner scanHexInt:&anInt];
          NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
          [hexData appendData:entity];
          
          range.location += range.length;
          range.length = 2;
      }
      return hexData;
}
NSString *dataToHexString(NSData *data) {
    if (!data || [data length] == 0) {
         return @"";
     }
     NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
     
     [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
         unsigned char *dataBytes = (unsigned char*)bytes;
         for (NSInteger i = 0; i < byteRange.length; i++) {
             NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
             if ([hexStr length] == 2) {
                 [string appendString:hexStr];
             } else {
                 [string appendFormat:@"0%@", hexStr];
             }
         }
     }];
     return string;
}

NSString *privacyString(NSString *value, int from, int len,NSString *pString) {
    if (value.length ==0 || (value.length-1 < (from+len))) {
        return value;
    }
    NSMutableString *xxx = [[NSMutableString alloc] init];
    for (int i = 0; i < len; i++) {
        [xxx appendString:pString];
    }
    NSMutableString *s = [[NSMutableString alloc] initWithString:value];
    [s replaceCharactersInRange:NSMakeRange(from, len) withString:xxx];
    
    return s;
}

NSString *nowTimeTimestamp(void) {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%lld", (long long)([datenow timeIntervalSince1970]*1000.0)];
    return timeSp;
}

NSString *timestampString(long long t ,NSString *formatter){
    if (t > 100000000000) {
        t = t / 1000;
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];
    NSDateFormatter *datef = [[NSDateFormatter alloc] init];
    [datef setDateFormat:formatter];
    NSString *dateString = [datef stringFromDate:date];
    return dateString;
}


NSString *deviceWifiName(void) {
    return @"DAS01-1";
}
NSString *deviceWifiPWd(void) {
    return @"12345678";
}

NSString *WIFIAddress(void) {
    NSString *address = nil;
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
      // Loop through linked list of interfaces
      temp_addr = interfaces;
      while(temp_addr != NULL) {
        if(temp_addr->ifa_addr->sa_family == AF_INET) {
          // Check if interface is en0 which is the wifi connection on the iPhone
          if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
            // Get NSString from C String
            address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
          }
        }
        temp_addr = temp_addr->ifa_next;
      }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}


NSString *WIFIName(void)
{
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
     for (NSString *ifname in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef) ifname);
        if (info && [info count]) {
            break;
        }
    }
    NSDictionary *dic = (NSDictionary *)info;
    NSString *ssid = [dic objectForKey:@"SSID"];
    
    if (TARGET_IPHONE_SIMULATOR == 1 && TARGET_OS_IPHONE == 1) {
          //模拟器
          return deviceWifiName();
      }
    return ssid;
}
///WIFI 名字
NSString *WIFIMacAddress(void) {
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
     for (NSString *ifname in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef) ifname);
        if (info && [info count]) {
            break;
        }
    }
    NSDictionary *dic = (NSDictionary *)info;
    NSString *ssid = [dic objectForKey:@"BSSID"] ;
    
    return ssid;
}

bool islinkDeviceWifi(void) {

    return  [WIFIName() containsString:deviceWifiName()];

}


@end


@implementation UILabel (SMBase)
- (void)wb_setFontSize:(CGFloat )fontSize TextColor:(UIColor *)textColor Text:(NSString *)text {
    self.font = [UIFont systemFontOfSize:fontSize];
    self.textColor = textColor;
    self.text = text;
}
@end


@implementation UIImage (SMBase)


+ (instancetype )wb_imageWithColor:(UIColor *)color {
    return [self wb_imageWithColor:color size:CGSizeMake(1, 1)];
}

+ (instancetype )wb_imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/// 根据不同比例设置图片
+ (instancetype )wb_biliImageName:(NSString *)name {
    NSString *bImageName = name;
    CGSize bSize = [UIScreen mainScreen].bounds.size;
    if (abs((int)(bSize.height / 16 - bSize.width / 9)) < 5) {
        bImageName = [NSString stringWithFormat:@"%@_16",name];
    }
    if (abs((int)(bSize.height / 19 - bSize.width / 9)) < 5) {
        bImageName = [NSString stringWithFormat:@"%@_19",name];
    }
    UIImage *image =  [UIImage imageNamed:bImageName];
    if (!image) {
        image = [UIImage imageNamed:name];
    }
    return image;
}

@end

@implementation UIButton (SMBase)
- (void)wb_setImageName:(NSString *)imageName {
    NSString *imageNor = [NSString stringWithFormat:@"%@_nor",imageName];
    NSString *imageSel = [NSString stringWithFormat:@"%@_sel",imageName];
    UIImage *norImage = [UIImage imageNamed:imageNor];
    if (!norImage) {
        norImage = [UIImage imageNamed:imageName];
    }
    [self setImage:norImage forState:UIControlStateNormal];
    
    UIImage *selImage = [UIImage imageNamed:imageSel];
    if (selImage) {
        [self setImage:selImage forState:UIControlStateSelected];
    }
}

- (void)wb_setRightImage {

    self.transform = CGAffineTransformRotate(self.transform, M_PI);
    self.titleLabel.transform = CGAffineTransformRotate(self.titleLabel.transform, M_PI);
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, M_PI);
}
@end

@implementation UIColor (SMBase)
+ (instancetype)wb_randColor {
    return [UIColor colorWithRed:drand48() green:drand48() blue:drand48() alpha:1];
}
@end

@implementation NSAttributedString (SMBase)
- (instancetype)wb_initWithString:(NSString *)str FontSize:(CGFloat )fontSize TextColor:(UIColor *)textColor{
    if (!str || ![str isKindOfClass:[NSString class]]) {
        str = @"";
    }
    NSMutableDictionary *pDict = [[NSMutableDictionary alloc] init];
    pDict[NSFontAttributeName] = [UIFont systemFontOfSize:fontSize];
    pDict[NSForegroundColorAttributeName] = textColor;
    
    return [[NSAttributedString alloc ] initWithString:str attributes:pDict];
}
@end

@implementation UIViewController (SMBase)


+ (void)load {
    Method viewDidLoadM = class_getInstanceMethod(self, @selector(viewDidLoad));
    Method zl_viewDidLoadM = class_getInstanceMethod(self, @selector(zl_viewDidLoad));
    method_exchangeImplementations(viewDidLoadM, zl_viewDidLoadM);
    
    
}
- (void)zl_viewDidLoad {
    [self zl_viewDidLoad];
    NSLog(@"DEBUG控制器 zl_viewDidLoad %@",[self class]);
    self.wb_titleLabel = [[UILabel alloc] init];
    self.wb_titleLabel.font = [UIFont systemFontOfSize:17];
    self.wb_titleLabel.textColor = rgba(76, 74, 66, 1);
    self.wb_titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.wb_titleLabel];
    [self.wb_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(safaTop(35));
        make.centerX.mas_equalTo(0);
        make.left.mas_equalTo(60);
        make.right.mas_equalTo(-60);
    }];
}


- (UILabel *)wb_titleLabel {
    return objc_getAssociatedObject(self, @selector(wb_titleLabel));
}

- (void)setWb_titleLabel:(UILabel *)wb_title {
    return objc_setAssociatedObject(self,  @selector(wb_titleLabel), wb_title, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


@end



@implementation UIView (SMBase)

- (void)wb_showFromSuperView:(UIView *)view {
    [view addSubview:self];
    self.frame = CGRectMake(0, view.bounds.size.height, view.bounds.size.width, view.bounds.size.height);
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height);
    }];
}
- (void)wb_disMiss {
    [UIView animateWithDuration:0.25 animations:^{
        CGRect bRect =self.frame;
        self.frame = CGRectMake(0,bRect.size.height, bRect.size.width, bRect.size.height);
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


- (void)wb_showRTLFromSuperView:(UIView *)view {
    [view addSubview:self];
    self.frame = CGRectMake(view.bounds.size.width, 0, view.bounds.size.width, view.bounds.size.height);
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height);
    }];
}
- (void)wb_disLTRMiss {
    [UIView animateWithDuration:0.25 animations:^{
        CGRect bRect =self.frame;
        self.frame = CGRectMake( bRect.size.width,0, bRect.size.width, bRect.size.height);
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


- (void)wb_showlTBFromSuperView:(UIView *)view {
    UIButton *wb_backView = [[UIButton alloc] init];
    [wb_backView addTarget:self action:@selector(wb_disBTlLMiss) forControlEvents:UIControlEventTouchUpInside];
    wb_backView.frame =[UIScreen mainScreen].bounds;
    wb_backView.backgroundColor =[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [wb_backView addSubview:self];
    self.center = wb_backView.center;
    [view addSubview:wb_backView];
    [self animationWithLayer:wb_backView.layer duration:0.25 values:@[@0.0, @1.2, @1.0]];
}

- (void)wb_disBTlLMiss
{
    UIView *wb_backView = self.superview;
    [self animationWithLayer:wb_backView.layer duration:0.25 values:@[@1.0, @0.66, @0.33, @0.0]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [wb_backView removeFromSuperview];
    });
}

- (void)animationWithLayer:(CALayer *)layer duration:(CGFloat)duration values:(NSArray *)values
{
    CAKeyframeAnimation *KFAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    KFAnimation.duration = duration;
    KFAnimation.removedOnCompletion = NO;
    KFAnimation.fillMode = kCAFillModeForwards;

    NSMutableArray *valueArr = [NSMutableArray arrayWithCapacity:values.count];
    for (NSUInteger i = 0; i<values.count; i++) {
        CGFloat scaleValue = [values[i] floatValue];
        [valueArr addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(scaleValue, scaleValue, scaleValue)]];
    }
    KFAnimation.values = valueArr;
    KFAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];

    [layer addAnimation:KFAnimation forKey:nil];
}

+ (void)showFromView:(UIView *)view text:(NSString *)text afterDelay:(CGFloat )afterDelay {

    UIView *selfView = [[UIView alloc] init];
    selfView.frame = view.bounds;
    [view addSubview:selfView];
    
    CGFloat tW = view.bounds.size.width- 100;
   CGRect tRect =  [text boundingRectWithSize:CGSizeMake(tW, MAXFLOAT)
                                         options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine
                                      attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
                                         context:nil];
    
    UIView *contView = [[UIView alloc] init];
    contView.alpha = 0;
    contView.backgroundColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:0.34];
    contView.layer.cornerRadius = 10;

    
    [selfView addSubview:contView];
    [contView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(100);
        make.size.mas_equalTo(CGSizeMake(tW+40, tRect.size.height+40));
    }];
    

    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.numberOfLines = 0;
    textLabel.attributedText = createAttString(text, 15, [UIColor whiteColor]);
    textLabel.frame = CGRectMake(20, 20, tW, tRect.size.height);
    [contView addSubview:textLabel];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(afterDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.25 animations:^{
            contView.alpha = 0.0;
        } completion:^(BOOL finished) {
            [selfView removeFromSuperview];
        }];

    });

    [UIView animateWithDuration:0.25 animations:^{
        contView.alpha = 1.0;
    }];
}

/// 箭头显示在哪个位置
-(void)alertToView:(UIView *)pView Postion:(int)postion vsize:(CGSize)vsize{
    UIResponder *nextResponder =  pView;
    UIViewController *vc = nil;
    do
    {
        nextResponder = [nextResponder nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            vc = (UIViewController*)nextResponder;
            
        }

    } while (nextResponder);
    
    UIControl *bgView = [[UIControl alloc] init];
    bgView.tag = 147889;
    [bgView addTarget:bgView action:@selector(removeFromSuperview) forControlEvents:UIControlEventTouchUpInside];
    bgView.backgroundColor = rgba(0, 0, 0, 0.3);
    bgView.frame = CGRectMake(0, 0, vc.view.frame.size.width,  vc.view.frame.size.height);
    [vc.view addSubview:bgView];
    
    CGRect xRect = [pView.superview convertRect:pView.frame toView:vc.view];
    UIImageView *jtImageView = [[UIImageView alloc] init];
    jtImageView.image = [UIImage imageNamed:@"alert_pop_tk"];
    [bgView addSubview:jtImageView];

    [bgView addSubview:self];
    
    /// 下面
    jtImageView.frame = CGRectMake(xRect.origin.x,  CGRectGetMaxY(xRect), 18, 14);
    CGFloat vX = xRect.origin.x - (vsize.width/2.0);
    if (vX +vsize.width > bgView.frame.size.width) { // 右边
        CGFloat d = (vX + vsize.width) - bgView.frame.size.width;
        vX =vX - d - 10;
    }
    // 左边为做
    self.frame = CGRectMake(vX, CGRectGetMaxY(xRect)+10, vsize.width, vsize.height);

}

-(void)alertDisMiss {
    UIResponder *nextResponder =  self;
    UIViewController *vc = nil;
    do
    {
        nextResponder = [nextResponder nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            vc = (UIViewController*)nextResponder;
            
        }

    } while (nextResponder);
    
    for (UIView *vView in  vc.view.subviews) {
        if (vView.tag == 147889) {
            [vView removeFromSuperview];
            break;;
        }
    }
    
}

@end


