




#import "ACBridgeUtil.h"
#import "ACBaseJSConstant.h"
#import <WebKit/WebKit.h>

@interface ACBridgeUtil ()
@end

@implementation ACBridgeUtil

+ (void)webView:(id)webView callJsWithMessage:(ACMessage *)msg
{
    NSString *messageStr = [msg json];

    NSString *formatStr = [kACJSHandleMessageFormat copy];
    NSString *jsStr = [NSString stringWithFormat:formatStr,messageStr];
    
    [self webView:webView callJsWithString:jsStr];
}

+ (void)webView:(id)webView callJsWithString:(NSString *)jsStr
{
    if (![NSThread isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self webView:webView callJsWithString:jsStr completionHandler:nil];
        });
    }
    else {
        [self webView:webView callJsWithString:jsStr completionHandler:nil];
    }
}

+ (void)webView:(id)webView callJsWithString:(NSString *)jsStr completionHandler:(CompletionJSBlock)block
{
    void(^CallJSBlock)(void) = ^(void) {
        if ([webView isKindOfClass:[UIWebView class]]) {
            NSString *string = [(UIWebView *)webView stringByEvaluatingJavaScriptFromString:jsStr];
            if (block) {
                block(string);
            }
        }
        else if ([webView isKindOfClass:[WKWebView class]]) {
            [(WKWebView *)webView evaluateJavaScript:jsStr completionHandler:^(id obj, NSError * _Nullable error) {
                if (block) {
                    block(obj);
                }
            }];
        }
    };
    
    if (![NSThread isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            CallJSBlock();
        });
    }
    else {
        CallJSBlock();
    }
}

// @param msgJsonStr 属性 格式为 json 格式 eg： {"callbackId":"xxx","data":"xxxxx"}
+ (ACMessage *)convertStringToMessage:(NSString *)msgJsonStr
{
    ACMessage *message = [ACMessage new];
    
    // 获取native方法属性
    NSData *jsonData = [msgJsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *msgDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    NSString *callbackIdStr = msgDic[@"callbackId"];
    NSString *dataStr = msgDic[@"data"];
    
    if ([dataStr isKindOfClass:[NSNull class]]) {
        dataStr = nil;
    }
    NSDictionary *dataDic = nil;
    if (dataStr) {
        NSData *jsonData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    }
    
    message.callbackIdStr = callbackIdStr;
    message.dataDic = dataDic;
    
    return message;
}

@end
