//
//  Tools.m
//  MIMI
//
//  Created by Liu on 14-7-14.
//  Copyright (c) 2014年 wangjun. All rights reserved.
//

#import "Tools.h"

const double a = 6378245.0;
const double ee = 0.00669342162296594323;
const double pi = 3.14159265358979324;

@implementation Tools
//判断字母数字
+ (BOOL)IsNumber:(NSString *)number
{
    //是否字母数字
    NSString *miaoNumRegex =@"^[a-zA-Z0-9_]+$";
    NSPredicate *passTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",miaoNumRegex];
    return [passTest evaluateWithObject:number];
}

//判断喵喵号格式
+ (BOOL)isValidateMiaoMiao:(NSString *)miaoNum
{
    //字母开头,长度在5-20之间,只能包含字母、数字和下划线!
    NSString *miaoNumRegex =@"^[a-zA-Z][a-zA-Z0-9_]{5,19}$";
    NSPredicate *passTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",miaoNumRegex];
    return [passTest evaluateWithObject:miaoNum];
}
//MIMI密码格式
+ (BOOL)passWord:(NSString *)str
{
    //(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,16}//((?=.*?\\d)(?=.*?[A-Za-z])|(?=.*?\\d)(?=.*?[!@#$%^&])|(?=.*?[A-Za-z])(?=.*?[!@#$%^&]))[\\dA-Za-z!@#$%^&]{6,16}$
    
    //特殊字符判断
    //    NSString *regex = @"^[A-Za-z0-9_]+$";
    NSString *regex = @"^((?=.*?\\d)(?=.*?[A-Za-z])|(?=.*?\\d)(?=.*?[!@#$%^&])|(?=.*?[A-Za-z])(?=.*?[!@#$%^&]))[\\dA-Za-z!@#$%^&]{6,16}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    //    if ([predicate evaluateWithObject:str] == NO) {
    //        return NO;
    //    }
    
    return [predicate evaluateWithObject:str];
    
}

//QQ号,腾讯QQ号从10000开始
+ (BOOL)isQQnum:(NSString *)qqstr
{
    NSString *qqCheck = @"[1-9][0-9]{4,}";
    NSPredicate *qqTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",qqCheck];
    return [qqTest evaluateWithObject:qqstr];
}

//微信号
+ (BOOL)isWXnum:(NSString *)wxstr
{
    //    NSString *wxCheck = @"^[a-zA-Z\\d_]{5,}$";
    //字母开头,长度在6-20之间,只能包含字母、数字和下划线和减号!
    NSString *wxCheck =@"^[a-zA-Z][a-zA-Z0-9_-]{5,19}$";
    NSPredicate *wxTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",wxCheck];
    return [wxTest evaluateWithObject:wxstr];
}

// 判断邮箱是否正确
+ (BOOL)isValidateEmail:(NSString *)Email
{
    NSString *emailCheck = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailCheck];
    return [emailTest evaluateWithObject:Email];
}

//身份证号
+ (BOOL)validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
    
    /*
     NSString *pattern = @(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$);
     NSPredicate *pred = [NSPredicate predicateWithFormat:@SELF MATCHES %@, pattern];
     BOOL isMatch = [pred evaluateWithObject:idCard];
     */
}

//出生证..不知道正不正确。网上找的
+ (BOOL)validateBirthidCard: (NSString *)identityCard
{
    NSString *emailCheck = @"^[a-zA-Z0-9]{5,21}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailCheck];
    return [emailTest evaluateWithObject:identityCard];
}

//// 正则判断手机号码地址格式
+(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[1278])\\d)\\d{7}$";
    //     NSString *CM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\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}$";
    //    NSString *CU = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //    /**
    //     20         * 中国电信：China Telecom
    //     21         * 133,1349,153,180,189
    //     22         */
    ////    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    //    NSString *CT = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    //    /**
    //     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;
    //    }
    
    //新版
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    
    
    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;
    }
}

