//
//  iTools.m
//  VclustersGemini
//
//  Created by 余衡武 on 2020/4/1.
//  Copyright © 2020 APPLE. All rights reserved.
//

#import "iTools.h"
#import "CommonCrypto/CommonDigest.h"
#import <CommonCrypto/CommonCrypto.h>
#import "RSA.h"

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/* 运营商 首先需要引入以下两个系统类：*/
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

@implementation iTools

+ (NSString *)getJSONStringFromDictionary:(NSDictionary *)dict {
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonStr;
}

+ (NSString *)getJSONStringFromArray:(NSArray *)array {
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonStr;
}

+ (NSInteger)getNowTimeStamp {
    return [[NSDate date] timeIntervalSince1970];
}

+ (NSInteger)getNowTimeStampSS {
    NSDate  *dateValue = [NSDate date];
    NSTimeInterval second = [dateValue timeIntervalSince1970];
    long  long dTime = [[NSNumber numberWithDouble:second*1000] longLongValue];
    return dTime;
}

/** 获取当前时间戳-以秒为单位-return yyyyy年MM月dd日 HH:mm:ss */
+ (NSString *)getNowTimeString1 {
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    NSString *dateStr = [format stringFromDate:nowDate];
    return dateStr;
}

/** 获取当前时间戳-以秒为单位-return yyyyy-MM-dd HH:mm:ss */
+ (NSString *)getNowTimeString2 {
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [format stringFromDate:nowDate];
    return dateStr;
}

+ (NSInteger)getNowTimeStampToInterval:(NSTimeInterval)second {
    long  long dTime = [[NSNumber numberWithDouble:second*1000] longLongValue];
    return dTime;
}

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

+ (NSString *)getNowTimeString {
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString *dateStr = [format stringFromDate:nowDate];
    return dateStr;
}

+ (NSString *)getNowDateString {
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [format stringFromDate:nowDate];
    return dateStr;
}

+ (NSString *)getTimeStringFromTimeInterval:(NSInteger)timeInterval {
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString *timeString = [formatter stringFromDate:date];
    return timeString;
}

+ (NSDate *)getTimeStringToDate:(NSString *)timeStr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //需要设置为和字符串相同的格式
    [dateFormatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    NSDate *localDate = [dateFormatter dateFromString:timeStr];
    return localDate;
}

+ (NSString *)getPlayTimeStringFromTimeInterval:(NSTimeInterval)timeInterval {

    NSInteger seconds = timeInterval;
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minut
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];

    return format_time;
}

//ypp add 通讯录文件名格式YmdHis+随机数字(1000~9999) 2020 07 07 15 08 25 1000
+ (NSString *)getContactsNameStr {
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmss"];
    date = [formatter stringFromDate:[NSDate date]];
    int randomNumber = (int) arc4random_uniform(9999) + 1000;
    NSString *contactsNameStr = [NSString stringWithFormat:@"%@%d",date,randomNumber];
    return contactsNameStr;
}

+ (UIImage*)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)imageFromColor:(UIColor *)color view:(UIView *)view {
    CGRect rect = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (UIImage *)getImageFromColor:(UIColor *)color rect:(CGRect)rect {
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

/**将UIColor变换为UIImage,设置尺寸**/
+ (UIImage *)createImageWithColor:(UIColor *)color withSize:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size,NO,[UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

/**将文件大小B 自动转成对应的B  KB MB GB**/
+ (NSString *)getFileSizeStringFormedValue:(NSInteger)value
{
   double convertedValue = value*1.0;
   int multiplyFactor = 0;
   NSArray *tokens = [NSArray arrayWithObjects:@"B",@"KB",@"MB",@"GB",@"TB",nil];

   while (convertedValue > 1024 && multiplyFactor < tokens.count) {
       convertedValue /= 1024;
       multiplyFactor++;
   }

    NSString *text = [NSString stringWithFormat:@"%4.2f%@",convertedValue, [tokens objectAtIndex:multiplyFactor]];
    if ([text isEqualToString:@"0.00B"]) {
        text = @"0B";
    }
    
    return text;

}

+(BOOL)getBoolWithKey:(NSString*)key{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults boolForKey:key];
}
+(void)setBoolWithKey:(NSString*)key value:(BOOL)value{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:value forKey:key];
    [defaults synchronize];
}
+(NSString*)getStringWithKey:(NSString*)key{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults stringForKey:key];
}
+(void)setStringWithKey:(NSString*)key value:(NSString*)value{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:value forKey:key];
    [defaults synchronize];
}
+(NSInteger)getIntegerWithKey:(NSString*)key{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults integerForKey:key];
}
+(void)setIntegerWithKey:(NSString*)key value:(NSInteger)value{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:value forKey:key];
    [defaults synchronize];
}


