//
//  Tools.m
//  Open
//
//  Created by 雷俊博 on 2019/6/30.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "Tools.h"
#import "KeychainItemWrapper.h"
#import<AdSupport/AdSupport.h>
@implementation Tools

//打开链接
+(void)openWebUrl:(UIViewController *)controller:(NSString *)openUrl{
    WebVC *vc = [[WebVC alloc]init];
    vc.title = @"";
    vc.url =openUrl;
    [controller.navigationController pushViewController:vc animated:YES];
}

//打开URi
+(void)openUri:(NSString *)openUri{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUri] options:nil completionHandler:nil];
}
//是否安装支付宝
+(BOOL)isInstallAlipay{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipays://"]];
}
//打开微信小程序
+ (void)smallProgram:(NSString *)wxId:(NSString *)wxPath{
    
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = wxId; //拉起的小程序的username
    if(wxPath!=nil&&![wxPath isEqualToString:@""]){
        launchMiniProgramReq.path = wxPath; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
    }
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
    }];
}
//获取版本号
+(NSString*) getVersionCode{
    NSString*version = nil;
    NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray*vArr = [v componentsSeparatedByString:@"."];
    for (int i = 0; i < vArr.count; i++) {
        if (version == nil) {
            version = [NSString stringWithFormat:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    return version;
}

//动态菜单请求url
+(NSString*) getMenuRequestUrl{
    NSString*url = [NSString stringWithFormat:@"%@dynamic/menu/get",[NetworkConfig ipYinShuConfig]];
    return url;
}

+ (NSString *)ValidblankString:(NSString *)string{
    if (![string isKindOfClass:[NSString class]] ){
        return  @"";
    }
    if ([string isEqual:[NSNull null]]){
        return  @"";
    }
    if (string == NULL || [string isEqual:nil] || [string isEqual:Nil] || string == nil){
        return  @"";
    }
    if([string isEqualToString:@"(null)"]){
        return  @"";
    }
    if([string isEqualToString:@"<null>"]){
        return  @"";
    }
    if (string.length == 0 || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
        return  @"";
    }
    return string;
}
+ (BOOL)isMobileNumber:(NSString *)mobileNumString {
    NSString *pattern = @"^((13[0-9])|(15[0-9])|(16[5-7])|(19[0-9])|(18[0-9])|(17[0-9])|(14[0-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    
    BOOL isMatch = [pred evaluateWithObject:mobileNumString];
    
    return isMatch;
}

//toast
+ (void)showMessage:(NSString *)message
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *showView = [[UIView alloc]init];
    showView.backgroundColor = [UIColor darkGrayColor];
    showView.frame = CGRectMake(1, 1, 1, 1);
    showView.alpha = 1.0f;
    showView.layer.cornerRadius = 5.0f;
    showView.layer.masksToBounds = YES;
    [window addSubview:showView];
    
    UILabel *label = [[UILabel alloc]init];
    CGSize labelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    label.frame = CGRectMake(10, 5, labelSize.width, labelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showView addSubview:label];
    showView.frame = CGRectMake((ScreenWidth - labelSize.width - 20)/2, ScreenHeight - 100, labelSize.width + 20, labelSize.height + 10);
    
    [UIView animateWithDuration:2 animations:^{
        showView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [showView removeFromSuperview];
    }];
}


+ (BOOL)isChinese:(NSString*)text
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:text];
}

+ (NSInteger)genderOfIDNumber:(NSString *)IDNumber
{
      //  记录校验结果：0未知，1男，2女
    NSInteger result = 0;
    NSString *fontNumer = nil;
    
    if (IDNumber.length == 15)
    { // 15位身份证号码：第15位代表性别，奇数为男，偶数为女。
        fontNumer = [IDNumber substringWithRange:NSMakeRange(14, 1)];
 
    }else if (IDNumber.length == 18)
    { // 18位身份证号码：第17位代表性别，奇数为男，偶数为女。
        fontNumer = [IDNumber substringWithRange:NSMakeRange(16, 1)];
    }else
    { //  不是15位也不是18位，则不是正常的身份证号码，直接返回
        return result;
    }
    
    NSInteger genderNumber = [fontNumer integerValue];
    
    if(genderNumber % 2 == 1)
        result = 1;
    
    else if (genderNumber % 2 == 0)
        result = 2;
    return result;
}