// 正则判断电话号码地址格式,固话
+(BOOL)isTelePhone:(NSString *)telePhoneNum
{
    /**
     * 手机号码
     * 移动：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}$";
    NSString * PHS = @"^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$";
    //    NSString * PHS = @"^(\\b0[1-2]\\d-\\d{8}(-\\d{1,4})?\\b)|(\\b0\\d{3}-\\d{7,8}(-\\d{1,4})?\\b)$";
    //    NSString * PHS = @"^(0?1[358]\\d{9})|((0(10|2[1-3]|[3-9]\\d{2}))?[1-9]\\d{6,7})$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:telePhoneNum] == YES)
        ||([regextestphs evaluateWithObject:telePhoneNum] == YES)
        || ([regextestcm evaluateWithObject:telePhoneNum] == YES)
        || ([regextestct evaluateWithObject:telePhoneNum] == YES)
        || ([regextestcu evaluateWithObject:telePhoneNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


#pragma mark - 计算文本宽高 -
//计算宽度
+ (CGFloat)getTheStringWidth:(NSString *)string setFont:(CGFloat)font
{
    NSMutableAttributedString  *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = NSMakeRange(0, attrStr.length);     //设置字体
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:font]
                    range:range];
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];   // 获取该段attributedString
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return textSize.width;
}
//计算高度
+ (CGFloat)getTheStringHeight:(NSString *)string setFont:(CGFloat)font width:(CGFloat)width
{
    NSMutableAttributedString  *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = NSMakeRange(0, attrStr.length);     //设置字体
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:font]
                    range:range];
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];   // 获取该段attributedString
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return textSize.height;
}

#pragma mark - 图片
+(UIImage *)setImgName:(NSString *)name {
    UIImage *img = [UIImage imageNamed:name];
    img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}
//+(CGSize)getSize:(NSString *)str widthSize:(CGFloat)width FontOfSize:(CGFloat)fontSize
//{
//    CGSize requiredSize;
//    if ([str respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
//        CGRect rect = [str boundingRectWithSize:(CGSize){width, MAXFLOAT}
//                                        options:NSStringDrawingUsesLineFragmentOrigin
//                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}
//                                        context:nil];
//        requiredSize = rect.size;
//
//    } else {
//
//        requiredSize = [str sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:(CGSize){width, MAXFLOAT} lineBreakMode:NSLineBreakByWordWrapping];
//    }
//
//    return requiredSize;
//}
//
//+(CGSize)getSize:(NSString *)str widthSize:(CGFloat)width FontOfBSize:(CGFloat)fontSize
//{
//    CGSize requiredSize;
//    if ([str respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
//        CGRect rect = [str boundingRectWithSize:(CGSize){width, MAXFLOAT}
//                                        options:NSStringDrawingUsesLineFragmentOrigin
//                                     attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize]}
//                                        context:nil];
//        requiredSize = rect.size;
//
//    } else {
//
//        requiredSize = [str sizeWithFont:[UIFont boldSystemFontOfSize:fontSize] constrainedToSize:(CGSize){width, MAXFLOAT} lineBreakMode:NSLineBreakByWordWrapping];
//    }
//
//    return requiredSize;
//}
//
//
//#pragma mark 图片压缩
//+ (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withImage:(UIImage*)selectedImage
//{
//    //方法1
////    CGFloat scaxy=1.0;
////    CGSize imageSize = selectedImage.size;
////    CGFloat targetWidth = targetSize.width;
////    CGFloat targetHeight = targetSize.height;
////
////    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
////    {
////        CGFloat scax = targetWidth / imageSize.width;
////        CGFloat scay =  targetHeight / imageSize.height;
////        if (scax > scay)
////        {
////            scaxy = scay;
////        }
////        else
////        {
////            scaxy = scax;
////        }
////    }
////
////    CGFloat scaledWidth = selectedImage.size.width * scaxy;
////    CGFloat scaledHeight = selectedImage.size.height *scaxy;
////
//////    UIGraphicsBeginImageContext(CGSizeMake(selectedImage.size.width * scaxy, selectedImage.size.height *scaxy));
////    UIGraphicsBeginImageContext(CGSizeMake(scaledWidth, scaledHeight));
////    // Tell the old image to draw in this new context, with the desired// new size
//////    [selectedImage drawInRect:CGRectMake(0,0,selectedImage.size.width * scaxy, selectedImage.size.height *scaxy)];
////
////    CGRect thumbnailRect = CGRectZero;
////    thumbnailRect.origin = CGPointMake(0.0, 0.0);
////    thumbnailRect.size.width = scaledWidth;
////    thumbnailRect.size.height = scaledHeight;
////
////    CGContextRef context = UIGraphicsGetCurrentContext();
////    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
////    UIRectFill(CGRectMake(0, 0, targetWidth, targetHeight));//clear background
////
////    [selectedImage drawInRect:thumbnailRect];
////
////    UIImage    *newImage = UIGraphicsGetImageFromCurrentImageContext();
////    UIGraphicsEndImageContext();
//
//    //方法2
//        CGFloat scaxy=1.0;
//        const int maxW = targetSize.width, maxH = targetSize.height;
//        if (selectedImage.size.height>maxH && selectedImage.size.width >maxW)
//        {
//            CGFloat scax = maxH/selectedImage.size.width;
//            CGFloat scay = maxW/selectedImage.size.height;
//            if (scax > scay)
//            {
//                scaxy = scay;
//            }
//            else
//            {
//                scaxy = scax;
//            }
//        }
//        UIGraphicsBeginImageContext(CGSizeMake(selectedImage.size.width * scaxy, selectedImage.size.height *scaxy));
//        // Tell the old image to draw in this new context, with the desired// new size
//        [selectedImage drawInRect:CGRectMake(0,0,selectedImage.size.width * scaxy, selectedImage.size.height *scaxy)];
//        UIImage    *newImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//
////  方法3
////    //    UIImage *selectedImage = self;
////    UIImage *newImage = nil;
////    CGSize imageSize = selectedImage.size;
////    CGFloat width = imageSize.width;
////    CGFloat height = imageSize.height;
////    CGFloat targetWidth = targetSize.width;
////    CGFloat targetHeight = targetSize.height;
////    CGFloat scaleFactor = 0.0;
////    CGFloat scaledWidth = targetWidth;
////    CGFloat scaledHeight = targetHeight;
//////    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
////
////    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
////    {
////        CGFloat widthFactor = targetWidth / width;
////        CGFloat heightFactor = targetHeight / height;
////
////        if (widthFactor > heightFactor)
////            scaleFactor = widthFactor; // scale to fit height
////        else
////            scaleFactor = heightFactor; // scale to fit width
////        scaledWidth  = width * scaleFactor;
////        scaledHeight = height * scaleFactor;
////
////        // center the image 裁剪中间
//////        if (widthFactor > heightFactor)
//////        {
//////            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
//////        }
//////        else
//////            if (widthFactor < heightFactor)
//////            {
//////                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
//////            }
////    }
////
//////    UIGraphicsBeginImageContext(targetSize); // this will crop
////     UIGraphicsBeginImageContext(CGSizeMake(scaledWidth, scaledHeight)); // this will crop
////
////    CGRect thumbnailRect = CGRectZero;
//////    thumbnailRect.origin = thumbnailPoint;
////    thumbnailRect.size.width  = scaledWidth;
////    thumbnailRect.size.height = scaledHeight;
////
////    [selectedImage drawInRect:thumbnailRect];
////
////    newImage = UIGraphicsGetImageFromCurrentImageContext();
////    if(newImage == nil)
////        NSLog(@"could not scale image");
////
////    //pop the context to get back to the default
////    UIGraphicsEndImageContext();
//    return newImage;
//}
//
//+(UIImage *)scaleAndRotateImage:(UIImage *)image resolution:(int)kMaxResolution{
//    CGImageRef imgRef = image.CGImage;
//    CGFloat width = CGImageGetWidth(imgRef);
//    CGFloat height = CGImageGetHeight(imgRef);
//
//    CGAffineTransform transform = CGAffineTransformIdentity;
//    CGRect bounds = CGRectMake(0, 0, width, height);
//    if (width > kMaxResolution || height > kMaxResolution) {
//        CGFloat ratio = width/height;
//        if (ratio > 1) {
//            bounds.size.width = kMaxResolution;
//            bounds.size.height = bounds.size.width / ratio;
//        } else {
//            bounds.size.height = kMaxResolution;
//            bounds.size.width = bounds.size.height * ratio;
//        }
//    }
//
//    CGFloat scaleRatio = bounds.size.width / width;
//    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
//    CGFloat boundHeight;
//
//    UIImageOrientation orient = image.imageOrientation;
//    switch(orient) {
//        case UIImageOrientationUp:
//            transform = CGAffineTransformIdentity;
//            break;
//        case UIImageOrientationUpMirrored:
//            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
//            transform = CGAffineTransformScale(transform, -1.0, 1.0);
//            break;
//        case UIImageOrientationDown:
//            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
//            transform = CGAffineTransformRotate(transform, M_PI);
//            break;
//        case UIImageOrientationDownMirrored:
//            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
//            transform = CGAffineTransformScale(transform, 1.0, -1.0);
//            break;
//        case UIImageOrientationLeftMirrored:
//            boundHeight = bounds.size.height;
//            bounds.size.height = bounds.size.width;
//            bounds.size.width = boundHeight;
//            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
//            transform = CGAffineTransformScale(transform, -1.0, 1.0);
//            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
//            break;
//        case UIImageOrientationLeft:
//            boundHeight = bounds.size.height;
//            bounds.size.height = bounds.size.width;
//            bounds.size.width = boundHeight;
//            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
//            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
//            break;
//        case UIImageOrientationRightMirrored:
//            boundHeight = bounds.size.height;
//            bounds.size.height = bounds.size.width;
//            bounds.size.width = boundHeight;
//            transform = CGAffineTransformMakeScale(-1.0, 1.0);
//            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
//            break;
//        case UIImageOrientationRight:
//            boundHeight = bounds.size.height;
//            bounds.size.height = bounds.size.width;
//            bounds.size.width = boundHeight;
//            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
//            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
//            break;
//        default:
//            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
//    }
//
//    UIGraphicsBeginImageContext(CGSizeMake(floorf(bounds.size.width), floorf(bounds.size.height)));
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
//        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
//        CGContextTranslateCTM(context, -height, 0);
//    } else {
//        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
//        CGContextTranslateCTM(context, 0, -height);
//    }
//    CGContextConcatCTM(context, transform);
//
//    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, floorf(width), floorf(height)), imgRef);
//    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return imageCopy;
//}

//系统定位的坐标偏移优化
+(CLLocationCoordinate2D)transformFromWGSToGCJ:(CLLocationCoordinate2D)wgsLoc
{
    CLLocationCoordinate2D adjustLoc;
    if([self isLocationOutOfChina:wgsLoc]){
        adjustLoc = wgsLoc;
    }else{
        double adjustLat = [self transformLatWithX:wgsLoc.longitude - 105.0 withY:wgsLoc.latitude - 35.0];
        double adjustLon = [self transformLonWithX:wgsLoc.longitude - 105.0 withY:wgsLoc.latitude - 35.0];
        double radLat = wgsLoc.latitude / 180.0 * pi;
        double magic = sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = sqrt(magic);
        adjustLat = (adjustLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        adjustLon = (adjustLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi);
        adjustLoc.latitude = wgsLoc.latitude + adjustLat;
        adjustLoc.longitude = wgsLoc.longitude + adjustLon;
    }
    return adjustLoc;
}

//判断是不是在中国
+(BOOL)isLocationOutOfChina:(CLLocationCoordinate2D)location
{
    if (location.longitude < 72.004 || location.longitude > 137.8347 || location.latitude < 0.8293 || location.latitude > 55.8271)
        return YES;
    return NO;
}

//坐标转换
const double x_pi2 = 3.14159265358979324 * 3000.0 / 180.0;
//百度坐标转火星
+(CLLocationCoordinate2D)bd_g_decrypt:(CLLocationCoordinate2D)wgsLoc
{
    CLLocationCoordinate2D adjustLoc;
    double x = wgsLoc.longitude - 0.0065, y = wgsLoc.latitude - 0.006;
    double z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi2);
    double theta = atan2(y, x) - 0.000003 * cos(x * x_pi2);
    adjustLoc.longitude = z * cos(theta);
    adjustLoc.latitude = z * sin(theta);
    return adjustLoc;
}
//火星转百度坐标
+(CLLocationCoordinate2D)bd_g_encrypt:(CLLocationCoordinate2D)wgsLoc
{
    CLLocationCoordinate2D adjustLoc;
    double x = wgsLoc.longitude, y = wgsLoc.latitude;
    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi2);
    double theta = atan2(y, x) + 0.000003 * cos(x * x_pi2);
    adjustLoc.longitude = z * cos(theta) + 0.0065;
    adjustLoc.latitude = z * sin(theta) + 0.006;
    return adjustLoc;
}


+(double)transformLatWithX:(double)x withY:(double)y
{
    double lat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x));
    lat += (20.0 * sin(6.0 * x * pi) + 20.0 *sin(2.0 * x * pi)) * 2.0 / 3.0;
    lat += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0;
    lat += (160.0 * sin(y / 12.0 * pi) + 3320 * sin(y * pi / 30.0)) * 2.0 / 3.0;
    return lat;
}

+(double)transformLonWithX:(double)x withY:(double)y
{
    double lon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x));
    lon += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
    lon += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0;
    lon += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0;
    return lon;
}

//时间转化成时间戳
+ (NSString *)dateTotimewithd:(NSString *)dates formatStr:(NSString *)formatstr{
    NSDateFormatter *dateformat=[[NSDateFormatter  alloc] init];
    [dateformat setDateFormat:formatstr];//@"yyyy-MM-dd HH:mm"];
    
    NSLocale *lcoao = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateformat setLocale:lcoao];
    NSDate *deta = [dateformat dateFromString:dates];
    
    NSString *sendtimeme = [NSString stringWithFormat:@"%lld",(long long)[deta timeIntervalSince1970]];
    
    lcoao = nil;
    deta = nil;
    dateformat = nil;
    
    return sendtimeme;
}

#pragma mark - 剩余时间计算
+(NSString *)dateStr:(NSString *)timeStr
{
    //计算时间，先取当前时间然后比较
    //获取当前时间
    NSDate * nowDate = [NSDate date];
    //    NSLog(@"---Now---- %@",nowDate);
    
    //    NSLog(@"---后台---- %@",date);
    NSTimeInterval backDate = [timeStr longLongValue]*1000;
    //    int nowdate = [[NSString stringWithFormat:@"%ld",(long)[nowDate timeIntervalSince1970]] intValue];
    NSTimeInterval nowdate =  [[NSString stringWithFormat:@"%lld", (long long)[nowDate timeIntervalSince1970]*1000] longLongValue];
    //    NSLog(@"%d,%d",backDate,nowdate);
    
    int cha = (backDate - nowdate)/1000;
    //    NSLog(@" 差值  %d",cha);
    int day = cha / ( 60 * 60 * 24);
    //    NSLog(@" 日 %d",day);
    int hour = (cha / (60 * 60) - day * 24);
    //    NSLog(@" 小时 %d",hour);
    int minute = (cha / 60 - day * 24 * 60 - hour * 60);
    //    NSLog(@" 分钟 %d",minute);
    
    if (day < 1)
    {
        if (hour < 1)
        {
            if (minute < 1)
            {
                //                return [[NSString stringWithFormat:@"%d",0] stringByAppendingString:@""];
                //停止计时
                //                return [[NSString stringWithFormat:@"%d",0] stringByAppendingString:@"分钟"];
                return nil;
            }
            else
            {
                return [[NSString stringWithFormat:@"%d",minute] stringByAppendingString:@"分钟"];
            }
            
        }
        else
        {
            return [NSString stringWithFormat:@"%d小时%d分钟",hour,minute];
        }
    }
    else
    {
        return [NSString stringWithFormat:@"%d天%d小时%d分钟",day,hour,minute];
    }
    return nil;
}


//count down倒计时
//time  :   倒计时间
//-(NSString *)setCountDown_WhatTime:(NSInteger)time{
//    
//    //计算时间，先取当前时间然后比较
//    //获取当前时间
//    NSDate * nowDate = [NSDate date];
//    
//    
//}


/**
 /////  和当前时间比较
 ////   1）1分钟以内 显示        :    刚刚
 ////   2）1小时以内 显示        :    X分钟前
 ///    3）今天或者昨天 显示      :    今天 09:30   昨天 09:30
 ///    4) 今年显示              :   09月12日
 ///    5) 大于本年      显示    :    2013/09/09
 **/

+ (NSString *)formateDate:(NSString *)dateString withFormate:(NSString *) formate
{
    
    @try {
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:formate];
        
        NSDate * nowDate = [NSDate date];
        
        /////  将需要转换的时间转换成 NSDate 对象
        NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
        /////  取当前时间和转换时间两个日期对象的时间间隔
        /////  这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:  typedef double NSTimeInterval;
        NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
        
        //// 再然后，把间隔的秒数折算成天数和小时数：
        
        NSString *dateStr = @"";
        
        if (time<=60) {  //// 1分钟以内的
            dateStr = @"刚刚";
        }else if(time<=60*60){  ////  一个小时以内的
            
            int mins = time/60;
            dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
            
        }else if(time<=60*60*24*2){   //// 在两天内的
            
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
            NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
            
            [dateFormatter setDateFormat:@"HH:mm"];
            if ([need_yMd isEqualToString:now_yMd]) {
                //// 在同一天
                dateStr = [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }else{
                ////  昨天
                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }
        }else {
            
            [dateFormatter setDateFormat:@"yyyy"];
            NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
            NSString *nowYear = [dateFormatter stringFromDate:nowDate];
            
            if ([yearStr isEqualToString:nowYear]) {
                ////  在同一年
                [dateFormatter setDateFormat:@"MM-dd HH:mm"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }else{
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }
        }
        
        return dateStr;
    }
    @catch (NSException *exception) {
        return @"";
    }
    
    
}

//定位判断
+(BOOL)checkLocationState:(UIViewController *)currentViewController
{
    if(![CLLocationManager locationServicesEnabled]){
        NSLog(@"请开启定位:设置 > 隐私 > 位置 > 定位服务");
        return NO;
    }else{
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
        //        if (status != kCLAuthorizationStatusAuthorized) {
        //            NSLog(@"定位失败，请开启定位:设置 > 隐私 > 位置 > 定位服务 下 XX应用1111");
        //            return NO;
        //        }
        if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
            NSLog(@"定位失败，请开启定位:设置 > 隐私 > 位置 > 定位服务 下 XX应用2222");
            //            [self settingDingWei:currentViewController];
            //手动设置允许定位
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"同城乐购需要访问您的定位服务"
                                                                           message:@"点击“设置”前往系统设置允许同城乐购使用定位服务"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel
                                                                 handler:^(UIAlertAction * action) {
                //重置？？
            }];
            
            [alert addAction:cancelAction];
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDestructive
                                                                  handler:^(UIAlertAction * action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    //如果点击打开的话，需要记录当前的状态，从设置回到应用的时候会用到
                    [[UIApplication sharedApplication] openURL:url];
                }
                
                
            }];
            [alert addAction:defaultAction];
            [currentViewController presentViewController:alert animated:YES completion:nil];
            
            return NO;
        }
        
        if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusNotDetermined) {
            //定位功能可用，开始定位
            NSLog(@"定位可用");
            return YES;
        }
    }
    
    return NO;
}