+ (NSString *)notRounding:(float)price afterPoint:(int)position {

    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

    NSDecimalNumber *ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];

    NSDecimalNumber *roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];

    return [NSString stringWithFormat:@"%@%%",roundedOunces];

}

+ (CGFloat)notRoundingFloat:(float)price afterPoint:(int)position {

    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

    NSDecimalNumber *ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];

    NSDecimalNumber *roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];

    return [roundedOunces floatValue];

}

+ (NSString *)formatFloat:(float)f
{
    if (fmodf(f, 1)==0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.0f",f];
    } else if (fmodf(f*10, 1)==0) {//如果有两位小数点
        return [NSString stringWithFormat:@"%.1f",f];
    } else {
        return [NSString stringWithFormat:@"%.2f",f];
    }
}

/**
  获取运营商名称
 */
+ (NSString *)getCarrierInfo
{
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = nil;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 12.1) {
        if ([telephonyInfo respondsToSelector:@selector(serviceSubscriberCellularProviders)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
            NSDictionary *dic = [telephonyInfo serviceSubscriberCellularProviders];
            if (dic.allKeys.count) {
                carrier = [dic objectForKey:dic.allKeys[0]];
            }
#pragma clang diagnostic pop
        }
    }
   
    if(!carrier) {
        //遇到的 warning 又明知干不掉的时候就用这种方法隐藏即可,-Wdeprecated-declarations
#pragma clang diagnostic push
#pragma clang diagnostic ignored  "-Wdeprecated-declarations"
        carrier = telephonyInfo.subscriberCellularProvider;
#pragma clang diagnostic pop
    }
    
    //countryCode，移动国家码，MCC的资源由国际电联（ITU）统一分配和管理，唯一识别移动用户所属的国家，共3位，中国为460;
    NSString *countryCode = [carrier mobileCountryCode];
    
    //code，移动网络码，共2位，中国移动TD系统使用00，中国联通GSM系统使用01，中国移动GSM系统使用02，中国电信CDMA系统使用03，一个典型的IMSI号码为460030912121001
    NSString *code = [carrier mobileNetworkCode];
    
    //网络运营商的名字
    NSString *carrier_name = @"";

    //用户运营商网络 （中国电信：CHINANET，中国联通：UNICOM，中国移动：CMNET，中国铁通：CRTC，中国广电：GCABLENET）
    if ([countryCode isEqualToString:@"460"] && countryCode && code) {
        if ([code isEqualToString:@"00"] || [code isEqualToString:@"02"] || [code isEqualToString:@"04"] || [code isEqualToString:@"07"] || [code isEqualToString:@"08"]|| [code isEqualToString:@"13"]) {
            carrier_name = @"CMNET";
        }
        else if ([code isEqualToString:@"03"] || [code isEqualToString:@"05"] || [code isEqualToString:@"11"] || [code isEqualToString:@"12"])
        {
            carrier_name =  @"CHINANET";
        }
        else if ([code isEqualToString:@"01"] || [code isEqualToString:@"06"] || [code isEqualToString:@"09"] || [code isEqualToString:@"10"])
        {
            carrier_name =  @"UNICOM";
        }
        else if ([code isEqualToString:@"20"])
        {
            carrier_name =  @"CRTC";
        }
        else if ([code isEqualToString:@"15"])
        {
            carrier_name =  @"GCABLENET";
        }
       
    }

    return  carrier_name;

}

