//
//  ToolsManager.m
//  Patrol
//
//  Created by 曹云霄 on 2017/7/20.
//  Copyright © 2017年 上海勾芒科技信息有限公司. All rights reserved.
//

#import "ToolsManager.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonHMAC.h>
#import <AVFoundation/AVFoundation.h>

@implementation ToolsManager

+ (NSString *)completeUrl:(NSString *)url
{
    return [NSString stringWithFormat:@"%@/%@",HTTP_REST_API_BASE_URL,url];
}

/**
 拼接附件地址（如果没有HTTP前缀）
 */
+ (NSString *)jointUrl:(NSString *)string
{
    BOOL boolValue = [string rangeOfString:@"http"].location != NSNotFound;
    if (boolValue) {
        return string;
    }
    NSString *urlString = [NSString stringWithFormat:@"%@%@",HTTP_LOCAL_BASE_URL,string];
    return urlString;
}

/**
 VI检查拼接附件地址（如果没有HTTP前缀）
 */
+ (NSString *)viJointUrl:(NSString *)string
{
    BOOL boolValue = [string rangeOfString:@"http"].location != NSNotFound;
    if (boolValue) {
        return string;
    }
    NSString *urlString = [NSString stringWithFormat:@"%@%@",VIHTTP_LOCAL_BASE_URL,string];
    return urlString;
}

/**
 比较时间字符串大小
 
 @param date1 时间1
 @param date2 时间2

 */
 // -1 a<b  0 a==b  1 a>b
+ (NSInteger)compareTime:(NSString *)date1 date2:(NSString *)date2
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *newDate1 = [dateFormatter dateFromString:date1];
    NSDate *newDate2 = [dateFormatter dateFromString:date2];
    return [newDate1 compare:newDate2];
}


/**
 加密data
 */
+ (NSString *) md5Data:(NSData *)data {
    const char *cStr = [data bytes];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)data.length, result );
    
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}



//HmacSHA1加密
+(NSString *)Base_HmacSha1:(NSString *)key data:(NSString *)data
{
    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
    //Sha256:
    // unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    //CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    //sha1
    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                          length:sizeof(cHMAC)];
    NSMutableData *mutableData = [NSMutableData dataWithData:HMAC];
    [mutableData appendData:[data dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *hash = [mutableData base64EncodedStringWithOptions:0];
    return hash;
}

#pragma mark - 获取时间戳
+ (NSString *)getTheTimestamp
{
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970] * 1000; //*1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f",a]; //转为字符型
    return timeString;
}

#pragma mark - 判断字符串是否为空
+ (BOOL)empty:(NSString *)string
{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}


#pragma mark -汉字转码
+ (NSString *)returnUrlString:(NSString *)ChineseString
{
    NSString* encodedString = [ChineseString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return encodedString;
}

/**
 计算文字高度
 */
+ (CGFloat)heightWithFontSize:(CGFloat)fontSize width:(CGFloat)width text:(NSString *)string
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    return  [string boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.height;
}


/**
 计算字符串宽度
 */
+ (CGFloat)witdhWithFontSize:(CGFloat)fontSize height:(CGFloat)height text:(NSString *)string
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    return  [string boundingRectWithSize:CGSizeMake(0, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width;
}


// 相机权限判断
+ (BOOL)getPhotoAuthorizationStatus
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {
        //没有权限
        ShowAlertView(@"相机权限未开启", @"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能", @[@"取消",@"立即开启"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ONE) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        });
        return NO;
    }else{
        return YES;
    }
}

/**
 定位权限判断
 */
+ (BOOL)getLocationAuthorizationStatus
{
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted) {
        //没有权限
        ShowAlertView(@"定位权限未开启", @"定位权限未开启，请进入系统【设置】>【隐私】>【位置】中打开开关,开启定位功能", @[@"取消",@"立即开启"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ONE) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        });
        return NO;
    }
    return YES;
}