//+(void)shareActionIconImgUrl:(NSString *)iconUrl Title:(NSString *)title Content:(NSString *)content MainUrl:(NSString *)mainUrl{
//    //1、创建分享参数
//    
//    NSArray* imageArray = @[iconUrl];
//    //（注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数http://mob.com/Assets/images///logo.png?v=20150320 images:@[@""]）
//    if (imageArray) {
//        
//        
//        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
//        [shareParams SSDKSetupShareParamsByText:content
//                                         images:imageArray
//                                            url:[NSURL URLWithString:[NSString stringWithFormat:@"%@",mainUrl]]
//                                          title:title
//                                           type:SSDKContentTypeAuto];
//        //2、分享（可以弹出我们的分享菜单和编辑界面）
//        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
//                                 items:nil
//                           shareParams:shareParams
//                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
//                       
//                       switch (state) {
//                           case SSDKResponseStateSuccess:
//                           {
//                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
//                                                                                   message:nil
//                                                                                  delegate:nil
//                                                                         cancelButtonTitle:@"确定"
//                                                                         otherButtonTitles:nil];
//                               [alertView show];
//                               break;
//                           }
//                           case SSDKResponseStateFail:
//                           {
//                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                               message:[NSString stringWithFormat:@"%@",error]
//                                                                              delegate:nil
//                                                                     cancelButtonTitle:@"OK"
//                                                                     otherButtonTitles:nil, nil];
//                               [alert show];
//                               break;
//                           }
//                           default:
//                               break;
//                       }
//                   }
//         ];}
//    
//    
//    
//    
//}