// 去除字符串中所有的空格和换行符(包括中间和首尾)
+ (NSString *)removeSpaceAndNewline:(NSString *)str
{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}

#pragma mark 加密/解密(AES RSA base64 md5)
// AES加密
+ (NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key
{
    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        
        return [resultData base64EncodedStringWithOptions:(NSDataBase64Encoding64CharacterLineLength)];
    }
    free(buffer);
    return nil;
}

//AES解密
+ (NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key
{
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc] initWithBase64EncodedString:encryptText options:NSDataBase64DecodingIgnoreUnknownCharacters];//base64解码
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        
        return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }
    free(buffer);
    return nil;
}

/**RSA加密-publicKey-公钥*/
+ (NSString *)RSAEncrypt:(NSString *)plainText key:(NSString *)publicKey {
    NSString *encrypted = [RSA encryptString:plainText publicKey:publicKey];
    return encrypted;
}
/**RSA解密-privateKey-私钥*/
+ (NSString *)RSADecrypt:(NSString *)encryptText key:(NSString *)privateKey {
    NSString *decrypted = [RSA decryptString:encryptText privateKey:privateKey];
    return decrypted;
}

/**Base64加密*/
+ (NSString *)Base64Encrypt:(NSString *)plainText {
    
    NSData *data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    
    return [data base64EncodedStringWithOptions:0];
}

/**base64解密*/
+ (NSString *)Base64Decrypt:(NSString *)encryptText {
    
    NSData *data = [self dataWithBase64EncodedString:encryptText];

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

/**base64格式字符串转换为文本数据*/
+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (string == nil)
        [NSException raise:NSInvalidArgumentException format:@""];
    if ([string length] == 0)
        return [NSData data];
    
    static char *decodingTable = NULL;
    if (decodingTable == NULL)
    {
        decodingTable = malloc(256);
        if (decodingTable == NULL)
            return nil;
        memset(decodingTable, CHAR_MAX, 256);
        NSUInteger i;
        for (i = 0; i < 64; i++)
            decodingTable[(short)encodingTable[i]] = i;
    }
    
    const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if (characters == NULL)     //  Not an ASCII string!
        return nil;
    char *bytes = malloc((([string length] + 3) / 4) * 3);
    if (bytes == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (YES)
    {
        char buffer[4];
        short bufferLength;
        for (bufferLength = 0; bufferLength < 4; i++)
        {
            if (characters[i] == '\0')
                break;
            if (isspace(characters[i]) || characters[i] == '=')
                continue;
            buffer[bufferLength] = decodingTable[(short)characters[i]];
            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
            {
                free(bytes);
                return nil;
            }
        }
        
        if (bufferLength == 0)
            break;
        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
        {
            free(bytes);
            return nil;
        }
        
        //  Decode the characters in the buffer to bytes.
        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
        if (bufferLength > 2)
            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
        if (bufferLength > 3)
            bytes[length++] = (buffer[2] << 6) | buffer[3];
    }
    
    bytes = realloc(bytes, length);
    return [NSData dataWithBytesNoCopy:bytes length:length];
}

/**md5加密*/
+ (NSString *)md5Encrypt:(NSString *)encryptText{

    const char *cStr = [encryptText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    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]
             
             ] lowercaseString];
    
}