#pragma mark - 计算视频长度
+ (NSString *)calculateVideoLength:(NSString *)fileUrl
{
    if ([fileUrl rangeOfString:@".mp4"].location != NSNotFound) {
        NSURL *movieURL = [NSURL URLWithString:fileUrl];
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                         forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:movieURL options:opts];  // 初始化视频媒体文件
        NSInteger interval = urlAsset.duration.value / urlAsset.duration.timescale; // 获取视频总时长,单位秒
        NSUInteger secondPerDay = 24 * 60 * 60;
        NSUInteger secondPerHour = 60 * 60;
        NSUInteger secondPerMinute = 60;
        
        // 剩余小时不应该大于24小时，所以应该先除去满足一天的秒数，再计算还剩下多少小时
        NSInteger hour = interval % secondPerDay / secondPerHour;
        // 剩余分钟数与上面同理
        NSInteger minute = interval % secondPerHour / secondPerMinute;
        // 剩余秒数直接等于秒数对每分钟秒数所取的余数
        NSInteger second = interval % secondPerMinute;
        NSMutableString *string = [NSMutableString string];
        if (hour) {
            [string appendString:[NSString stringWithFormat:@"%02zd:",hour]];
        }
        [string appendString:[NSString stringWithFormat:@"%02zd:%02zd",minute,second]];
        return string;
    }
    return nil;
}

#pragma mark - 获取当前时间之前或者之后的时间（之前传入负数）
+ (NSString *)getTimeby:(NSInteger)day
{
    NSDate *nowDate = [NSDate date];
    NSDate *theDate;
    if(day!=0){
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*day];
    }else{
        theDate = nowDate;
    }
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    return the_date_str;
}

/**
 判断VI检查任务门店任务状态
 
 @param state 状态码
 @return 状态码图片
 */
+ (UIImage *)returnPatrolTaskStateImage:(NSInteger)state {
    switch (state) {
        case 0: //未完成
        {
            return TCImage(@"not");
        } break;
        case 1: //已完成
        {
            return TCImage(@"submited");
        } break;
        case 2: //进行中
        {
            return TCImage(@"underway");
        } break;
            
        default:
            break;
    }
    return nil;
}

/**
 判断VI检查任务门店组坐标状态
 
 @param state 状态码
 @param taskState 门店状态
 @return 状态码图片
 */
+ (UIImage *)returnStoreCoordStateImage:(NSString *)state withTaskState:(NSInteger)taskState {
    if (!taskState) {
        return TCImage(@"coord_not");
    }
    if ([[self class] empty:state]) {
        return TCImage(@"coord_mismatching");
    }else {
        return TCImage(@"coord_matching");
    }
}

#pragma mark - 计算门店信息显示长度，并返回最大值
+ (CGFloat)calculateStoreInformation:(NSArray *)storeArray {
    NSMutableArray *titleWidthArray = [NSMutableArray array];
    for (NSString *title in storeArray) {
        CGFloat width = [title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:12] } context:nil].size.width;
        [titleWidthArray addObject:@(width)];
    }
    CGFloat max = [[titleWidthArray valueForKeyPath:@"@max.floatValue"] floatValue];
    return max + 10;
}


/**
 * 比较版本号
 *
 * @param string1 第一个版本号
 * @param string2 第二个版本号
 *
 * @return 如果版本号相等，返回 0,
 *         如果第一个版本号低于第二个，返回 -1，否则返回 1.
 */
+ (NSInteger)compareVersion:(NSString *)string1 string:(NSString *)string2
{
    int result = compareVersion([string1 UTF8String], [string2 UTF8String]);
    switch (result) {
        case 0:
            return 0;
        case -1:
            return -1;
        case 1:
            return 1;
        default:
            break;
    }
    return NO;
}


/**
 * 比较版本号
 *
 * @param v1 第一个版本号
 * @param v2 第二个版本号
 *
 * @return 如果版本号相等，返回 0,
 *         如果第一个版本号低于第二个，返回 -1，否则返回 1.
 */