//时间戳转时间
+(NSString *)timestamp_timeOrType:(NSString *)type Timestamp:(NSString *)timestamp{
    //时间戳转时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:type];
    NSString *timeStr = [NSString stringWithFormat:@"%@",timestamp];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStr integerValue]];
    
    NSString *nowtimeStr = [formatter stringFromDate:date];
    return nowtimeStr;
}

// 登录成功保存用户数据
+ (BOOL)saveUserSource:(NSDictionary *)dict {
    NSArray *arr  = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [arr objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingString:@"/user.plist"];
    BOOL result = [dict writeToFile:path atomically:YES];
    
    return result;
}

// 删除用户数据
+ (BOOL)removeUserSource {
    NSArray *arr  = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [arr objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingString:@"/user.plist"];
    NSFileManager *fileMger = [NSFileManager defaultManager];
    //如果文件路径存在的话
    BOOL bRet = [fileMger fileExistsAtPath:path];
    BOOL result = NO;
    if (bRet) {
        NSError *err;
        result = [fileMger removeItemAtPath:path error:&err];
    }
    return result;
}

+ (NSDictionary *)getUserDict {
    NSArray *arr  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [arr objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingString:@"/user.plist"];
    NSDictionary *userDic = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    if (!userDic) {
        return nil;
    }
    return userDic;
}

