//
//  Utils.m
//  UPayProject
//
//  Created by 张建伟 on 15/1/6.
//  Copyright (c) 2015年 张建伟. All rights reserved.
//

#import "Utils.h"
#import "CommonCrypto/CommonDigest.h"
//#import "AFHTTPRequestOperation.h"
#import "UIImage+Additions.h"
#import <QuartzCore/QuartzCore.h>
#import <Accelerate/Accelerate.h>
#import "MBProgressHUD.h"
#import <AVFoundation/AVFoundation.h>
#import <UIImageView+WebCache.h>
//#import "LoginModel.h"
#import "MyColors.h"
#import "MBProgressHUD+Add.h"
#import "NSString+Additions.h"
#import <CommonCrypto/CommonDigest.h>
//#import "NewMessageModule.h"
#import <sys/utsname.h>

#import "Utils.h"
#import "StitchingImage.h"
@implementation Utils


+(id)ifNullToNil:(id)objc
{
    if ([objc isKindOfClass:[NSNull class]]) {
        return nil;
    }
    
    return objc;
}

+ (NSDictionary *)DeviceInfo
{
    BOOL allowPush = YES;
    
    if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
        if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
            allowPush = YES;
        }else{
            allowPush = NO;
        }
    }else{
        if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes]!=UIRemoteNotificationTypeNone) {
            allowPush = YES;
        }else{
            allowPush = NO;
        }
    }

    NSString *devicemodel = [self DeviceModel];
    NSString *appversion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *iosversion = [UIDevice currentDevice].systemVersion;
    NSString *devicetoken = [userDefaults objectForKey:USERDEFAULT_APP_TOKEN];
    if (!devicetoken) {
        devicetoken = [NSUUID UUID].UUIDString;
    }

    NSDictionary *params = @{
                             @"allowPush":@(allowPush),
                             @"serverID":Server_ID,//String serverID   -必填项，服务器ID
                             @"clientType":@1,
                             @"loginName":Login_Name,//String loginName  -必填项，用户账号
                             @"deviceToken":devicetoken,//String token      -必填项，设备唯一标识，android端IMEI，ios端token；常规情况下，用于通知推送
                             @"device":@"ios",
                             @"pushToken":devicetoken,//String pushToken  -必填项，设备通知推送token，特殊设备采用该字段推送通知，如华为机型；
                             @"brand":@"Apple",//String brand      -可选项，设备品牌
                             @"model":devicemodel,//String model      -可选项，设备型号
                             @"password":Login_Word,
                             @"serverID":Server_ID,
                             @"version":[NSString stringWithFormat:@"%@-%@",iosversion,appversion]//String version    -可选项，设备系统版本
                             //String uuid       -可选项，请求唯一标识
                             };

    return params;
}