+ (UIImage *)convertViewToImage:(UIView *)view {

   //UIGraphicsBeginImageContext(view.bounds.size);
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:view.bounds.size];
    
   [view.layer renderInContext:UIGraphicsGetCurrentContext()];
   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return image;

}

/**
 *  时间字符串转成字符串
 *
 *  @param timestr 时间字符串
 *
 *  @return 格式化后的字符串
 */

+ (NSString *)timeFromTimestr:(NSString *)timestr{
    
    NSDateFormatter *dateFormtter = [[NSDateFormatter alloc] init];
    [dateFormtter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *d = [dateFormtter dateFromString:timestr];
    
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;    //转记录的时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;   //获取当前时间戳
    NSString *timeString=@"";
    NSTimeInterval cha=now-late;
    // 发表在一小时之内
    if (cha/3600<1) {
        if (cha/60<1) {
            timeString = @"1";
        }
        else
        {
            timeString = [NSString stringWithFormat:@"%f", cha/60];
            timeString = [timeString substringToIndex:timeString.length-7];
        }
        
        timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
    }
    // 在一小时以上24小以内
    else if (cha/3600>1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
    }
    // 发表在24以上10天以内
    else if (cha/86400>1&&cha/86400*3<1)     //86400 = 60(分)*60(秒)*24(小时)   3天内
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@天前", timeString];
    }
    // 发表时间大于10天
    else
    {
        [dateFormtter setDateFormat:@"yyyy-MM-dd"];
        timeString = [dateFormtter stringFromDate:d];
    }
    
    return timeString;
}

+(NSString*)getCurrentTimes
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSLog(@"currentTimeString =  %@",currentTimeString);
    return currentTimeString;
}

+ (UIViewController *)jsd_findVisibleViewController {
    
    UIViewController* currentViewController = [self jsd_getRootViewController];

    BOOL runLoopFind = YES;
    while (runLoopFind) {
        if (currentViewController.presentedViewController) {
            currentViewController = currentViewController.presentedViewController;
        } else {
            if ([currentViewController isKindOfClass:[UINavigationController class]]) {
                currentViewController = ((UINavigationController *)currentViewController).visibleViewController;
            } else if ([currentViewController isKindOfClass:[UITabBarController class]]) {
                currentViewController = ((UITabBarController* )currentViewController).selectedViewController;
            } else {
                break;
            }
        }
    }
    
    return currentViewController;
}

+ (UIViewController *)jsd_getRootViewController{

    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    NSAssert(window, @"The window is empty");
    return window.rootViewController;
}

+(BOOL)isBlankString:(NSString *)string
{
    if ([string isEqual:@"NULL"] || [string isEqual:@""] || [string isKindOfClass:[NSNull class]] || [string isEqual:[NSNull null]] || [string isEqual:NULL] || [[string class] isSubclassOfClass:[NSNull class]] || string == nil || string == NULL || [string isKindOfClass:[NSNull class]] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0 || [string isEqualToString:@"<null>"] || [string isEqualToString:@"(null)"]){
        return YES;
    }
    
    return NO;
}

