//
//  NSString+Category.m
//  SharedParking
//
//  Created by gui_huan on 2018/4/16.
//  Copyright © 2018年 gui_huan. All rights reserved.
//

#import "NSString+Category.h"
#import <objc/runtime.h>
@implementation NSString (Category)
static char *MoneyConversion = "moneyConversion";

- (CGSize)stringSizeWithFont:(UIFont *)font Size:(CGSize)size
{
    CGSize resultSize;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7) {
        //段落样式
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineBreakMode = NSLineBreakByWordWrapping;
        
        //字体大小，换行模式
        NSDictionary *attributes = @{NSFontAttributeName : font , NSParagraphStyleAttributeName : style};
        resultSize = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    } else {
        //计算正文的高度
        resultSize = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
    }
    return resultSize;
}

- (NSString *)qhw_stringByTrimingWhitespace {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)stringRemoveSpace {
    NSString *newString = [self qhw_stringByTrimingWhitespace];
    return [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
}

// http://baike.baidu.com/view/781667.htm
- (NSString *)qhw_carrier {
    if (self.length < 3 || ![self qhw_validDigits]) {
        return @"未知运营商";
    }
    
    NSString *prefix = [self substringToIndex:3];
    
    /// “1700” 为中国电信的转售号码标识，“1705” 为中国移动，“1709” 为中国联通。
    if ([prefix isEqualToString:@"170"]) {
        if (self.length < 4) {
            return @"未知运营商";
        }
        else {
            NSString *key = [self substringWithRange:NSMakeRange(3, 1)];
            if ([key isEqualToString:@"0"]) {
                return @"中国电信";
            }
            else if ([key isEqualToString:@"5"]) {
                return @"中国移动";
            }
            else if ([key isEqualToString:@"9"]) {
                return @"中国联通";
            }
            else {
                return @"未知运营商";
            }
        }
    }
    
    // 中国移动
    NSString *cm = @"^(134|135|136|137|138|139|150|151|152|158|159|182|183|184|157|187|188|178)$";
    
    // 中国联通
    NSString *cu = @"^(130|131|132|155|156|185|186|176)$";
    
    // 中国电信
    NSString *ct = @"^(133|153|180|181|189|177)$";
    
    if ([prefix qhw_isMatchsRegex:cm]) {
        return @"中国移动";
    }
    else if ([prefix qhw_isMatchsRegex:cu]) {
        return @"中国联通";
    }
    else if ([prefix qhw_isMatchsRegex:ct]) {
        return @"中国电信";
    }
    else {
        return @"未知运营商";
    }
}

- (BOOL)qhw_validPhoneNumber {
    return [self qhw_isMatchsRegex:@"^(13\\d|14[57]|15[^4,\\D]|17[0135678]|18\\d)\\d{8}$"];
}

- (BOOL)qhw_validPassword {
    return [self qhw_isMatchsRegex:@"^(?!\\d{1,8}$)[\\S]{6,16}$"];
}

// 是否有效的数字
- (BOOL)qhw_validDigits {
    NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
    return r.location == NSNotFound;
}

- (BOOL)qhw_validAmount {
    return [self qhw_isMatchsRegex:@"^(([0-9]|([1-9][0-9]{0,9}))((\\.[0-9]{0,2})?))$"];
}


#pragma mark - Private

- (BOOL)qhw_isMatchsRegex:(NSString *)regex {
    if ([self qhw_stringByTrimingWhitespace].length == 0) {
        return NO;
    }
    
    NSPredicate *matches = [NSPredicate predicateWithFormat:@"SELF MATCHES%@", regex];
    return [matches evaluateWithObject:self];
}



+ (NSString *)weekdayOfCalendarIndex:(NSInteger)index {
    //   NSAssert((index >= 1 && index <= 7), @"传入的数字必须在1和7之间");
    switch (index) {
        case 7:
            return @"星期六";
        case 1:
            return @"星期天";
        case 2:
            return @"星期一";
        case 3:
            return @"星期二";
        case 4:
            return @"星期三";
        case 5:
            return @"星期四";
        case 6:
            return @"星期五";
        default:
            return @"";
            break;
    }
}

- (BOOL)isPuloIntNumberString {
    NSScanner *scan = [NSScanner scannerWithString:self];
    
    int val;
    
    return [scan scanInt:&val]&&[scan isAtEnd];
}


#pragma mark - 身份证
+ (NSString *)getStringWithRange:(NSString *)str Value1:(NSInteger)value1 Value2:(NSInteger)value2
{
    return [str substringWithRange:NSMakeRange(value1,value2)];
}


// 判断大陆身份证
+ (BOOL)Chk18PaperId :(NSString *)sPaperId
{
    //判断位数
    if ([sPaperId length] < 15 ||[sPaperId length] > 18) {
        
        return NO;
    }
    
    NSString *carid = sPaperId;
    long lSumQT =0;
    //加权因子
    int R[] ={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
    //校验码
    unsigned char sChecker[11]={'1','0','X', '9', '8', '7', '6', '5', '4', '3', '2'};
    
    //将15位身份证号转换成18位
    
    NSMutableString *mString = [NSMutableString stringWithString:sPaperId];
    if ([sPaperId length] == 15) {
        
        
        [mString insertString:@"19" atIndex:6];
        
        long p = 0;
        const char *pid = [mString UTF8String];
        for (int i=0; i<=16; i++)
        {
            p += (pid[i]-48) * R[i];
        }
        
        int o = p%11;
        NSString *string_content = [NSString stringWithFormat:@"%c",sChecker[o]];
        [mString insertString:string_content atIndex:[mString length]];
        carid = mString;
        
    }
    
    //判断地区码
    NSString * sProvince = [carid substringToIndex:2];
    
    if (![self areaCode:sProvince]) {
        
        return NO;
    }
    
    //判断年月日是否有效
    
    //年份
    int strYear = [[self getStringWithRange:carid Value1:6 Value2:4] intValue];
    //月份
    int strMonth = [[self getStringWithRange:carid Value1:10 Value2:2] intValue];
    //日
    int strDay = [[self getStringWithRange:carid Value1:12 Value2:2] intValue];
    
    
    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setTimeZone:localZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d 12:01:01",strYear,strMonth,strDay]];
    if (date == nil) {
        
        return NO;
    }
    
    const char *PaperId  = [carid UTF8String];
    
    //检验长度
    if( 18 != strlen(PaperId)) return -1;
    //校验数字
    for (int i=0; i<18; i++)
    {
        if ( !isdigit(PaperId[i]) && !(('X' == PaperId[i] || 'x' == PaperId[i]) && 17 == i) )
        {
            return NO;
        }
    }
    //验证最末的校验码
    for (int i=0; i<=16; i++)
    {
        lSumQT += (PaperId[i]-48) * R[i];
    }
    if (sChecker[lSumQT%11] != PaperId[17] && (sChecker[lSumQT%11] + 32) != PaperId[17])
    {
        return NO;
    }
    
    return YES;
}

+ (BOOL)areaCode:(NSString *)code
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init] ;
    [dic setObject:@"北京" forKey:@"11"];
    [dic setObject:@"天津" forKey:@"12"];
    [dic setObject:@"河北" forKey:@"13"];
    [dic setObject:@"山西" forKey:@"14"];
    [dic setObject:@"内蒙古" forKey:@"15"];
    [dic setObject:@"辽宁" forKey:@"21"];
    [dic setObject:@"吉林" forKey:@"22"];
    [dic setObject:@"黑龙江" forKey:@"23"];
    [dic setObject:@"上海" forKey:@"31"];
    [dic setObject:@"江苏" forKey:@"32"];
    [dic setObject:@"浙江" forKey:@"33"];
    [dic setObject:@"安徽" forKey:@"34"];
    [dic setObject:@"福建" forKey:@"35"];
    [dic setObject:@"江西" forKey:@"36"];
    [dic setObject:@"山东" forKey:@"37"];
    [dic setObject:@"河南" forKey:@"41"];
    [dic setObject:@"湖北" forKey:@"42"];
    [dic setObject:@"湖南" forKey:@"43"];
    [dic setObject:@"广东" forKey:@"44"];
    [dic setObject:@"广西" forKey:@"45"];
    [dic setObject:@"海南" forKey:@"46"];
    [dic setObject:@"重庆" forKey:@"50"];
    [dic setObject:@"四川" forKey:@"51"];
    [dic setObject:@"贵州" forKey:@"52"];
    [dic setObject:@"云南" forKey:@"53"];
    [dic setObject:@"西藏" forKey:@"54"];
    [dic setObject:@"陕西" forKey:@"61"];
    [dic setObject:@"甘肃" forKey:@"62"];
    [dic setObject:@"青海" forKey:@"63"];
    [dic setObject:@"宁夏" forKey:@"64"];
    [dic setObject:@"新疆" forKey:@"65"];
    [dic setObject:@"台湾" forKey:@"71"];
    [dic setObject:@"香港" forKey:@"81"];
    [dic setObject:@"澳门" forKey:@"82"];
    [dic setObject:@"国外" forKey:@"91"];
    
    if ([dic objectForKey:code] == nil) {
        
        return NO;
    }
    return YES;
}
/// 从指定格式,时间戳获取时间
+ (NSString *)defaultTimeFromFormatter:(NSString *)fomatter timeString:(NSString *)string{
   return [self timeFromFormatter:fomatter timeString:string];
}
+ (NSString *)timeFromFormatter:(NSString *)fomatter timeString:(NSString *)string {
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    dateformatter.dateFormat = fomatter;
    return [dateformatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:string.longLongValue / 1000]];
}

