//
//  WebActionOC.m
//  SYMobilePortal
//
//  Created by xiejiangbo on 2018/5/31.
//  Copyright © 2018年 yin chen. All rights reserved.
//

#import "WebActionOC.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

static NSString* const kInitVector = @"ABCDEF1234123412";
static NSString* const kAESkey = @"1234123412ABCDEF";

@implementation WebActionOC
+ (WebActionOC *)ShareWebActionOC{
    static WebActionOC *webActionOC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        webActionOC = [[WebActionOC alloc]init];
    });
    return webActionOC;
}
+ (WKProcessPool*)singleWkProcessPool{
    static WKProcessPool*sharedPool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedPool = [[WKProcessPool alloc]init];
    });
    return sharedPool;
}
///百分号解码
-(NSString *)decodingAction:(NSString *)str{
    return [str stringByRemovingPercentEncoding];
}
-(NSString *)getUrl:(NSString *)urlStr{
//    return [urlStr cStringUsingEncoding:NSUTF8StringEncoding];
//    return  [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`%^{}\"[]|\\<>() "].invertedSet];
//    return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

-(void)WeAction:(NSString *)message AndBody:(NSString *)body{
    if ([self getNilString:body]) {
        [SMAlertView showAlert:@"号码为空！"];
        return;
    }
    if ([message containsString:@"callPhone"]) {
//        NSRange range = [message rangeOfString:@"callPhone:"];//匹配得到的下标
//        message = [message substringFromIndex:range.length+range.location];
        [self openPhone:body];
    }
    if ([message containsString:@"sendSms"]) {
//        NSRange range = [message rangeOfString:@"callPhone:"];//匹配得到的下标
//        message = [message substringFromIndex:range.length+range.location];
        [self openPhoneMessage:body];
    }
}
#pragma mark ----- 拨打电话
-(void)openPhone:(NSString *)phoneUrl{
    
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", phoneUrl];
    callPhone = [self setMobileNumberProcessing:callPhone];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}
#pragma mark ----- 发送短信
-(void)openPhoneMessage:(NSString *)phoneUrl{
    NSString *callPhone = [NSString stringWithFormat:@"sms://%@", phoneUrl];
    callPhone = [self setMobileNumberProcessing:callPhone];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}
- (NSString *)getWebCookie:(NSString *)info{
//    return [NSString stringWithFormat:@"document.cookie = 'info=%@';",info];
//    LYLSLog(@"cookie=%@",info);
    if ([[AccountInfo sharedInstance].loginType isEqualToString:@"1"]) {
        return [NSString stringWithFormat:@"document.cookie = 'info=%@';",info];
    } else {
        return [NSString stringWithFormat:@"document.cookie = 'info=%@';",info];
    }
    
}
- (NSMutableString*)getCookieValue:(NSString *)cookie host:(NSString *)host{
    // 在此处获取返回的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];
    }
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieJar deleteCookie:cookie];
    }
//    NSArray * cookiesArray= [cookieJar cookies];
    // cookie重复，先放到字典进行去重，再进行拼接
    for (NSString *key in cookieDic) {
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
            [cookieValue appendString:appendString];
    }
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:@"info" forKey:NSHTTPCookieName];
    [cookieProperties setObject:cookie forKey:NSHTTPCookieValue];
    [cookieProperties setObject:host forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:host forKey:NSHTTPCookieOriginURL];
    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
    [cookieProperties setObject:@(NO) forKey:NSHTTPCookieSecure];
//    [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
    [cookieProperties setObject:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];//设置失效时间