#pragma mark - RSA加密demo
- (void)RSA {
    
    NSString *pubkey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI2bvVLVYrb4B0raZgFP60VXY\ncvRmk9q56QiTmEm9HXlSPq1zyhyPQHGti5FokYJMzNcKm0bwL1q6ioJuD4EFI56D\na+70XdRz1CjQPQE3yXrXXVvOsmq9LsdxTFWsVBTehdCmrapKZVVx6PKl7myh0cfX\nQmyveT/eqyZK1gYjvQIDAQAB\n-----END PUBLIC KEY-----";
    NSString *privkey = @"-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMMjZu9UtVitvgHS\ntpmAU/rRVdhy9GaT2rnpCJOYSb0deVI+rXPKHI9Aca2LkWiRgkzM1wqbRvAvWrqK\ngm4PgQUjnoNr7vRd1HPUKNA9ATfJetddW86yar0ux3FMVaxUFN6F0KatqkplVXHo\n8qXubKHRx9dCbK95P96rJkrWBiO9AgMBAAECgYBO1UKEdYg9pxMX0XSLVtiWf3Na\n2jX6Ksk2Sfp5BhDkIcAdhcy09nXLOZGzNqsrv30QYcCOPGTQK5FPwx0mMYVBRAdo\nOLYp7NzxW/File//169O3ZFpkZ7MF0I2oQcNGTpMCUpaY6xMmxqN22INgi8SHp3w\nVU+2bRMLDXEc/MOmAQJBAP+Sv6JdkrY+7WGuQN5O5PjsB15lOGcr4vcfz4vAQ/uy\nEGYZh6IO2Eu0lW6sw2x6uRg0c6hMiFEJcO89qlH/B10CQQDDdtGrzXWVG457vA27\nkpduDpM6BQWTX6wYV9zRlcYYMFHwAQkE0BTvIYde2il6DKGyzokgI6zQyhgtRJ1x\nL6fhAkB9NvvW4/uWeLw7CHHVuVersZBmqjb5LWJU62v3L2rfbT1lmIqAVr+YT9CK\n2fAhPPtkpYYo5d4/vd1sCY1iAQ4tAkEAm2yPrJzjMn2G/ry57rzRzKGqUChOFrGs\nlm7HF6CQtAs4HC+2jC0peDyg97th37rLmPLB9txnPl50ewpkZuwOAQJBAM/eJnFw\nF5QAcL4CYDbfBKocx82VX/pFXng50T7FODiWbbL4UnxICE0UBFInNNiWJxNEb6jL\n5xd0pcy9O2DOeso=\n-----END PRIVATE KEY-----";

    NSString *encrypted = [RSA encryptString:@"hello world!" publicKey:pubkey];
    HLog(@"encrypted: %@", encrypted);
    NSString *decrypted = [RSA decryptString:encrypted privateKey:privkey];
    HLog(@"decrypted: %@", decrypted);
}


//防止N秒内，同部同接口频繁调用的处理
+ (BOOL)timeOverTosecode:(NSInteger)index  bannerOldTime:(NSString *)bannerOldTime;
{
    BOOL reFreshDevice_flag = YES;
    
    NSString *nowTime = [iTools getNowTimeStampString];
    
    NSString *oldTime = nil;
    if (![bannerOldTime isEqual:@""]) {
        oldTime = bannerOldTime;
    }
    
    //比较
    if ([oldTime length] > 0) {
        //时间差
        NSDate *dateNow = [iTools getTimeStringToDate:nowTime];
        NSDate *dateOld = [iTools getTimeStringToDate:oldTime];
        NSTimeInterval distanceBetweenDates = [dateNow timeIntervalSinceDate:dateOld];
        long long min = [[NSNumber numberWithDouble:distanceBetweenDates] longLongValue];
        if (min < index)
        {
            reFreshDevice_flag = NO;
        }else{
            reFreshDevice_flag = YES;
        }
    }
    return reFreshDevice_flag;
}

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)FirstCharactor:(NSString *)pString
{
    //转成了可变字符串
    NSMutableString *pStr = [NSMutableString stringWithString:pString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)pStr,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)pStr,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pPinYin = [pStr capitalizedString];
    //获取并返回首字母
    return [pPinYin substringToIndex:1];
}