+ (BOOL)savePlistForDocumentWithData:(id)data name:(NSString *)fileName dataType:(ToolsFileType)type {
    NSArray *arr  = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [arr objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingString:fileName];
    BOOL result;
    if (type == NSPrivateModelType) {
        // 保存自定义的model
        result = [NSKeyedArchiver archiveRootObject:data toFile:path];
    }else {
        result = [data writeToFile:path atomically:YES];
    }
    return result;
}

+ (id)getPlistDataFromDocumentWithFileName:(NSString *)fileName dataType:(ToolsFileType)type {
    NSArray *arr  = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [arr objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingString:fileName];
    id value;
    if (type == NSArrayType) {
        value = [NSArray arrayWithContentsOfFile:path];
    }else if (type == NSDictionaryType) {
        value = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    }else {
        value = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    }
    // 娶不到值返回nil
    if (!value) {
        return nil;
    }
    return value;
}

+ (BOOL)removePlistDataForDocumentWithPath:(NSString *)fileName {
    NSArray *arr  = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [arr objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingString:fileName];
    NSFileManager *fileMger = [NSFileManager defaultManager];
    //如果文件路径存在的话
    BOOL bRet = [fileMger fileExistsAtPath:path];
    BOOL result = NO;
    if (bRet) {
        NSError *err;
        result = [fileMger removeItemAtPath:path error:&err];
    }
    return result;
}

