//
//  YDAuthenticationHelper.m
//  H5APPDemo
//
//  Copyright © 2019 GMX. All rights reserved.
//

#import "YDAuthenticationHelper.h"
#import <CommonCrypto/CommonCrypto.h>
#import "AFNetworking.h"
@implementation YDAuthenticationHelper

static NSString * s_appSecret = nil;

+(void)registerApp:(NSString *)appSecret{
    s_appSecret = appSecret;
}

#pragma mark - 验证签名
+(void)authentication:(NSString *)Url
                 body:(NSDictionary *)body
              success:(GMXResponseSuccess)success
                 fail:(GMXResponseFail)fail{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.responseSerializer.acceptableContentTypes = nil;
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:Url]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json;charset=utf-8;multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    request.HTTPMethod = @"POST";
    NSError *error = nil;
    NSMutableDictionary * params = body.mutableCopy;
    [params setValue:[self createSignWith:params] forKey:@"sign"];
    [params setValue:[self getCurrentTimeMillisecond] forKey:@"timestamp"];
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error];;
    request.HTTPBody = jsonData;
    
    
    
    

    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary * dic = responseObject;
        if (dic == nil) {
            fail(error);
        }else{
            NSInteger code = [dic[@"code"] integerValue];
            if (code == 0) {
                success(dic);
            }else{
                fail(dic);
            }
        }
    }];
    [dataTask resume];
}

#pragma mark - H5签名拼接
+(NSURL *)jointUrlWithBody:(NSDictionary *)body
                       andUrl:(NSString *)urlStr{
    if ([self isNull:urlStr]) {
        NSLog(@"url不能为空");
        return nil;
    }
    NSMutableDictionary * params = body.mutableCopy;
    NSArray * keys = [params allKeys];
    for (NSString * key in keys) {
        NSString * value = [NSString stringWithFormat:@"%@",params[key]];
        if ([self isNull:value]) {
            [params removeObjectForKey:key];
        }
    }
    NSString * jsonStr = [self dictionaryToJsonString:params];
    urlStr = [self urlAddCompnentForValue:jsonStr key:@"data" url:urlStr];
    urlStr = [self urlAddCompnentForValue:@"iOS" key:@"platform" url:urlStr];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL * url = [NSURL URLWithString:urlStr];
    return url;
}

#pragma mark - NSDictionary转JsonString
+(NSString *)dictionaryToJsonString:(NSDictionary *)dicJson {
    if (![dicJson isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dicJson]) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}

#pragma mark - 生成签名
+(NSString *)createSignWith:(NSDictionary *)body{
    if ([self isNull:s_appSecret]) {
        NSLog(@"appSecret不能为空");
        return @"";
    }
    NSMutableDictionary * params = body.mutableCopy;
    for (NSString * key in [body allKeys]) {
        NSString * value = body[key];
        if ([self isNull:value]) {
            [params removeObjectForKey:key];
        }
    }
    [params setValue:[self getCurrentTimeMillisecond] forKey:@"timestamp"];
    NSArray * keys = [[self sortKeysWithArray:[params allKeys]] mutableCopy];
    NSString * tempStr = @"";
    for (int i = 0; i<keys.count; i++) {
        NSString * key = keys[i];
        NSString * value = params[key];
        tempStr = [NSString stringWithFormat:@"%@&%@=%@",tempStr,key,value];
    }
    tempStr = [NSString stringWithFormat:@"%@&key=%@",tempStr,s_appSecret];//key(appSecret)
    NSString * sign = [self MD5ForUpper32Bate:[tempStr substringFromIndex:1]];
    return sign;
}

#pragma mark - MD5加密 32位 大写
+ (NSString *)MD5ForUpper32Bate:(NSString *)str{
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }
    return digest;
}

#pragma mark - 获取当前时间戳
+(NSString *)getCurrentTimeMillisecond{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *dateNow = [NSDate date];
    NSString *currentTime = [formatter stringFromDate:dateNow];
    return currentTime;
}

#pragma mark - 对key进行ASC排序
+(NSArray *)sortKeysWithArray:(NSArray *)array{
    NSStringCompareOptions comparisonOptions =NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range =NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray2 = [array sortedArrayUsingComparator:sort];
    return resultArray2;
}

#pragma mark - 判断字符串是否为空
+ (BOOL)isNull:(id)object{
    if ([object isKindOfClass:[NSNumber class]]) {
        object = [NSString stringWithFormat:@"%@",object];
    }
    if ([object isKindOfClass:[NSDictionary class]]) {
        return NO;
    }
    // 判断是否为空串
    if ([object isEqual:[NSNull null]]) {
        return YES;
    }else if ([object isKindOfClass:[NSNull class]]){
        return YES;
    }else if (object==nil){
        return YES;
    }else if ([object isEqualToString:@"<null>"]){
        return YES;
    }else if ([object isEqualToString:@"null"]){
        return YES;
    }else if ([object isEqualToString:@"(null)"]){
        return YES;
    }else if ([object isEqualToString:@""]){
        return YES;
    }
    return NO;
}

#pragma mark - 拼接url
+(NSString *)urlAddCompnentForValue:(NSString *)value key:(NSString *)key url:(NSString *)url{
    NSMutableString *string = [[NSMutableString alloc]initWithString:url];
    @try {
        NSRange range = [string rangeOfString:@"?"];
        if (range.location != NSNotFound) {
            if (string.length == (range.location + range.length)) {
                string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
            }else{
                if([string hasSuffix:@"&"]){
                    string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
                }else{
                    string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,value]];
                }
            }
        }else{
            if([string hasSuffix:@"&"]){
                string = (NSMutableString *)[string substringToIndex:string.length-1];
            }
            string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"?%@=%@",key,value]];
        }
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    return string.copy;
}

+(NSURL*)changeURLSchemeStr:(NSString*)urlStr{
    NSString* tmpUrlStr = urlStr.copy;
    if([urlStr containsString:@"fromAppUrlScheme"]) {
        tmpUrlStr = [tmpUrlStr stringByRemovingPercentEncoding];
        NSDictionary* tmpDic = [self dictionaryWithUrlString:tmpUrlStr];
        NSString* tmpValue = [tmpDic valueForKey:@"fromAppUrlScheme"];
        tmpUrlStr = [[tmpUrlStr stringByReplacingOccurrencesOfString:tmpValue withString:@"YDWH5Alisafepay"] mutableCopy];
        tmpUrlStr = [[tmpUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] mutableCopy];
    }
    NSURL * newURl = [NSURL URLWithString:tmpUrlStr];
    return newURl;
}
+(NSDictionary*)dictionaryWithUrlString:(NSString*)urlStr{
    if(urlStr && urlStr.length&& [urlStr rangeOfString:@"?"].length==1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if(array && array.count==2) {
            NSString*paramsStr = array[1];
            if(paramsStr.length) {
                NSString* paramterStr = [paramsStr stringByRemovingPercentEncoding];
                NSData *jsonData = [paramterStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
                return responseDic;
            }
        }
    }
    return nil;
}

@end