//根据uiview得到图像
+ (UIImage *)getImageFromView:(UIView *)fromView useScreenScale:(BOOL)use useNewMethod:(BOOL)useNewMethod
{
    UIImage *viewImage = nil;
    
    if (([[[UIDevice currentDevice] systemVersion] doubleValue] > 7) && useNewMethod) {
        UIGraphicsBeginImageContextWithOptions(fromView.bounds.size, NO, [[UIScreen mainScreen] scale]);
        [fromView drawViewHierarchyInRect:fromView.bounds afterScreenUpdates:NO];
        viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } else {
        NSInteger scale = use ? [[UIScreen mainScreen] scale] : 1;
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(fromView.bounds.size.width, fromView.bounds.size.height), NO, scale);
        [fromView.layer renderInContext:UIGraphicsGetCurrentContext()];
        viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    return viewImage;
}

//验证身份证
//必须满足以下规则
//1. 长度必须是18位，前17位必须是数字，第十八位可以是数字或X
//2. 前两位必须是以下情形中的一种：11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91
//3. 第7到第14位出生年月日。第7到第10位为出生年份；11到12位表示月份，范围为01-12；13到14位为合法的日期
//4. 第17位表示性别，双数表示女，单数表示男
//5. 第18位为前17位的校验位
//算法如下：
//（1）校验和 = (n1 + n11) * 7 + (n2 + n12) * 9 + (n3 + n13) * 10 + (n4 + n14) * 5 + (n5 + n15) * 8 + (n6 + n16) * 4 + (n7 + n17) * 2 + n8 + n9 * 6 + n10 * 3，其中n数值，表示第几位的数字
//（2）余数 ＝ 校验和 % 11
//（3）如果余数为0，校验位应为1，余数为1到10校验位应为字符串“0X98765432”(不包括分号)的第余数位的值（比如余数等于3，校验位应为9）
//6. 出生年份的前两位必须是19或20
+ (BOOL)verifyIDCardNumber:(NSString *)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([value length] != 18) {
        return NO;
    }
    NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString *leapMmdd = @"0229";
    NSString *year = @"(19|20)[0-9]{2}";
    NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd  , @"[0-9]{3}[0-9Xx]"];
    
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![regexTest evaluateWithObject:value]) {
        return NO;
    }
    int summary = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7
            + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9
            + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10
            + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5
            + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8
            + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4
            + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2
            + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6
            + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
    NSInteger remainder = summary % 11;
    NSString *checkBit = @"";
    NSString *checkString = @"10X98765432";
    checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判断校验位
    return [checkBit isEqualToString:[[value substringWithRange:NSMakeRange(17,1)] uppercaseString]];
}

#pragma mark --------------------
#pragma mark - Localizable

/**< 得到当前系统的语言 */
+ (NSString *)getCurrentLocalizableLanguage {
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    return currentLanguage;
}

/**< 得到当前语言是否为中文 */
+ (BOOL)isChineseLanguage {
    NSString *currentLanguage = [self getCurrentLocalizableLanguage];
    if ([currentLanguage rangeOfString:@"^zh-" options:NSRegularExpressionSearch range:NSMakeRange(0, currentLanguage.length)].location != NSNotFound) {
        return YES;
    }
    
    return NO;
}


#define FileHashDefaultChunkSizeForReadingData 1024*8
+ (NSString*)getFileMD5WithPath:(NSString*)path {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if([fileManager fileExistsAtPath:path isDirectory:nil])
    {
        NSData *data = [NSData dataWithContentsOfFile:path];

        unsigned char digest[CC_MD5_DIGEST_LENGTH];

        CC_MD5( data.bytes, (CC_LONG)data.length, digest );

        NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

        for( int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ )
        {

            [output appendFormat:@"%02x", digest[i]];
        }

        return output;

    }
    else
    {

        return @"";

    }
}


+ (CAShapeLayer *)getCornerRoundWithSelfView:(UIView *)originalView byRoundingCorners:(UIRectCorner)corners cornerRect:(CGRect)rect {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = originalView.bounds;
    maskLayer.path = maskPath.CGPath;
    return maskLayer;
}