+(NSString*)getCurrentYearMonthWithFormatter:(NSString *)dateFormat{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormat];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}

+(NSString*)getCurrentDayWithFormatter:(NSString *)dateFormat timeDiff:(CGFloat)timeDiff{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormat];
    NSString *currentTimeString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:timeDiff]];
    return currentTimeString;
}

+(NSString*)getCurrentYearMonth{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSArray *currentTimeArr = [currentTimeString componentsSeparatedByString:@"-"];
    NSString *yearMonth = [NSString stringWithFormat:@"%@%@",currentTimeArr[0],currentTimeArr[1]];
    return yearMonth;
}

+ (NSString *)lastDayWithFormatter:(NSString *)formatter {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = formatter;
    return [format stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-24*3600]];
}

- (NSString *)changeMoneyFormat:(NSNumberFormatterStyle)style {
    if (!style) {
        style = NSNumberFormatterDecimalStyle;
    }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = style;
    NSString *formatString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[self doubleValue]]];
    
    // 转成的string如果小数点后面值为0 会去除0 所以自己添加上去
    NSArray *eleString = [formatString componentsSeparatedByString:@"."];
    if (eleString.count == 1) {
        formatString = [formatString stringByAppendingString:@".00"];
    }else if (eleString.count == 1) {
        NSString *secend = eleString.lastObject;
        if (secend.length == 1) {
            formatString = [formatString stringByAppendingString:@"0"];
            
        }
    }
    
    return formatString;
}