//    [cookieProperties setObject:@"0" forKey:NSHTTPCookieDiscard]; //设置sessionOnly
    NSHTTPCookie *cookies = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [cookieJar setCookie:cookies];

    cookieDic = [NSMutableDictionary dictionary];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
    }
    NSLog(@"cookie==%@",cookie);
    NSString *appendString = [NSString stringWithFormat:@"info=%@;",cookie];
    [cookieValue appendString:appendString];
    return cookieValue;
}
+ (NSString *)ajaxCookieScripts {
    NSMutableString *cookieScript = [[NSMutableString alloc] init];
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        // Skip cookies that will break our script
        if ([cookie.value rangeOfString:@"'"].location != NSNotFound) {
            continue;
        }
        // Create a line that appends this cookie to the web view's document's cookies
        [cookieScript appendFormat:@"document.cookie='%@=%@;", cookie.name, cookie.value];
        if (cookie.domain || cookie.domain.length > 0) {
            [cookieScript appendFormat:@"domain=%@;", cookie.domain];
        }
        if (cookie.path || cookie.path.length > 0) {
            [cookieScript appendFormat:@"path=%@;", cookie.path];
        }
        if (cookie.expiresDate) {
            [cookieScript appendFormat:@"expires=%@;", [NSDate dateWithTimeIntervalSinceNow:60*60]];
        }
        
        if (cookie.secure) {
            // 只有 https 请求才能携带该 cookie
            [cookieScript appendString:@"Secure;"];
        }
        if (cookie.HTTPOnly) {
            // 保持 native 的 cookie 完整性，当 HTTPOnly 时，不能通过 document.cookie 来读取该 cookie。
            [cookieScript appendString:@"HTTPOnly;"];
        }
        [cookieScript appendFormat:@"'\n"];
    }
    
    return cookieScript;
}
+ (NSMutableURLRequest *)syncRequestCookie:(NSMutableURLRequest *)request {
    if (!request.URL) {
        return request;
    }
    NSMutableURLRequest *requestTwo = (NSMutableURLRequest *)request;
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSDictionary *dict = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    requestTwo.allHTTPHeaderFields = dict;
    return requestTwo;
}
-(NSString *)setMobileNumberProcessing:(NSString *)phone{
    if ([phone rangeOfString:@" "].location != NSNotFound) {
        phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    if ([phone rangeOfString:@"+86"].location != NSNotFound) {
        phone = [phone stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    }
    if ([phone rangeOfString:@"("].location != NSNotFound) {
        NSRange starRange = [phone rangeOfString:@"("];
        NSRange endRange = [phone rangeOfString:@")"];
        NSRange range = NSMakeRange(starRange.location + starRange.length, endRange.location - starRange.location - starRange.length);
        phone = [phone stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"(%@)",[phone substringWithRange:range]] withString:@""];
    }
    if ([phone rangeOfString:@"-"].location != NSNotFound) {
        phone = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    return phone;
}
- (void)openApp:(NSString *)openAppUrl {
    // 1.获取应用程序App-B的URL Scheme
    NSURL *URL = [NSURL URLWithString:openAppUrl];
    UIApplication *application = [UIApplication sharedApplication];
    // 2.判断手机中是否安装了对应程序
    if ([[UIApplication sharedApplication] canOpenURL:URL]) {
        // 3. 打开应用程序App-B
        if([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
            if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                if (@available(iOS 10.0, *)) {
                    [application openURL:URL options:@{}
                       completionHandler:^(BOOL success) {
                           NSLog(@"Open: %d",success);
                       }];
                } else {
                    // Fallback on earlier versions
                }
            } else {
                BOOL success = [application openURL:URL];
                NSLog(@"Open: %d",success);
            }
        }
        else{
            bool can = [application canOpenURL:URL];
            if(can){
                [application openURL:URL];
            }
        }
    } else {
        NSLog(@"没有安装");
    }
}
-(void)clearCache{
    if ([[[UIDevice currentDevice]systemVersion]intValue ] >= 9.0) {
        if (@available(iOS 9.0, *)) {
            NSArray *array = @[WKWebsiteDataTypeDiskCache,//磁盘缓存
                               WKWebsiteDataTypeOfflineWebApplicationCache,//HTML离线Web应用程序缓存
                               WKWebsiteDataTypeMemoryCache,//内存中的缓存
                               WKWebsiteDataTypeLocalStorage,//HTML本地存储
                               WKWebsiteDataTypeCookies,//Cookies 缓存
                               WKWebsiteDataTypeSessionStorage,//HTML会话存储
                               WKWebsiteDataTypeIndexedDBDatabases,//IndexedDB数据库
                               WKWebsiteDataTypeWebSQLDatabases];//WebSQL数据库
//            NSArray * array =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
            NSSet *websiteDataTypes = [NSSet setWithArray:array];
            NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
            
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
                
            }];
        } else {
            // Fallback on earlier versions
        }
    }else{
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
}
- (BOOL)getNilString:(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;
}
//-(void)setNSURLProtocolCustom{
//    //2.注册
//    //[NSURLProtocol registerClass:[NSURLProtocolCustom class]];
//    //3.实现拦截功能，这个是核心
//    Class cls = NSClassFromString(@"WKBrowsingContextController");
//    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
//    if ([(id)cls respondsToSelector:sel]) {
//#pragma clang diagnostic push
//#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//        [(id)cls performSelector:sel withObject:@"http"];
//        [(id)cls performSelector:sel withObject:@"https"];
//#pragma clang diagnostic pop
//    }
//}
/// 加密
- (NSString *)encryptAES:(NSString *)content key:(NSString *)key {
    if ([self getNilString:key]) {
        key = kAESkey;
    }
    size_t const kKeySize = kCCKeySizeAES128;
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = contentData.length;
    
    // 为结束符'\0' +1
    char keyPtr[kKeySize + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    // 密文长度 <= 明文长度 + BlockSize
    size_t encryptSize = dataLength + kCCBlockSizeAES128;
    void *encryptedBytes = malloc(encryptSize);
    size_t actualOutSize = 0;
    
    NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,  // 系统默认使用 CBC，然后指明使用 PKCS7Padding
                                          keyPtr,
                                          kKeySize,
                                          initVector.bytes,
                                          contentData.bytes,
                                          dataLength,
                                          encryptedBytes,
                                          encryptSize,
                                          &actualOutSize);
    
    if (cryptStatus == kCCSuccess) {
        // 对加密后的数据进行 base64 编码
        
        return [[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    free(encryptedBytes);
    return nil;
}
/// 解密
-(NSString *)decryptAES:(NSString *)content key:(NSString *)key {
    // 把 base64 String 转换成 Data
    size_t const kKeySize = kCCKeySizeAES128;
    NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSUInteger dataLength = contentData.length;
    
    char keyPtr[kKeySize + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    size_t decryptSize = dataLength + kCCBlockSizeAES128;
    void *decryptedBytes = malloc(decryptSize);
    size_t actualOutSize = 0;
    
    NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kKeySize,
                                          initVector.bytes,
                                          contentData.bytes,
                                          dataLength,
                                          decryptedBytes,
                                          decryptSize,
                                          &actualOutSize);
    
    if (cryptStatus == kCCSuccess) {
        return [[NSString alloc] initWithData:[NSData dataWithBytesNoCopy:decryptedBytes length:actualOutSize] encoding:NSUTF8StringEncoding];
    }
    free(decryptedBytes);
    return nil;
}
/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    // 查找参数
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}
/// 字典转字符串
- (NSString *)getDictStr:(NSMutableDictionary *)dic{
    NSString *parametersValue = @"";
    for (NSString *key in dic) {
        if (![key isEqualToString:@"filename"]) {
            NSString *appendString = [NSString stringWithFormat:@"%@=%@&", key, [dic valueForKey:key]];
            parametersValue = [NSString stringWithFormat:@"%@%@",parametersValue,appendString];
        }
    }
    return parametersValue;
}
- (NSString *)getUrlStr:(NSURL *)url{
    return [NSString stringWithFormat:@"%@",url];
}
@end