+ (UIViewController *)getCurrentViewController:(UIView *)view {
    UIResponder *next = [view nextResponder];
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next != nil);
    return nil;
}

/*
 *  判断用户输入的密码是否符合规范，符合规范的密码要求：
 1. 长度大于6位(小于20位)
 2. 密码中必须同时包含数字和字母
 */
+ (BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

/*
 *  弹出一个alertView
 */
+ (void)showAlertViewWithTitle:(NSString *)title content:(NSString *)content {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:content delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
    [alertView show];
}

/**
 *  设置viewController的返回title
 */
+ (void)setViewControllerBackTitle:(NSString *)title controller:(UIViewController *)viewC navigation:(UINavigationController *)navController{
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] init];
    backBarButtonItem.title = title;
    viewC.navigationItem.backBarButtonItem = backBarButtonItem;
}


+ (BOOL)blankString:(NSString*)str{
    if (![str isKindOfClass:[NSString class]] ){
        return  YES;
    }
    if ([str isEqual:[NSNull null]]){
        return  YES;
    }
    if (str == NULL || [str isEqual:nil] || [str isEqual:Nil] || self == nil){
        return  YES;
    }
    if([str isEqualToString:@"(null)"]){
        return  YES;
    }
    if([str isEqualToString:@"<null>"]){
        return  YES;
    }
    if (str.length == 0 || [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
        return  YES;
    }
    return NO;
}


@end
