//
//  SDGeneralTool.m
//  HomeHealth
//
//  Created by newuser on 16/12/30.
//  Copyright © 2016年 ChiJian. All rights reserved.
//

#import "SDGeneralTool.h"
#import "sys/utsname.h"
#import "UIImageView+ZYJWebCache.h"
#import "DataSafe.h"
#import "SDGeneralDefine.h"
#import "DSToast.h"
#import "ZYJMJExtension.h"

@implementation SDGeneralTool
//toast
+(void)toastWithTitlemessage:(NSString *)titlemessage{
    if(titlemessage.length>0){
        DSToast *toast = [[DSToast alloc] initWithText:titlemessage];
        toast.maxWidth = 284.0;
        toast.textInsets = UIEdgeInsetsMake(13.5, 44, 13.5, 44);
        [toast showInView:KKeyWindow showType:DSToastShowTypeCenter];
    }
}

+(void)removeDSToast{
    UIView *view = KKeyWindow;
    for (int i=0; i<view.subviews.count; i++) {
        if ([view.subviews[i] isKindOfClass:[DSToast class]]) {
            [view.subviews[i] removeFromSuperview];
        }
    }
}
+(void)popAlertControllerWithTarget:(UIViewController *)target title:(NSString *)title message:(NSString *)message finished:(void(^)(UIAlertAction * _Nonnull action))finished{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *actionOne1 = [UIAlertAction actionWithTitle:@"预览" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        if (finished) {
            finished(action);
        }
    }];
    UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:actionOne1];
    [alert addAction:actionTwo];
    
    @try {
        NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:title.length?title:@""];
        [alertControllerStr addAttribute:NSForegroundColorAttributeName value:UICOLOR_RGB_Alpha(0x0d0d0d, 1) range:NSMakeRange(0, alertControllerStr.length)];
        [alertControllerStr addAttribute:NSFontAttributeName value:KFontNameMediumSize(17) range:NSMakeRange(0, alertControllerStr.length)];
        [alert setValue:alertControllerStr forKey:@"attributedTitle"];
        
        NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:message.length?message:@""];
        [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:UICOLOR_RGB_Alpha(0xcccccc, 1) range:NSMakeRange(0, alertControllerMessageStr.length)];
        [alertControllerMessageStr addAttribute:NSFontAttributeName value:KFontNameMediumSize(14) range:NSMakeRange(0, alertControllerMessageStr.length)];
        [alert setValue:alertControllerMessageStr forKey:@"attributedMessage"];
       [actionOne1 setValue:UICOLOR_RGB_Alpha(0x007aff, 1) forKey:@"_titleTextColor"];
       [actionTwo setValue:UICOLOR_RGB_Alpha(0x007aff, 1) forKey:@"_titleTextColor"];
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        [alert.view setTintColor:UICOLOR_RGB_Alpha(0x007aff, 1)];
    }
    [target presentViewController:alert animated:YES completion:nil];
}
//push
+(void)pushViewControllerWithController:(UIViewController *)Controller{
    if ([KRootTabBarController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabVC = (UITabBarController *)KRootTabBarController;
        UINavigationController *nav = tabVC.selectedViewController;
        [nav pushViewController:Controller animated:YES];
    }else{
        UINavigationController *nav = (UINavigationController *)KRootTabBarController;
        [nav pushViewController:Controller animated:YES];
    }
}
+ (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //    NSString * deviceString =  [UIDevice currentDevice].model;
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
    if ([deviceString isEqualToString:@"iPhone9,3"])    return @"美版、台版iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,4"])    return @"美版、台版iPhone 7 Plus";
    if ([deviceString isEqualToString:@"iPhone10,1"])   return @"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,4"])   return @"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,2"])   return @"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,5"])   return @"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,3"])   return @"iPhone X";
    if ([deviceString isEqualToString:@"iPhone10,6"])   return @"iPhone X";
    if ([deviceString isEqualToString:@"iPhone11,2"])   return @"iPhone XS";
    if ([deviceString isEqualToString:@"iPhone11,4"])   return @"iPhone XS Max";
    if ([deviceString isEqualToString:@"iPhone11,6"])   return @"iPhone XS Max";
    if ([deviceString isEqualToString:@"iPhone11,8"])   return @"iPhone XR";
    
    if ([deviceString isEqualToString:@"i386"])         return @"iPhone Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"iPhone Simulator";
    
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad 1G";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad Mini 1G";
    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad Mini 1G";
    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad Mini 1G";
    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3";
    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3";
    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4";
    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4";
    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,4"])      return @"iPad Mini 2G";
    if ([deviceString isEqualToString:@"iPad4,5"])      return @"iPad Mini 2G";
    if ([deviceString isEqualToString:@"iPad4,6"])      return @"iPad Mini 2G";
    
    return deviceString;
}
//判断是否是iphone4
+ (BOOL)isIPhone4{
    if ([UIScreen mainScreen].bounds.size.height == 480) {
        return YES;
    }
    return NO;
}

+ (BOOL)isIPhoneX{
    if ([UIScreen mainScreen].bounds.size.height == 812) {
        return YES;
    }
    return NO;
}