+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}

- (NSString *)filterNullStringWithString:(NSString *)replaceString {
    if (!self) {
        return replaceString;
    }
    if (self.length == 0) {
        return replaceString;
    }
    if ([self isEqualToString:@"<null>"] || [self isEqualToString:@"(null)"]) {
        return replaceString;
    }
    return self;
}

- (BOOL)isChineseOrEnglish {
    if (self && self.length == 0) {
        return YES;
    }
    NSString *reges = @"^[a-zA-Z\u4e00-\u9fa5]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self matches %@", reges];
    if ([predicate evaluateWithObject:self]) {
        return YES;
    }else {
        return NO;
    }
    
    return YES;
}

- (BOOL)isNumberOrEnglish {
    if (self && self.length == 0) {
        return YES;
    }
    
    NSString *regular = @"^[0-9a-zA-Z]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self matches %@", regular];
    if ([predicate evaluateWithObject:self]) {
        return YES;
    }else {
        return NO;
    }
}

- (BOOL)isChineseOrEnglishWhiteAndDash {
    if (self && self.length == 0) {
        return YES;
    }
    NSString *reges = @"^[a-zA-Z -\u4e00-\u9fa5]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self matches %@", reges];
    if ([predicate evaluateWithObject:self]) {
        return YES;
    }else {
        return NO;
    }
    
    return YES;
}