int compareVersion(const char *v1, const char *v2)
{
    assert(v1);
    assert(v2);
    
    const char *p_v1 = v1;
    const char *p_v2 = v2;
    
    while (*p_v1 && *p_v2) {
        char buf_v1[32] = {0};
        char buf_v2[32] = {0};
        
        char *i_v1 = strchr(p_v1, '.');
        char *i_v2 = strchr(p_v2, '.');
        
        if (!i_v1 || !i_v2) break;
        
        if (i_v1 != p_v1) {
            strncpy(buf_v1, p_v1, i_v1 - p_v1);
            p_v1 = i_v1;
        }
        else
            p_v1++;
        
        if (i_v2 != p_v2) {
            strncpy(buf_v2, p_v2, i_v2 - p_v2);
            p_v2 = i_v2;
        }
        else
            p_v2++;
        
        
        
        int order = atoi(buf_v1) - atoi(buf_v2);
        if (order != 0)
            return order < 0 ? -1 : 1;
    }
    
    double res = atof(p_v1) - atof(p_v2);
    
    if (res < 0) return -1;
    if (res > 0) return 1;
    return 0;
}

/*
 周边加阴影，并且同时圆角
 */
+ (void)addShadowToView:(UIView *)view
            withOpacity:(float)shadowOpacity
           shadowRadius:(CGFloat)shadowRadius
        andCornerRadius:(CGFloat)cornerRadius
{
    //////// shadow /////////
    CALayer *shadowLayer = [CALayer layer];
    shadowLayer.frame = view.layer.frame;
    shadowLayer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
    shadowLayer.shadowOffset = CGSizeMake(0, 0);//shadowOffset阴影偏移，默认(0, -3),这个跟shadowRadius配合使用
    shadowLayer.shadowOpacity = shadowOpacity;//0.8;//阴影透明度，默认0
    shadowLayer.shadowRadius = shadowRadius;//8;//阴影半径，默认3
    //路径阴影
    UIBezierPath *path = [UIBezierPath bezierPath];
    float width = shadowLayer.bounds.size.width;
    float height = shadowLayer.bounds.size.height;
    float x = shadowLayer.bounds.origin.x;
    float y = shadowLayer.bounds.origin.y;
    
    CGPoint topLeft      = shadowLayer.bounds.origin;
    CGPoint topRight     = CGPointMake(x + width, y);
    CGPoint bottomRight  = CGPointMake(x + width, y + height);
    CGPoint bottomLeft   = CGPointMake(x, y + height);
    
    CGFloat offset = -1.f;
    [path moveToPoint:CGPointMake(topLeft.x - offset, topLeft.y + cornerRadius)];
    [path addArcWithCenter:CGPointMake(topLeft.x + cornerRadius, topLeft.y + cornerRadius) radius:(cornerRadius + offset) startAngle:M_PI endAngle:M_PI_2 * 3 clockwise:YES];
    [path addLineToPoint:CGPointMake(topRight.x - cornerRadius, topRight.y - offset)];
    [path addArcWithCenter:CGPointMake(topRight.x - cornerRadius, topRight.y + cornerRadius) radius:(cornerRadius + offset) startAngle:M_PI_2 * 3 endAngle:M_PI * 2 clockwise:YES];
    [path addLineToPoint:CGPointMake(bottomRight.x + offset, bottomRight.y - cornerRadius)];
    [path addArcWithCenter:CGPointMake(bottomRight.x - cornerRadius, bottomRight.y - cornerRadius) radius:(cornerRadius + offset) startAngle:0 endAngle:M_PI_2 clockwise:YES];
    [path addLineToPoint:CGPointMake(bottomLeft.x + cornerRadius, bottomLeft.y + offset)];
    [path addArcWithCenter:CGPointMake(bottomLeft.x + cornerRadius, bottomLeft.y - cornerRadius) radius:(cornerRadius + offset) startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
    [path addLineToPoint:CGPointMake(topLeft.x - offset, topLeft.y + cornerRadius)];
    //设置阴影路径
    shadowLayer.shadowPath = path.CGPath;
    //////// cornerRadius /////////
    view.layer.cornerRadius = cornerRadius;
    view.layer.masksToBounds = YES;
    view.layer.shouldRasterize = YES;
    view.layer.rasterizationScale = [UIScreen mainScreen].scale;
    [view.superview.layer insertSublayer:shadowLayer below:view.layer];
}


@end