+ (NSString *)getDouble2Num:(id)num{
    NSString *string = @"";
    if ([num respondsToSelector:@selector(doubleValue)]) {
        CGFloat fV = [num doubleValue];
        string = [NSString stringWithFormat:@"%.2f",fV];
    }
    return string;
}
#pragma mark - 计算时间差
+(BOOL)isPassMinute:(int)min startTime:(NSString *)startTime endTime:(NSString *)endTime{
    
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *startD =[date dateFromString:startTime];
    NSDate *endD = [date dateFromString:endTime];
    NSTimeInterval start = [startD timeIntervalSince1970]*1;
    NSTimeInterval end = [endD timeIntervalSince1970]*1;
    NSTimeInterval value = end - start;
//    int s = (int)value %60;
//    int minute = (int)value /60%60;
//    int house = (int)value / 3600%3600;
//    int day = (int)value / (24*3600)%(24*3600);
//    int sum = day*(24*3600)+house * 3600 + minute*60 + s;
    if (value>(min*60)) {
        return YES;
    }
    return NO;
}
//聊天获取下一条消息时间标签
+(NSString*)getNextMsgTimeWithTime:(NSString *)Time{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *endD = [date dateFromString:Time];
    NSTimeInterval end = [endD timeIntervalSince1970]*1;

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"HH:mm"];
    NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:end];
    return [format stringFromDate:endDate];
}
//当天时间
+(NSString*)getHistorySameDayTimeWithTime:(NSString *)Time{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *endD = [date dateFromString:Time];
    NSTimeInterval end = [endD timeIntervalSince1970]*1;
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"HH:mm:ss"];
    NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:end];
    return [format stringFromDate:endDate];
}
//获取当前的时间
+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];

    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}
+(NSString*)getAllCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}
+(NSString *)getHHTimeWithSeconds:(NSTimeInterval)s{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"HH:mm"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:s/1000];
    return [format stringFromDate:date];
}
+(NSString *)getTimeWithSeconds:(NSTimeInterval)s{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:s];
    return [format stringFromDate:date];
}
+(NSString *)getTimeWithDate:(NSDate *)date{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    return [format stringFromDate:date];
}
//获取当前时间（以毫秒为单位）
+(NSString *)getNowTimeTimestampMillisecond{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"];
    
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}
//@"d MMM yyyy HH:mm:ss 'GMT'"
+(NSString *)getGMTTimestamp{
    NSDate *date = [NSDate date];
    NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];
    [NSTimeZone setDefaultTimeZone:tzGMT];
    NSDateFormatter *iosDateFormater=[[NSDateFormatter alloc] init];
    iosDateFormater.dateFormat=@"EEE, dd MMM yyyy HH:mm:ss 'GMT'";
    iosDateFormater.locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    return [iosDateFormater stringFromDate:date];
}
#pragma mark - 将某个时间转化成时间戳
+(NSInteger)timeSwitchTimestamp:(NSString *)formatTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];

    NSDate* date = [formatter dateFromString:formatTime];
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}
+(NSInteger)timeSwitchDayTimestamp:(NSString *)formatTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];

    NSDate* date = [formatter dateFromString:formatTime];
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}
//获取当前时间戳(以秒为单位)
+(NSString *)getNowSSTimeTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}
//获取当前时间戳(以毫秒为单位)
+(NSString *)getNowSSSTimeTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; //

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
}

#pragma mark 获取系统开机时间到1970时间差值
+(double)getLaunchSystemTime{
    NSTimeInterval sysTime = [NSProcessInfo processInfo].systemUptime;
    return sysTime;
}

+ (BOOL)isAllowInputPasssword:(NSString *)str{
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
    NSString *filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [str isEqualToString:filtered];
}
//[6-20位字符，可由中文、英文、数字及“_”、“-”组成]
+(BOOL)isValidateName:(NSString *)name{
    NSString *phoneRegex = @"^[\u4e00-\u9fa50-9a-zA-Z_-]{0,20}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:name];
}
+(BOOL)checkTelNumber:(NSString *)telNumber{
    NSString *pattern = @"^1+\\d{10}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}
//base64编码
+(NSString *)encode:(NSString *)string{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}
//base64解码
+(NSString *)dencode:(NSString *)base64String{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

//+ (NSString *)uuidString
//{
//    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
//    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
//    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
//    CFRelease(uuid_ref);
//    CFRelease(uuid_string_ref);
//    return [uuid lowercaseString];
//}
//[[NSUUID UUID] UUIDString];

+(NSString *)hidNameWithStr:(NSString *)str{
    NSString *pattern = @"\\d*";
    
    NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionAnchorsMatchLines error:nil];
    NSArray *matchs = [regExp matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    for (int i=0; i<matchs.count; i++) {
        NSTextCheckingResult *Result = matchs[i];
        NSString *subStr = [str substringWithRange:Result.range];
        if (subStr.length==11 && [SDGeneralTool checkTelNumber:subStr]) {
            NSString *hidStr = [subStr stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            str = [str stringByReplacingCharactersInRange:Result.range withString:hidStr];
        }
    }
    
    return str;
}

//普通字符串转换为十六进制的
+(NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr = @"";
    for(int i=0;i<[myD length];i++){
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1){
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        }else{
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
    }
    return hexStr;
}
@end