//大写转小写
+(NSString *)stringToLower:(NSString *)str
{
    for (NSInteger i = 0; i < str.length; i++){
        if ([str characterAtIndex:i] >= 'A' & [str characterAtIndex:i] <= 'Z'){
            char temp = [str characterAtIndex:i]+32;
            NSRange range = NSMakeRange(i, 1);
            str = [str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
        }
    }
    return str;
}
//小写转大写
+(NSString *)stringToUpper:(NSString *)str
{
    if (str.length >0) {
        NSString *idCardLast = [str substringWithRange:NSMakeRange(str.length - 1,1)];
        if ([idCardLast isEqualToString:@"x"]) {
            return [NSString stringWithFormat:@"%@X",[str substringWithRange:NSMakeRange(0,str.length - 1)]];
        }
    }
    
    return str;
}


//base64解密
+ (NSDictionary *)dencode:(NSString *)base64String
{
    //NSData *base64data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
   NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    return dictionary;
}

//Json字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - 判断银行卡号
+ (BOOL) IsBankCard:(NSString *)cardNumber
{
         if(cardNumber.length==0)
         {
                  return NO;
         }
         NSString *digitsOnly = @"";
         char c;
         for (int i = 0; i < cardNumber.length; i++)
         {
                  c = [cardNumber characterAtIndex:i];
                  if (isdigit(c))
                  {
                           digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
                  }
         }
         int sum = 0;
         int digit = 0;
         int addend = 0;
         BOOL timesTwo = false;
         for (NSInteger i = digitsOnly.length - 1; i >= 0; i--)
         {
                  digit = [digitsOnly characterAtIndex:i] - '0';
                  if (timesTwo)
                  {
                           addend = digit * 2;
                           if (addend > 9) {
                                    addend -= 9;
                           }
                  }
                  else {
                           addend = digit;
                  }
                  sum += addend;
                  timesTwo = !timesTwo;
         }
         int modulus = sum % 10;
         return modulus == 0;
}



+ (NSString *)getDeviceUUID{
    NSString * currentDeviceUUIDStr = [SSKeychain passwordForService:@"deviceId" account:@"kksh"];
    if ([Tools isBlankString:currentDeviceUUIDStr])
    {
        NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;
        currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
        currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
        currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
        [SSKeychain setPassword: currentDeviceUUIDStr forService:@"deviceId"account:@"kksh"];
        
        currentDeviceUUIDStr = [SSKeychain passwordForService:@"deviceId" account:@"kksh"];
    }
    NSLog(@"currentDeviceUUIDStr = %@",currentDeviceUUIDStr) ;
    
    return currentDeviceUUIDStr;
}

+ (NSString *) getDeviceOaid{
    NSString *oaid= [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return oaid;
}
//可用空间
+ (long ) getCanUseSpace{
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
    NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil];
    long use=[NSString stringWithFormat:@"%@",results[NSURLVolumeAvailableCapacityForImportantUsageKey]].longLongValue;
    return use;
}

//全部空间
+ (long ) getAllSpace{
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
    NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeTotalCapacityKey] error:nil];
    long all= [NSString stringWithFormat:@"%@",results[NSURLVolumeTotalCapacityKey]].longLongValue;
    return all;
}

+(NSString *)getGBString:(long)space{
    if (space<1000000000) {
        return [@"" stringByAppendingFormat:@"%d%@",space,@"Byte"];
    }
    int zs=space/1000000000L;//整数
    int xs=space%1000000000;//小数部分
    NSString *s=[NSString stringWithFormat:@"%d",xs];
    NSString *xxss=[s substringToIndex:2];//截取的小数部分
    NSString *value=[@"" stringByAppendingFormat:@"%d%@%@%@",zs,@".",xxss,@"GB"];
    return value;
}


+ (BOOL)dx_isNullOrNilWithObject:(id)object
{
    if (object == nil || [object isEqual:[NSNull null]]) {
        return YES;
    } else if ([object isKindOfClass:[NSString class]]) {
        if ([object isEqualToString:@""]) {
            return YES;
        } else {
            return NO;
        }
    }

    return NO;
}

/**
 *  检测用户输入密码是否以字母开头，6-18位数字和字母组合
 *正则匹配用户密码6-18位数字和字母组合
 *  @param pattern 传入需要检测的字符串
 *
 *  @return 返回检测结果 是或者不是
 */
+(BOOL)detectionIsPasswordQualified:(NSString *)patternStr{
    
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,12}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:patternStr];
    return isMatch;
    
}


#pragma mark - 获取当前时间戳
//毫秒级时间戳
+(NSString *)getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSpStr = [NSString stringWithFormat:@"%@",@((long)([datenow timeIntervalSince1970]*1000))];
    
    return timeSpStr;
}

#pragma mark - 获取当前时间戳,long
//毫秒级时间戳
+(long)getNowTimeTimesLong{

    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    long time=(long)([datenow timeIntervalSince1970]*1000);
    
    return time;
}

// 判断是否是同一天
+ (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}