// 四位添加一个空格
- (NSString *)insertSpacePreFourCharacter {
    if (!self || self.length ==0) {
        return @"";
    }
    NSString *newString = @"";
    NSInteger count = self.length;
    NSInteger i = 0;
    while ((count - 4 * (i + 1)) > 0) {
        newString = [newString stringByAppendingString:[self substringWithRange:NSMakeRange(i++ * 4, 4)]];
        newString = [newString stringByAppendingString:@" "];
        if (i >= 4) {
            break;
        }
    }
    newString = [newString stringByAppendingString:[self substringWithRange:NSMakeRange(i * 4, count - i * 4)]];
    return newString;
}

- (NSString *)ID18DigitCardInsertSpace {
    if (!self || self.length == 0) {
        return @"";
    }
    
    // 不是18位的 4位一空格
    if (self.length != 18) {
        return [self insertSpacePreFourCharacter];
    }
    
    NSMutableString *string = [NSMutableString string];
    [string appendFormat:@"%@ ", [self substringWithRange:NSMakeRange(0, 6)]];
    [string appendFormat:@"%@ ", [self substringWithRange:NSMakeRange(6, 4)]];
    [string appendFormat:@"%@ ", [self substringWithRange:NSMakeRange(10, 4)]];
    [string appendFormat:@"%@", [self substringFromIndex:self.length - 4]];
    
    return string;
}

/// 银行卡中间数字替换成*
- (NSString *)bankCardNoExchangeWithStar {
    if (self.length <= 10) {
        return self;
    }
    
    NSString *first = [self substringToIndex:6];
    NSString *last = [self substringFromIndex:self.length - 4];
    NSString *card = @"";
    card = [card stringByAppendingString:first];
    for (int i = 0; i < self.length - 10; i++) {
        card = [card stringByAppendingString:@"*"];
    }
    card = [card stringByAppendingString:last];
    return card;
}

+ (BOOL)canChangeTextField:(UITextField *)textfield withString:(NSString *)string length:(NSInteger)length {
    if (textfield.text.length == length && ![string isEqualToString:@""]) {
        return NO;
    }
    
    return YES;
}

- (BOOL)isValidLoginPassword {
    if (![self isKindOfClass:[NSString class]]) {
        return NO;
    }
    // 6 - 18位
    if (self.length < 6 || self.length > 18) {
        return NO;
    }
    // 不能纯数字
    if ([self isPuloIntNumberString]) {
        return NO;
    }
    // 不能纯英文
    NSString *regix = @"^[a-zA-Z]+$";
    NSPredicate *presicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regix];
    if([presicate evaluateWithObject:self]) {
        return NO;
    }
    return YES;
}

/// textfield输入银行卡自动空格 并限制长度
+ (NSString *)textFieldBankInsertSpaceOriginal:(NSString *)original range:(NSRange)range string:(NSString *)string length:(NSInteger)length {
    NSString *content = [original stringByReplacingCharactersInRange:range withString:string];
    content = [content stringRemoveSpace];
    if (content.length > length) {
        return original;
    }else {
        return [content insertSpacePreFourCharacter];
    }
}

+ (NSString *)textFieldIDCardInsertSpaceOriginal:(NSString *)original range:(NSRange)range string:(NSString *)string length:(NSInteger)length {
    NSString *content = [original stringByReplacingCharactersInRange:range withString:string];
    content = [content stringRemoveSpace];
    if (content.length > length) {
        return original;
    }else {
        return [content ID18DigitCardInsertSpace];
    }
    
}

