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

#import "WebActionOC.h"

@implementation WebActionOC
+ (WebActionOC *)ShareWebActionOC{
    static WebActionOC *webActionOC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        webActionOC = [[WebActionOC alloc]init];
    });
    return webActionOC;
}
-(NSString *)getUrl:(NSString *)urlStr{
//    return [urlStr cStringUsingEncoding:NSUTF8StringEncoding];
//    return  [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

-(void)WeAction:(NSString *)message AndBody:(NSString *)body{
    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 *)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];
        
    }
}
//-(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
//    }
//}
@end
