//
//  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>

@implementation iTools

#pragma mark 字典、数组转JSONString
/** 字典转JSONString */
+ (NSString *)getJSONStringFromDictionary:(NSDictionary *)dict {
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonStr;
}

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

#pragma mark 时间戳
/** 获取当前时间戳-以秒为单位-return NSInteger */
+ (NSInteger)getNowTimeStamp {
    return [[NSDate date] timeIntervalSince1970];
}

/** 获取当前时间戳-以秒为单位-return yyyy/MM/dd HH:mm */
+ (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;
}

/** 获取当前时间戳-以秒为单位-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;
}

/** 获取当前时间戳-以毫秒为单位-return NSInteger */
+ (NSInteger)getNowTimeStampSS {
    NSDate  *dateValue = [NSDate date];
    NSTimeInterval second = [dateValue timeIntervalSince1970];
    long  long dTime = [[NSNumber numberWithDouble:second*1000] longLongValue];
    return dTime;
}

/** 获取当前时间戳-以毫秒为单位--return YYYYMMddhhmmssSSS */
+ (NSString *)getNowTimeStampString {
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    NSString *timeNow = [NSString stringWithFormat:@"%@", date];
    return timeNow;
}

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

/** 获取现在到某个时间点的时间戳*/
+ (NSInteger)getNowTimeStampToInterval:(NSTimeInterval)second {
    long  long dTime = [[NSNumber numberWithDouble:second*1000] longLongValue];
    return dTime;
}

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

/**时间戳转字符串-yyyy/MM/dd HH:mm*/
+ (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;
}

/** 秒转播放时间HH:mm:ss */
+ (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;
}

#pragma mark 通讯录备份
//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;
}

//ypp add 推流业务随机生成6位数的字符串
+ (NSString *)getTaskUidStr {
    int randomNumber = (int) arc4random_uniform(999999) + 100000;
    NSString *strRandom = [NSString stringWithFormat:@"%d",randomNumber];
    return strRandom;
}

#pragma mark 绘制图片UIImage
/** 根据颜色绘制图片 */
+ (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;
}

/** 根据颜色和view 绘制指定大小的图片 */
+ (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;
}

/** 根据颜色和rect 绘制指定大小的图片 */
+ (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;
}

/** 根据颜色和size 绘制指定大小的图片 */
+ (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;
}

/**根据uiview得到图像UIImage*/
+ (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;
}

//  彩色图变黑白图
+ (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;
}

#pragma mark 绘制圆角
/**圆角切割*/
+ (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;
}

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

#pragma mark 小数取整 不四舍五入.
/** 小数取整 不四舍五入 */
+ (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];
    }
}

#pragma mark 字符串处理
/** 去除字符串中所有的空格和换行符(包括中间和首尾) */
+ (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;
}

/** 获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)*/
+ (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];
}

#pragma mark 系统语言
/** 获取当前系统的语言 */
+ (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;
}

#pragma mark push到指定vc
/**push到vc 控制器
* 1、NavigationController之前有push过就back
* 2、NavigationController之前没有push过就push
*/
+ (void)pushVCWithBackOrPushFromNvc:(UINavigationController *)nvc toVc:(UIViewController *)vc {
    
    BOOL isBack = NO; // 是返回 还是push 
    for (UIViewController *controller in nvc.viewControllers) {
        if ([controller isKindOfClass:[vc class]]) {
            [nvc popToViewController:controller animated:YES];
            isBack = YES;
        }
    }
    
    if (!isBack) {
        [nvc pushViewController:vc animated:YES];
    }
}

#pragma mark 文件大小格式化
/**将文件大小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;

}

#pragma mark 获取文件MD5值
/**获取文件MD5值*/
#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 @"";

    }
}