+ (NSString *)concealPhoneNumber:(NSString *)number {
    if (![number isKindOfClass:[NSString class]]) {
        return @"";
    }
    
    if (number.length < 7) {
        return number;
    }
    
    return [NSString stringWithFormat:@"%@****%@", [number substringToIndex:3], [number substringFromIndex:number.length - 4]];
}

- (NSDictionary *)JSONFromString {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return json;
}

+(CGSize) boundingALLRectWithSize:(NSString*) txt Font:(UIFont*) font Size:(CGSize) size{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:txt];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    [style setLineSpacing:2.0f];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [txt length])];
    
    CGSize realSize = CGSizeZero;
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    CGRect textRect = [txt boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font,NSParagraphStyleAttributeName:style} context:nil];
    realSize = textRect.size;
#else
    realSize = [txt sizeWithFont:font constrainedToSize:size];
#endif
    
    realSize.width = ceilf(realSize.width);
    realSize.height = ceilf(realSize.height);
    return realSize;
}


+ (NSAttributedString *)getShowAttributedStringWithTotalString:(NSString *)totalString totalColor:(UIColor *)totalColor specialString:(NSString *)specialString specialColor:(UIColor *)SpecialColor specialfontOfSize:(CGFloat)fontSize{
    NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc] initWithString: totalString];
    NSRange normalRange = [totalString rangeOfString:totalString];
    [attributeString addAttribute:NSForegroundColorAttributeName value:totalColor range:normalRange];
    
    NSRange range = [totalString rangeOfString:specialString];
    [attributeString addAttribute:NSForegroundColorAttributeName value:SpecialColor range:range];
    [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:range];
    return attributeString;
}

+ (NSAttributedString *)getShowAttributedStringWithNormalString:(NSString *)normalString normalColor:(UIColor *)normalColor specialString:(NSString *)specialString specialColor:(UIColor *)SpecialColor specialfontOfSize:(CGFloat)fontSize{
    NSString * totalString = [NSString stringWithFormat:@"%@%@", normalString, specialString];
    NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc] initWithString: totalString];
    NSRange normalRange = [totalString rangeOfString:normalString];
    [attributeString addAttribute:NSForegroundColorAttributeName value:normalColor range:normalRange];
    
    NSRange range = [totalString rangeOfString:specialString];
    [attributeString addAttribute:NSForegroundColorAttributeName value:SpecialColor range:range];
    [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:range];
    return attributeString;
}


+ (NSAttributedString *)getShowAttributedStringWithNormalString:(NSString *)normalString specialString:(NSString *)specialString specialColor:(UIColor *)color specialfontOfSize:(CGFloat)fontSize{
    
    NSString * totalString = [NSString stringWithFormat:@"%@%@", normalString, specialString ?: @""];
    NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc] initWithString: totalString];
    NSRange range = [totalString rangeOfString:specialString ?: @""];
    
    [attributeString addAttribute:NSForegroundColorAttributeName value:color range:range];
    [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:range];
    return attributeString;
}

+ (NSAttributedString *)getShowAttributedStringWithNormalString:(NSString *)normalString normalColor:(UIColor *)normalColor specialString:(NSString *)specialString specialColor:(UIColor *)SpecialColor specialFont:(UIFont *)font {
    NSString * totalString = [NSString stringWithFormat:@"%@%@", normalString, specialString];
    NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc] initWithString: totalString];
    NSRange normalRange = [totalString rangeOfString:normalString];
    [attributeString addAttribute:NSForegroundColorAttributeName value:normalColor range:normalRange];
    
    NSRange range = [totalString rangeOfString:specialString];
    [attributeString addAttribute:NSForegroundColorAttributeName value:SpecialColor range:range];
    [attributeString addAttribute:NSFontAttributeName value:font range:range];
    return attributeString;
}