//  彩色图变黑白图
+ (UIImage*)getGrayImageFromImage:(UIImage*)sourceImage {

    int width = sourceImage.size.width-2;
    int height = sourceImage.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil, width, height,8,0, colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);

    if (context ==NULL) {
        return nil;
    }

    CGContextDrawImage(context,CGRectMake(0,0, width, height), sourceImage.CGImage);

    UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];

    CGContextRelease(context);

    return grayImage;
}

// 显示base64二进制图片
+ (void)setImageView:(UIImageView *)imageView WithBase64String:(NSString *)avatar {
    //参数在这里 + (void) setImageView:(UIImageView *)imageView WithString:(NSString *)avatar
    //二进制显示
    /*服务器返回：例如
     data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAABnRSTlMAAAAAAABupgeRAAAAhElEQVRYhe3Y0QmAIBhF4YwGaZRGaNRGaJRGaYEyTj/RfTjnVYQPBRXbuh9DXuPfgOtkkWSRZJFkkUJZU3H+tsx3Q5VrLXS1ZJFkkWSRZJFkkWSRZJFkkUJZLfPH5vktX3mtv54buomySLJIskihrNBTvvWHP0V37oDQTZRFkkWSRQplnQDfEjVVBe3tAAAAAElFTkSuQmCC
     
     *上面的字符串复制到浏览器是可以显示出来一个图片的，这里说一下，字符串前面的data:image/png;base64是这个图片的格式，
     * web上面 解析好像是需要这部分的，但是拿到我们的iOS平台上，是不需要这部分的，有这部分反而解析不出来图片。
     * 所以这里可以说这部分属于格式部分，so我们显示的时候不要这部分。
     */
    NSArray *imageArray = [avatar componentsSeparatedByString:@","];
    NSData *imageData = [[NSData alloc] initWithBase64EncodedString:imageArray[1] options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *image = [UIImage imageWithData:imageData];
    imageView.image = [iTools cutAlphaZero:image];

}

// iOS裁剪掉图片周围透明度为0的部分
+ (UIImage *)cutAlphaZero:(UIImage *)image {
        
    CGImageRef cgimage = [image CGImage];
    
    size_t width = CGImageGetWidth(cgimage); // 图片宽度
    size_t height = CGImageGetHeight(cgimage); // 图片高度
    
    unsigned char *data = calloc(width * height * 4, sizeof(unsigned char)); // 取图片首地址
    size_t bitsPerComponent = 8; // r g b a 每个component bits数目
    size_t bytesPerRow = width * 4; // 一张图片每行字节数目 (每个像素点包含r g b a 四个字节)
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); // 创建rgb颜色空间
    
    CGContextRef context = CGBitmapContextCreate(data, width,height,bitsPerComponent,bytesPerRow,space,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgimage);
    int top = 0;  // 上边框透明高度
    int left = 0; // 左边框透明高度
    int right = 0; // 右边框透明高度
    int bottom = 0; // 底边框透明高度
    
    for (size_t row = 0; row < height; row++) {
        BOOL find = false;
        for (size_t col = 0; col < width; col++) {
            size_t pixelIndex = (row * width + col) * 4;
            //            int red = data[pixelIndex];
            //            int green = data[pixelIndex+1];
            //            int blue = data[pixelIndex + 2];
            int alpha = data[pixelIndex + 3];
            if (alpha != 0) {
                find = YES;
                break;
            }
        }
        if (find) {
            break;
        }
        top ++;
    }
    
    for (size_t col = 0; col < width; col++) {
        BOOL find = false;
        for (size_t row = 0; row < height; row++) {
            size_t pixelIndex = (row * width + col) * 4;
            
            int alpha = data[pixelIndex + 3];
            if (alpha != 0) {
                find = YES;
                break;
            }
        }
        if (find) {
            break;
        }
        left ++;
    }
    
    for (size_t col = width - 1; col > 0; col--) {
        BOOL find = false;
        for (size_t row = 0; row < height; row++) {
            size_t pixelIndex = (row * width + col) * 4;
            
            int alpha = data[pixelIndex + 3];
            if (alpha != 0) {
                find = YES;
                break;
            }
        }
        if (find) {
            break;
        }
        right ++;
    }
    
    for (size_t row = height - 1; row > 0; row--) {
        BOOL find = false;
        for (size_t col = 0; col < width; col++) {
            size_t pixelIndex = (row * width + col) * 4;
            int alpha = data[pixelIndex + 3];
            if (alpha != 0) {
                find = YES;
                break;
            }
        }
        if (find) {
            break;
        }
        bottom ++;
    }
    

    CGFloat scale = image.scale;
    CGImageRef newImageRef = CGImageCreateWithImageInRect(cgimage, CGRectMake(left * scale, top *scale, (image.size.width - left - right)*scale, (image.size.height - top - bottom)*scale));
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    // 释放
    CGImageRelease(cgimage);
    CGContextRelease(context);
    CGColorSpaceRelease(space);
    return  newImage;
}