+ (NSString*)DeviceModel{
#warning 2016-09-26-缺失iphone7的model.
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //iPhone 系列
    if ([deviceModel isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
    if ([deviceModel isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([deviceModel isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([deviceModel isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,2"]) return @"Verizon iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([deviceModel isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,3"]) return @"iPhone 5C";
    if ([deviceModel isEqualToString:@"iPhone5,4"]) return @"iPhone 5C";
    if ([deviceModel isEqualToString:@"iPhone6,1"]) return @"iPhone 5S";
    if ([deviceModel isEqualToString:@"iPhone6,2"]) return @"iPhone 5S";
    if ([deviceModel isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([deviceModel isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    return deviceModel;
}


+(UIBarButtonItem*)createRightbarbutton:(NSString*)title target:(id)target sel:(SEL)sel{
//    UIImage* image = [UIImage imageNamed:@"add_friend_clear"];
//    UIImage* image_down = [UIImage imageNamed:@"add_friend_clear_down"];
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    [view setBackgroundColor:[UIColor clearColor]];
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    if(isIOS7)
    {
        [button setFrame:CGRectMake(10, 8, 100, 28)];

    }
    else
    {
        [button setFrame:CGRectMake(0, 8, 100, 28)];
    }
    //设置字体大小
    button.titleLabel.font = [UIFont systemFontOfSize: 16.0];
    //设置标题颜色和状态
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:(double)167/255.0f green:(double)169/255.0f blue:(double)171/255.0f alpha:1] forState:UIControlStateHighlighted];

//    [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
//    [button setBackgroundImage:image forState:UIControlStateNormal];
//    [button setBackgroundImage:image_down forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    //设置点击事件
    [button addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    //设置自定义bt
    UIBarButtonItem* msgLeft = [[UIBarButtonItem alloc] initWithCustomView:view];
    return msgLeft;
}

//创建右btbar的图标和点击事件
+(UIBarButtonItem*)createRightbarbuttonWithIcon:(NSString*)imageName target:(id)target sel:(SEL)sel{
    
    {
        UIImage* image = [UIImage imageNamed:imageName];
//        UIImage* image_down = [UIImage imageNamed:@"add_friend_clear_down"];
        UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
        [view setBackgroundColor:[UIColor clearColor]];
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        if(isIOS7)
        {
            [button setFrame:CGRectMake(40, 8, 50, 30)];
            
        }
        else
        {
            
            [button setFrame:CGRectMake(30, 8, 50, 30)];
            
        }
        button.titleLabel.font = [UIFont systemFontOfSize: 14.0];
        //    [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [button setImage:image forState:UIControlStateNormal];
        //    [button setBackgroundImage:image_down forState:UIControlStateHighlighted];
//        [button setTitle:title forState:UIControlStateNormal];
        [button addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        UIBarButtonItem* msgLeft = [[UIBarButtonItem alloc] initWithCustomView:view];
        return msgLeft;
    }

}

//设备唯一标识
+(NSString*) uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

//创建一个透明的view  将它添加到 footView
+(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

+(void)addBack2Navigationitem:(UINavigationItem*)item sel:(SEL)sel res:(id)res{
//    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    UIButton *backBtn = [[UIButton alloc] init];
    if(isIOS7)
    {
        backBtn.frame=CGRectMake(0, 7, 61, 30);
    }
    else
    {
    
        backBtn.frame=CGRectMake(10, 7, 61, 30);

        
    }
    [backBtn setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
//    [RightBtn setImage:[UIImage imageNamed:@"nav_back_down.png"] forState:UIControlStateHighlighted];
//    [RightBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(5, -80, 5, 5)];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(2, -30, 2, 15)];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn addTarget:res action:sel forControlEvents:UIControlEventTouchUpInside];
//    [view addSubview:RightBtn];
    UIBarButtonItem* left = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    item.leftBarButtonItem = left;
}


+(BOOL)isValidEmail:(NSString*)email{
    
    //Email的验证规则
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilterString ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


#pragma mark -
#pragma mark 等比縮放image

//返回高度一致,不变形的图片.
+ (UIImage *)scaleRigthSizeImageWithTargetView:(UIView *)targetView origionlImage:(UIImage *)origionalImage
{
    CGFloat transX = (targetView.frame.size.height/origionalImage.size.height)*origionalImage.size.width;

    return [self scaleToSize:origionalImage size:CGSizeMake(transX, targetView.frame.size.height)];
    
#warning 2016-11-02 待新增不存在image,生成图片不存在或删除..
}

+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    NSLog(@"%f, %f", image.size.width, image.size.height);
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize, image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

+ (UIImage *)creatImageWithPureColor:(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*theImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    return theImage;
}

+ (CGSize)getSizeFromText:(NSString *)text maxWidth:(CGFloat)maxWidth withFloatFont:(float)floatFont
{
    
    
    return [text stringgetSizebyMaxWidth:maxWidth Font:[UIFont systemFontOfSize:floatFont]];
    

}


+(NSString *)avatarPath
{
    //通过key获取UserDefaults中的用户登录
    return [Utils avatarPathWithUserID:Login_Name];
}

+(NSString *)avatarPathWithLoginName:(NSString *)loginname{
    NSString *loginavatarpaths;
    loginavatarpaths = [Utils avatarPathWithUserID:loginname];
    return loginavatarpaths;
}

+(NSString *)avatarPathWithUserID:(NSString *)userID
{
    //Document是对数据做一个持久化的保存 现在是获取Document
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath=[paths objectAtIndex:0];
    //创建路径地址
    documentPath = [documentPath stringByAppendingPathComponent:@"avatars"];
    //创建文件管理器
    NSFileManager* manager = [NSFileManager defaultManager];
    //判断是否是文件夹
    BOOL isDir;
    BOOL isEx = [manager fileExistsAtPath:documentPath isDirectory:&isDir];
    if (!isEx) {
        //如果不是文件夹 就创建 documentPath 文件
        [manager createDirectoryAtPath:documentPath withIntermediateDirectories:NO attributes:Nil error:nil];
    }
    documentPath = [documentPath stringByAppendingFormat:@"/%@_avatar.jpg",userID];
    //返回文件路径 也就是将用户的ID图片返回
    return documentPath;
}

//图片的下载缓存<头像>
+(void)loadUserAvatar:(UIImageView *)headerImageView imageUrl:(NSString*) imageUrl
{
//    headerImageView.image = DEFAULT_AVATAR;
    headerImageView.image = nil;
    
    [SDWebImageDownloader.sharedDownloader setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
                                 forHTTPHeaderField:@"Accept"];
    [headerImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        NSLog(@"%@",error);
        
        //设置头像
        if (headerImageView.image == nil) {
//            headerImageView.image = DEFAULT_AVATAR;    
            
            
        }
        
    }];
    
    
    
}

+ (void)getPCScreenPhotoAndTextWithExpression:(NSString *)expression content:(NSString *)content resultBlock:(void(^)(NSArray *subData))resultBlock
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    
    NSMutableArray *array3 = [NSMutableArray array];
    
    __block NSRange dealRange = NSMakeRange(0,0);
    
    [regex enumerateMatchesInString:content options:NSMatchingReportCompletion range:NSMakeRange(0, [content length]) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        
        NSMutableArray *arrayx = [NSMutableArray array];
        for (int i = 0; i < [result numberOfRanges]; i++) {
            //以正则中的(),划分成不同的匹配部分
            NSString *component = [content substringWithRange:[result rangeAtIndex:i]];
            dealRange = [result rangeAtIndex:i];
            [arrayx addObject:component];
            
            
        }
        //判断是否到底.
        if (!arrayx.count  && (content.length - (dealRange.length + dealRange.location)) > 0) {
            
            
            for (int j = 0; j < 4 ; j++) {
           
                
                if (j == 1) {
                    NSString *restString = [content substringWithRange:NSMakeRange(dealRange.location + dealRange.length, content.length - (dealRange.location + dealRange.length))];
                    [arrayx addObject:restString];
                }else [arrayx addObject:@""];
                
                
            }
        }
        
        if (arrayx.count) {
            [array3 addObject:arrayx];
        }
        
        
        
    }];
    
    if (resultBlock) {
        resultBlock(array3);
    }

}

//对图片的缓存和存储 使用了SDWebImage的缓存结果
//+(void)loadMyAvatar:(UIImageView *)headerImageView
//{
//    headerImageView.image = DEFAULT_AVATAR;
//    //判断文件夹是否存在 如果不存在  就下载并缓存
//    if (![FileManager fileExistsAtPath:[Utils avatarPath]]){
////        headerImageView.image = DEFAULT_AVATAR;
//        
//        
//        NSString* imageUrl = [LoginModel curLoginUser].avatar;
//        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:imageUrl] options:(SDWebImageDownloaderContinueInBackground) progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
//           
//            if ([data writeToFile:[Utils avatarPath] atomically:YES]) {
//                                //图片从数据中获取
//                                UIImage *avater = [UIImage imageWithData:data];
//                                headerImageView.image = avater;
//            }
//            
//        }];
//    }else{
//        
//        //如果文件夹存在 就直接从文件中获取图片
//        UIImage *avater = [UIImage imageWithContentsOfFile:[Utils avatarPath]];
//        headerImageView.image = avater;
//    }
//    
//}



//+(void)loadMyAvatarWithPath:(UIImageView *)headerImageView :(NSString*)Paths
//{
//    headerImageView.image = DEFAULT_AVATAR;
//    //判断文件夹是否存在 如果不存在  就下载并缓存
//    if (![FileManager fileExistsAtPath:[Utils avatarPath]]) {
//        //        headerImageView.image = DEFAULT_AVATAR;
//        
//        
//        NSString* imageUrl = [LoginModel curLoginUser].avatar;
//        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:imageUrl] options:(SDWebImageDownloaderContinueInBackground) progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
//            
//            if ([data writeToFile:[Utils avatarPath] atomically:YES]) {
//                //图片从数据中获取
//                UIImage *avater = [UIImage imageWithData:data];
//                headerImageView.image = avater;
//            }
//            
//        }];
//    }else{
//        
//        //如果文件夹存在 就直接从文件中获取图片
//        UIImage *avater = [UIImage imageWithContentsOfFile:[Utils avatarPath]];
//        headerImageView.image = avater;
//    }
//    
//}





//压缩图片
+(NSData*)getScaledPhotoData:(UIImage*) theImage
{
    NSData* photoData;
    //将图片进行处理<等比缩放 0.4>
    UIImage *image = [self scaleImage:theImage toScale:0.5];
    //对图片进行JPEG格式的压缩
    photoData = UIImageJPEGRepresentation(image, (CGFloat)0.5);
    
    return photoData;
}

/*
//下一次新增一个直接通过defaultavaer返回image
+ (UIImage *)getDefaultAvatarWithUserUUID:(NSString *)uuid isOffLine:(BOOL)isoffline
{

    
//    AddrBook *addrbook = nil;
    NSArray *userArray = nil;
    //选择自己还是friend

        //
    userArray = [uuid componentsSeparatedByString:@"-"];
  
    
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"serverID==%@ AND loginName==%@",userArray[0],userArray[1]];
    
    AddrBook *addrbook = [AddrBook fetchEntityByLoginName:userArray[1] serverID:userArray[0]];
    
      //数据库被手动删除的情况下。。。
    if (!addrbook) {
        //创建实体对象
        
         addrbook = [[NewMessageModule shareInstance]p_fetchAddrBookForReceivedMessage:uuid];;

    }
    
    if (addrbook.defaultAvatar) {
        //获取默认头像
        NSString *defaultAvatar = addrbook.defaultAvatar;
        NSArray *defaultAvatarArray = [defaultAvatar componentsSeparatedByString:@","];
        
        if (defaultAvatarArray.count == 2) {
            
            addrbook.defaultAvatar = [defaultAvatar substringWithRange:NSMakeRange(0, 1)];
            
        }
        
        int colorNum = [addrbook.defaultAvatar intValue];
        
//        int colorNum = [defaultAvatarArray[0]intValue];
        NSString *lastName = nil;
        
        //过滤空格.
        NSString *disPlayName = [addrbook.disPlayName stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        if (disPlayName.length >= 3) {
            lastName = [disPlayName substringWithRange:NSMakeRange(disPlayName.length - 2, 2)];
        }else lastName = disPlayName;
        
//        NSString *lastName = addrbook.disPlayName;
//        lastName = [lastName stringByAppendingString:[NSString stringWithFormat:@"%@",lastName]];
        
        MyColors *colors = [[MyColors alloc]init];
        
        UIColor *defaultHeaderImageColor = colors.arrayColor[colorNum];
        
        if (isoffline) {
            defaultHeaderImageColor = colors.offlineColors[colorNum];
        }
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSManagedObjectContext *privateContext= [NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]];
            [privateContext MR_saveToPersistentStoreAndWait];
            
        });
        
        return [self createImageByLastName:lastName bgColor:defaultHeaderImageColor];
        
        
    }else
    {
        MyColors *colors = [[MyColors alloc]init];
        
        //创建并存储
        int randomColorCount = arc4random()%(colors.arrayColor.count);
        
        addrbook.defaultAvatar = [NSString stringWithFormat:@"%d",randomColorCount];
        
        UIColor *bgColor = colors.arrayColor[randomColorCount];
        
        if (isoffline) {
            bgColor = colors.offlineColors[randomColorCount];
        }
        
        //对数据是否为空进行判断
//        NSString *checklasName = addrbook.disPlayName;
//        if ([checklasName isEqualToString:@""]) {
//            addrbook.disPlayName = @"空";
//        }
//
//            NSString *lastName = [addrbook.disPlayName substringToIndex:1];
//        
//        if (lastName) {
//            
//            addrbook.defaultAvatar = [NSString stringWithFormat:@"%d,%@",randomColorCount,lastName];
//            
//            [defaultContext MR_saveToPersistentStoreAndWait];
//        }else lastName = @"";
        
        NSString *lastName = nil;
        
        if (addrbook.disPlayName.length >= 3) {
            lastName = [addrbook.disPlayName substringWithRange:NSMakeRange(addrbook.disPlayName.length - 2, 2)];
        }else lastName = addrbook.disPlayName;

        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSManagedObjectContext *privateContext= [NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]];
            [privateContext MR_saveToPersistentStoreAndWait];
            
        });
        
        return [self createImageByLastName:lastName bgColor:bgColor];
        
    }
    
    

 
}
*/
#warning 2016-12-15 待优化.
/*
+ (UIImage *)getGroupHeaderImageWithGroup:(UserGroupObject *)group
{
    
    NSMutableArray *imageViews = [NSMutableArray array];
    
    NSArray *users = nil;
    
    if(group.members.count <= 9)
    {
        users = group.members;
    }else if(group.members.count > 9)
    {
        users = [group.members subarrayWithRange:NSMakeRange(0, 9)];
    }
    
    for (NSDictionary *memberDict in users) {
        
        
        AddrBook *userAddrBook = [[NewMessageModule shareInstance]p_fetchAddrBookForReceivedMessage:[memberDict[@"id"] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",ContentServerID(USERDEFAULT_ContentServer)] withString:@""]];
        //{alias =""; id = "0578+002682BECE10-xxj"; ts = '';}
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:userAddrBook.avatar] placeholderImage:[Utils getDefaultAvatarWithUserUUID:[memberDict[@"id"] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",ContentServerID(USERDEFAULT_ContentServer)] withString:@""] isOffLine:NO]];
        
        [imageViews addObject:imageView];
        
    }
#warning bug2016-10-26 bug之群组头像首次启动有时候不对.解散群组没有被删掉...
    
    UIImageView *canvasView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];

    canvasView.backgroundColor = [UIColor colorWithWhite:0.839 alpha:1.000];
    
    UIImageView *imageView = [[StitchingImage alloc] stitchingOnImageView:canvasView withImageViews:imageViews];
    
    imageView.frame = CGRectMake(0, 0, 60, 60);
    
    return [Utils imageWithView:imageView];
   
}
*/

/*
+ (UIImage *)getGroupHeaderImageWithGroupWithObject:(UserGroupObject *)group
{
    
    NSMutableArray *imageViews = [NSMutableArray array];
    
    NSArray *users = nil;
    
    if(group.members.count <= 9)
    {
        users = group.members;
    }else if(group.members.count > 9)
    {
        users = [group.members subarrayWithRange:NSMakeRange(0, 9)];
    }
    
    for (NSDictionary *memberDict in users) {
        
        
        AddrBook *userAddrBook = [[NewMessageModule shareInstance]p_fetchAddrBookForReceivedMessage:[memberDict[@"id"] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",ContentServerID(USERDEFAULT_ContentServer)] withString:@""]];
        //{alias =""; id = "0578+002682BECE10-xxj"; ts = '';}
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:userAddrBook.avatar] placeholderImage:[Utils getDefaultAvatarWithUserUUID:[memberDict[@"id"] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",ContentServerID(USERDEFAULT_ContentServer)] withString:@""] isOffLine:NO]];
        
        [imageViews addObject:imageView];
        
    }
#warning bug2016-10-26 bug之群组头像首次启动有时候不对.解散群组没有被删掉...
    
    UIImageView *canvasView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    
    canvasView.backgroundColor = [UIColor colorWithWhite:0.839 alpha:1.000];
    
    UIImageView *imageView = [[StitchingImage alloc] stitchingOnImageView:canvasView withImageViews:imageViews];
    
    imageView.frame = CGRectMake(0, 0, 60, 60);
    
    return [Utils imageWithView:imageView];
    
}
*/

/*
+ (UIImageView *)getGroupHeaderImageViewWithGroupWithObject:(UserGroupObject *)group
{
    NSMutableArray *imageViews = [NSMutableArray array];
    
    NSArray *users = nil;
    
    if(group.members.count <= 9)
    {
        users = group.members;
    }else if(group.members.count > 9)
    {
        users = [group.members subarrayWithRange:NSMakeRange(0, 9)];
    }
    
    for (NSDictionary *memberDict in users) {
        
        
        AddrBook *userAddrBook = [[NewMessageModule shareInstance]p_fetchAddrBookForReceivedMessage:[memberDict[@"id"] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",ContentServerID(USERDEFAULT_ContentServer)] withString:@""]];
        //{alias =""; id = "0578+002682BECE10-xxj"; ts = '';}
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:userAddrBook.avatar] placeholderImage:[Utils getDefaultAvatarWithUserUUID:[memberDict[@"id"] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",ContentServerID(USERDEFAULT_ContentServer)] withString:@""] isOffLine:NO]];
        
        [imageViews addObject:imageView];
        
    }
#warning bug2016-10-26 bug之群组头像首次启动有时候不对.解散群组没有被删掉...
    
    UIImageView *canvasView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    
    canvasView.backgroundColor = [UIColor colorWithWhite:0.839 alpha:1.000];
    
    UIImageView *imageView = [[StitchingImage alloc] stitchingOnImageView:canvasView withImageViews:imageViews];
    
    imageView.frame = CGRectMake(0, 0, 60, 60);
    
    return imageView;
}

 */
+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

//合并文字和image.
+ (UIImage *)createImageByLastName:(NSString *)lastName bgColor:(UIColor *)Color
{
    UIImage *image = [MyColors createImageWithColor:Color];
    //    image.size = CGSizeMake(HEAD_SIZE, HEAD_SIZE);
    
    CGFloat w = image.size.width;
    CGFloat h = image.size.height;
    //
    CGSize size= CGSizeMake (w , h ); // 画布大小
    
    UIGraphicsBeginImageContextWithOptions (size, NO , 0.0 );
    
    [image drawAtPoint : CGPointMake ( 0 , 0 )];
    
    // 获得一个位图图形上下文
    
    CGContextRef context= UIGraphicsGetCurrentContext ();
    
    CGContextDrawPath (context, kCGPathStroke );
    
    CGSize lastNameSize = [lastName sizeWithFont:[UIFont systemFontOfSize:14]];
    
    // 30 , image. size . height * 0.65
    [lastName drawAtPoint : CGPointMake ( w/2.0f - lastNameSize.width/2.0f, h/2.0f - lastNameSize.height/2.0f) withAttributes : @{ NSFontAttributeName :[ UIFont systemFontOfSize:14], NSForegroundColorAttributeName :[ UIColor whiteColor ] } ];
    
    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext ();
    
    UIGraphicsEndImageContext ();
    
    return newImage;
    
}

+ (void) netWorkType:(void(^)(AFNetworkReachabilityStatus status))success_block fail:(void(^)())fail_block
{
    [[AFNetworkReachabilityManager sharedManager]startMonitoring];
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if(status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            success_block(status);
        }else fail_block();
        
        [[AFNetworkReachabilityManager sharedManager]stopMonitoring];
    }];
    
}

+ (BOOL)isEnableNetWork
{
    return ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus] != NotReachable);
}

+ (NSMutableArray *)sortArray:(NSMutableArray *)orinalArray FromIndex:(NSUInteger)fromIndex ToIndex:(NSUInteger)toIndex
{
    //冒泡排序法
    return nil;
}

+ (NSString *)getIconWithFileName:(NSString *)fileName
{
    
    NSArray *fileTypeArray = [fileName componentsSeparatedByString:@"."];
    NSString *fileType = nil;
    if (fileTypeArray.count >= 2) {
        //
        fileType = fileTypeArray[fileTypeArray.count - 1];
        
        if ([fileType isEqualToString:@"doc"] || [fileType isEqualToString:@"docx"] || [fileType isEqualToString:@"DOC"] || [fileType isEqualToString:@"DOCX"]) {
            fileType = @"doc_file";
        }else if ([fileType isEqualToString:@"mp3"] || [fileType isEqualToString:@"wav"] || [fileType isEqualToString:@"amr"]||[fileType isEqualToString:@"MP3"] || [fileType isEqualToString:@"WAV"] || [fileType isEqualToString:@"AMR"])
        {
            fileType = @"mp3_file";
        }else if ([fileType isEqualToString:@
                   "vedio"] || [fileType isEqualToString:@"mp4"] || [fileType isEqualToString:@"avi"] || [fileType isEqualToString:@"wmv"] || [fileType isEqualToString:@"mov"]||[fileType isEqualToString:@"MP4"] || [fileType isEqualToString:@"AVI"] || [fileType isEqualToString:@"WMV"] || [fileType isEqualToString:@"MOV"])
        {
            fileType = @"vedio_file";
        }else if ([fileType isEqualToString:@"zip"]||[fileType isEqualToString:@"rar"]||[fileType isEqualToString:@"ZIP"]||[fileType isEqualToString:@"RAR"])
        {
            fileType = @"zip_file";
        }else if ([fileType isEqualToString:@"xlsx"] || [fileType isEqualToString:@"xls"]||[fileType isEqualToString:@"XLSX"] || [fileType isEqualToString:@"XLS"])
        {
            fileType = @"xlsx_file";
        }else if ([fileType isEqualToString:@"txt"]||[fileType isEqualToString:@"TXT"])
        {
            fileType = @"txt_file";
        }else if([fileType isEqualToString:@"pptx"] || [fileType isEqualToString:@"ppt"] || [fileType isEqualToString:@"pdf"]||[fileType isEqualToString:@"PPTX"] || [fileType isEqualToString:@"PPT"] || [fileType isEqualToString:@"PDF"])
        {
            fileType = @"pptx_file";
        }else{
            fileType = @"unknow_file";
        }
        
    }else fileType = @"unknow_file";
    
    return fileType;
    
}

+ (void)showSuccessToView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    [MBProgressHUD showSuccess:nil toView:view];
    
}

+ (void)showFailureToView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    [MBProgressHUD showError:@"失败" toView:view];
}

+ (void)showError:(NSString *)error toView:(UIView *)view finish:(void(^)())block
{
    [MBProgressHUD hideHUDForView:view animated:NO];;
    [MBProgressHUD showError:error toView:view];
    CGFloat delayTime = MIN((float)error.length*0.06 + 0.5, 5.0);
    if (block) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            block();
        });
    }
    
}

+ (void)showSuccess:(NSString *)success toView:(UIView *)view finish:(void(^)())block
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    [MBProgressHUD showSuccess:success toView:view];
    CGFloat delayTime = MIN((float)success.length*0.06 + 0.5, 5.0);
    if (block) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            block();
        });
    }
    
}

+ (void)showError:(NSString *)error ToView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    [MBProgressHUD showError:error toView:view];
}

+ (void)showWaitingToView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    [MBProgressHUD showMessag:nil toView:view];
}

+ (void)showWaitingWithMessage:(NSString *)message ToView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    [MBProgressHUD showMessag:message toView:view];
}

+ (void)HiddenWaitingToView:(UIView *)view
{
  
    [MBProgressHUD hideHUDForView:view animated:YES];
}

@end