#pragma mark 关闭声音
/**关闭其他播放声音*/
+ (void)closeVoice {
    
    NSError *categoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&categoryError];
    if (!success)
    {
        HLog(@"Error setting audio session category: %@", categoryError);
    }

    NSError *activeError = nil;
    success = [[AVAudioSession sharedInstance] setActive:NO error:&activeError];
    if (!success)
    {
        HLog(@"Error setting audio session active: %@", activeError);
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 恢复声音

        NSError *activeError1 = nil;
        BOOL success1 = [[AVAudioSession sharedInstance] setActive:YES error:&activeError1];
        if (!success1)
        {
            HLog(@"Error setting audio session active: %@", activeError1);
        }

    });

}

#pragma mark 其他
/**防止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;
}

// 根据文件ID 获取文件中心文件URL地址
+ (NSURL *)getFileUrlFromFileID:(NSString *)ID {
    
    NSString *fileUrl = [NSString stringWithFormat:@"%@/document/newFile/download/0/%@?fileKey=%@",FileService,Const_File_Access_Key,ID];
    return [NSURL URLWithString:fileUrl];
    
}


// 显示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 = (unsigned char *)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;
}


+ (NSUInteger)getIndexFromCloudPhoneListWithModel:(CloudPhoneModel *)model {
    
    NSUInteger index = 0;
    
    for (NSUInteger i = 0; i < [UseAccountManage shareInstance].cloudPhoneListModel.diskInfo.count; i++) {
        CloudPhoneModel *itemModel = [[UseAccountManage shareInstance].cloudPhoneListModel.diskInfo objectAtIndex:i];
        if (itemModel.phoneId == model.phoneId) {
            index = i;
            break;
        }
    }
    
    return index;
}

+ (NSUInteger)getIndexFromCloudPhoneListWithPhoneID:(NSInteger)phoneId {
    
    NSUInteger index = 0;
    
    for (NSUInteger i = 0; i < [UseAccountManage shareInstance].cloudPhoneListModel.diskInfo.count; i++) {
        CloudPhoneModel *itemModel = [[UseAccountManage shareInstance].cloudPhoneListModel.diskInfo objectAtIndex:i];
        if (itemModel.phoneId == phoneId) {
            index = i;
            break;
        }
    }
    
    return index;
}

+ (NSDate *)getInternetDate{
    NSString *urlString = @"http://m.baidu.com";

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    // 实例化NSMutableURLRequest，并进行参数配置
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSError *error = nil;
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request
    returningResponse:&response error:&error];

    // 处理返回的数据
    if (error) {
        return [NSDate date];
    }

    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];

    date = [date substringFromIndex:5];//index到这个字符串的结尾

    date = [date substringToIndex:[date length]-4];//从索引0到给定的索引index

    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];

    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];

    NSDate *netDate = [dMatter dateFromString:date];//时间差8小时

    NSTimeZone *zone = [NSTimeZone systemTimeZone];

    NSInteger interval = [zone secondsFromGMTForDate: netDate];

    netDate = [netDate dateByAddingTimeInterval: interval];
        
    return netDate;
}


+ (NSString *)getInternetDateString{
    NSString *urlString = @"http://m.baidu.com";

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    // 实例化NSMutableURLRequest，并进行参数配置
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSError *error = nil;
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request
    returningResponse:&response error:&error];

    // 处理返回的数据
    if (error) {
        NSDate *nowDate = [NSDate date];
        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *dateStr = [format stringFromDate:nowDate];
        
        return dateStr;
    }

    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];

    date = [date substringFromIndex:5];//index到这个字符串的结尾

    date = [date substringToIndex:[date length]-4];//从索引0到给定的索引index

    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];

    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];

    NSDate *netDate = [dMatter dateFromString:date];//时间差8小时

    NSTimeZone *zone = [NSTimeZone systemTimeZone];

    NSInteger interval = [zone secondsFromGMTForDate: netDate];

    netDate = [netDate dateByAddingTimeInterval: interval];
    
    NSDateFormatter *format1 = [[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [format1 stringFromDate:netDate];
    
    return dateStr;
}
@end