+ (UIWindow *)getKeyWindow {

    UIWindow* window = nil;
   
    if (@available(iOS 13.0, *))
    {
      for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes)
      {
          if (windowScene.activationState == UISceneActivationStateForegroundActive)
          {
              window = windowScene.windows.firstObject;

              break;
          }
      }
    }else{
      window = [UIApplication sharedApplication].keyWindow;
    }
    
    return window;
}

//调整相机拍摄的图片方向
+ (UIImage *)fixOrientation:(UIImage *)srcImg {
    if (srcImg.imageOrientation ==UIImageOrientationUp) return srcImg;
    CGAffineTransform transform =CGAffineTransformIdentity;
    switch (srcImg.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
             transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
             transform = CGAffineTransformRotate(transform,M_PI);
             break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
             transform = CGAffineTransformTranslate(transform, srcImg.size.width,0);
             transform = CGAffineTransformRotate(transform,M_PI_2);
             break;
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
             transform = CGAffineTransformTranslate(transform,0, srcImg.size.height);
             transform = CGAffineTransformRotate(transform, -M_PI_2);
             break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
             break;
    }
    
    switch (srcImg.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
             transform = CGAffineTransformTranslate(transform, srcImg.size.width,0);
             transform = CGAffineTransformScale(transform, -1,1);
             break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
             transform = CGAffineTransformTranslate(transform, srcImg.size.height,0);
             transform = CGAffineTransformScale(transform, -1,1);
             break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
             break;
    }
    
    CGContextRef ctx =CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height,
                                             CGImageGetBitsPerComponent(srcImg.CGImage),0,
                                             CGImageGetColorSpace(srcImg.CGImage),
                                             CGImageGetBitmapInfo(srcImg.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (srcImg.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
             CGContextDrawImage(ctx,CGRectMake(0,0,srcImg.size.height,srcImg.size.width), srcImg.CGImage);
             break;
            
        default:
            CGContextDrawImage(ctx,CGRectMake(0,0,srcImg.size.width,srcImg.size.height), srcImg.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


+ (NSString *)getTaskUidStr
{
    NSInteger num = 6;
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < num; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

+ (void)lc_setAlternateIconName:(NSString*)iconName
{
    //anti apple private method call analyse
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(supportsAlternateIcons)] &&
        [[UIApplication sharedApplication] supportsAlternateIcons])
    {
        NSMutableString *selectorString = [[NSMutableString alloc] initWithCapacity:40];
        [selectorString appendString:@"_setAlternate"];
        [selectorString appendString:@"IconName:"];
        [selectorString appendString:@"completionHandler:"];
        
        SEL selector = NSSelectorFromString(selectorString);
        IMP imp = [[UIApplication sharedApplication] methodForSelector:selector];
        void (*func)(id, SEL, id, id) = (void *)imp;
        if (func)
        {
            func([UIApplication sharedApplication], selector, iconName, ^(NSError * _Nullable error) {});
        }
    }
}

+ (UIViewController *)appRootViewController {
    UIViewController *appRootVC = [iTools getKeyWindow].rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}
@end