#pragma mark - 根据宽度计算文本的高度
+ (CGSize)calculationTextNeedSizeWithText:(NSString *)text
                                     font:(CGFloat)font
                                    width:(CGFloat)width{
    if (text) {
        NSDictionary *fontDic = @{NSFontAttributeName :[UIFont systemFontOfSize:font],
                                  };
        
        CGRect fontRect =  [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];
        return fontRect.size;
    }
    return CGSizeZero;
    
}
+ (CGPoint)calculationPointWithSize:(CGSize)size
                                text:(NSString *)text
                                font:(CGFloat)font{
    NSDictionary *fontDic = @{NSFontAttributeName :[UIFont systemFontOfSize:font],
                              };
    
    CGSize textSize = [text sizeWithAttributes:fontDic];
    CGFloat pointX = (size.width - textSize.width) /2.;
    CGFloat pointY = (size.height - textSize.height) / 2.;
    return CGPointMake(pointX, pointY);

}


+ (NSMutableAttributedString *)getOrderDetailString:(NSAttributedString *)str lineSpace:(CGFloat)space{
    NSMutableParagraphStyle  *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    // 行间距设置
    [paragraphStyle setLineSpacing:space];
    NSMutableAttributedString  *setString = [[NSMutableAttributedString alloc] initWithAttributedString:str];
    [setString  addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    return setString;
}

- (NSString *)moneyConversion{
    
    NSString *str = [NSString stringWithFormat:@"%.2f", ([self integerValue] /100.0)];
    return str;
}
- (void)setMoneyConversion:(NSString *)moneyConversion{
    ///以分为单位
    objc_setAssociatedObject(self, MoneyConversion, moneyConversion, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+(NSDictionary *)stringToDictionary:(NSString *)str{
    NSError *err;
    NSString *jsonStr = [NSString changeJsonStringToTrueJsonString:str];
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&err];
    if (err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return resultDic;
}
//把没有双引号和用了单引号的json字符串转化为标准格式字符串;
+ (NSString *)changeJsonStringToTrueJsonString:(NSString *)json
{
    // 将没有双引号的替换成有双引号的
    NSString *validString = [json stringByReplacingOccurrencesOfString:@"(\\w+)\\s*:([^A-Za-z0-9_])"
                                                            withString:@"\"$1\":$2"
                                                               options:NSRegularExpressionSearch
                                                                 range:NSMakeRange(0, [json length])];
    
    
    //把'单引号改为双引号"
    validString = [validString stringByReplacingOccurrencesOfString:@"([:\\[,\\{])'"
                                                         withString:@"$1\""
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, [validString length])];
    
    validString = [validString stringByReplacingOccurrencesOfString:@"'([:\\],\\}])"
                                                         withString:@"\"$1"
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, [validString length])];
    
    //再重复一次 将没有双引号的替换成有双引号的
    validString = [validString stringByReplacingOccurrencesOfString:@"([:\\[,\\{])(\\w+)\\s*:"
                                                         withString:@"$1\"$2\":"
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, [validString length])];
    return validString;
}

+ (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];
                //区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
        }
        [allString appendString:@","];
        count ++;
    }
    NSMutableString *initialStr = [NSMutableString new];
    //拼音首字母
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    return allString;
}

+ (NSMutableString*)getCookieValue{
    // 在此处获取返回的cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
        
    }
    // cookie重复，先放到字典进行去重，再进行拼接
    for (NSString *key in cookieDic) {
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
        [cookieValue appendString:appendString];
    }
    return cookieValue;
}

+ (NSString *)replaceHasPrefix:(NSString *)fixStr str:(NSString *)str {
    if ([str hasPrefix:fixStr]) {
        NSString *newStr = [str substringFromIndex:fixStr.length];
        return [self replaceHasPrefix:fixStr str:newStr];
    }
    return str;
}

+ (NSString *)getRandStringWithLength:(int)length {
    NSString *sourceStr = @"0123456789abcdefghijklmnopqrstuvwxyz";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    for (int i = 0; i < length; i++) {
        unsigned index = arc4random() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

@end