+ (NSString *)getInternationDate
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
        
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
//    int year = [dateComponent year];
        
    int month = [dateComponent month];
        
    int day = [dateComponent day];
    
    return [NSString stringWithFormat:@"%d月%d日",month,day];
}

+ (NSString *)getLunarDate
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
        
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    int year = [dateComponent year];
        
    int month = [dateComponent month];
        
    int day = [dateComponent day];
    
    NSString *lunarDate = [self LunarForSolarYear:year Month:month Day:day];
    
    return lunarDate;
}


//农历转换函数
+ (NSString *)LunarForSolarYear:(int)wCurYear Month:(int)wCurMonth Day:(NSInteger)wCurDay {
    //农历日期名
    NSArray *cDayName =  [NSArray arrayWithObjects:@"*",@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",
                          
                          @"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",
                          
                          @"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十",nil];
    //农历月份名
    NSArray *cMonName =  [NSArray arrayWithObjects:@"*",@"正",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十",@"十一",@"腊",nil];
    //公历每月前面的天数
    const int wMonthAdd[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
    //农历数据
    const int wNongliData[100] = {2635,333387,1701,1748,267701,694,2391,133423,1175,396438
        
        ,3402,3749,331177,1453,694,201326,2350,465197,3221,3402
        
        ,400202,2901,1386,267611,605,2349,137515,2709,464533,1738
        
        ,2901,330421,1242,2651,199255,1323,529706,3733,1706,398762
        
        ,2741,1206,267438,2647,1318,204070,3477,461653,1386,2413
        
        ,330077,1197,2637,268877,3365,531109,2900,2922,398042,2395
        
        ,1179,267415,2635,661067,1701,1748,398772,2742,2391,330031
        
        ,1175,1611,200010,3749,527717,1452,2742,332397,2350,3222
        
        ,268949,3402,3493,133973,1386,464219,605,2349,334123,2709
        
        ,2890,267946,2773,592565,1210,2651,395863,1323,2707,265877};
    
    static int nTheDate,nIsEnd,m,k,n,i,nBit;
    //计算到初始时间1921年2月8日的天数：1921-2-8(正月初一)
    nTheDate = (wCurYear - 1921) * 365 + (wCurYear - 1921) / 4 + wCurDay + wMonthAdd[wCurMonth - 1] - 38;
    
    if((!(wCurYear % 4)) && (wCurMonth > 2))
        nTheDate = nTheDate + 1;
    
    //计算农历天干、地支、月、日
    nIsEnd = 0;
    m = 0;
    
    while(nIsEnd != 1) {
        if(wNongliData[m] < 4095)
            k = 11;
        else
            k = 12;
        n = k;
        while(n>=0) {
            //获取wNongliData(m)的第n个二进制位的值
            nBit = wNongliData[m];
            for(i=1;i< n+1;i++)
                nBit = nBit/2;
                nBit = nBit % 2;
            if (nTheDate <= (29 + nBit)) {
                nIsEnd = 1;
                break;
            }
            nTheDate = nTheDate - 29 - nBit;
            n = n - 1;
        }
        if(nIsEnd)
            break;
        m = m + 1;
    }
    
    wCurYear = 1921 + m;
    wCurMonth = k - n + 1;
    wCurDay = nTheDate;
    
    if (k == 12) {
        if (wCurMonth == wNongliData[m] / 65536 + 1)
            wCurMonth = 1 - wCurMonth;
        else if (wCurMonth > wNongliData[m] / 65536 + 1)
            wCurMonth = wCurMonth - 1;
    }
    //生成农历月
    NSString *szNongliMonth;
    if (wCurMonth < 1){
        szNongliMonth = [NSString stringWithFormat:@"闰%@",(NSString *)[cMonName objectAtIndex:-1 * wCurMonth]];
    }else{
        szNongliMonth = (NSString *)[cMonName objectAtIndex:wCurMonth];
    }
    //生成农历日
    NSString *szNongliDay = [cDayName objectAtIndex:wCurDay];
    //合并
    NSString *lunarDate = [NSString stringWithFormat:@"%@月%@",szNongliMonth,szNongliDay];
    return lunarDate;
}



@end
